diff --git a/docs/sdk/sdk-parity-manifest.json b/docs/sdk/sdk-parity-manifest.json index ff3277332c9..2538c99676b 100644 --- a/docs/sdk/sdk-parity-manifest.json +++ b/docs/sdk/sdk-parity-manifest.json @@ -54,6 +54,7 @@ "platform_wallet_get_private_pair_held": "packages/rs-platform-wallet-ffi/src/private_contact_request.rs", "platform_wallet_get_private_payments_restore_failure": "packages/rs-platform-wallet-ffi/src/private_contact_request.rs", "platform_wallet_get_public_contact_request_unconfirmed": "packages/rs-platform-wallet-ffi/src/private_contact_request.rs", + "platform_wallet_invitation_claim_status_for_identity": "packages/rs-platform-wallet-ffi/src/invitation.rs", "platform_wallet_manager_accept_contact_request_replying_in_kind": "packages/rs-platform-wallet-ffi/src/private_contact_request.rs", "platform_wallet_manager_accept_private_contact_request": "packages/rs-platform-wallet-ffi/src/private_contact_request.rs", "platform_wallet_manager_create_with_persistence_capabilities": "packages/rs-platform-wallet-ffi/src/manager.rs", @@ -662,6 +663,47 @@ } ] }, + { + "id": "dashpay.invitation_claim_status_for_identity", + "title": "Invitation claim status tells whether this wallet made the claim", + "area": "shared-policy", + "shared_apis": [ + "platform_wallet_invitation_claim_status_for_identity" + ], + "required_persistence_capabilities": [], + "hosts": { + "swift": { + "sdk": "supported", + "example_app": "not-applicable", + "restart": "not_applicable", + "reason": null + }, + "kotlin": { + "sdk": "unsupported", + "example_app": "not-applicable", + "restart": "not_applicable", + "reason": "The JNI exposes neither the invitation claim status nor its wallet-aware variant; Android can read the claim's typed outcomes (codes 63-66) but cannot ask before claiming. Bridge platform_wallet_invitation_claim_status_for_identity when an Android caller needs it." + } + }, + "verification": [ + { + "host": "swift", + "kind": "unit", + "file": "packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift", + "id": "testShouldDecodeWhoseInvitationClaimItWas", + "command": "cd packages/swift-sdk && xcodebuild test -scheme SwiftDashSDK -destination 'platform=iOS Simulator,name=iPhone 17 Pro' -only-testing:SwiftDashSDKTests/ErrorHandlingTests", + "covers_restart": false + }, + { + "host": "shared", + "kind": "unit", + "file": "packages/rs-platform-wallet/src/wallet/identity/network/invitation.rs", + "id": "should_resolve_the_master_key_only_for_a_claimed_invitation", + "command": "cargo test -p platform-wallet --all-features --lib invitation", + "covers_restart": false + } + ] + }, { "id": "core.provider_restore", "title": "Provider special transactions restore with wallet ownership", diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ClaimInvitationSheet.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ClaimInvitationSheet.kt index 9857acaa653..6dd6207bfaf 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ClaimInvitationSheet.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ClaimInvitationSheet.kt @@ -25,11 +25,14 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import org.dashfoundation.dashsdk.errors.DashSdkError import org.dashfoundation.dashsdk.identity.RegistrationKeys import org.dashfoundation.dashsdk.tokens.InvitationPreview +import org.dashfoundation.dashsdk.wallet.PlatformWalletManager import org.dashfoundation.example.di.LocalAppContainer import org.dashfoundation.example.di.LocalAppState import org.dashfoundation.example.services.DashpayKeyProvisioning +import org.dashfoundation.example.util.Base58 import org.dashfoundation.example.util.toHex /** @@ -162,13 +165,47 @@ fun ClaimInvitationSheet( ) }, ) - mgr.identityRegistration.claimInvitation( - walletHandle = wallet.handle, - uri = uri, - identityIndex = identityIndex, - keys = keySet, - signerHandle = mgr.signerHandle, - ) + try { + mgr.identityRegistration.claimInvitation( + walletHandle = wallet.handle, + uri = uri, + identityIndex = identityIndex, + keys = keySet, + signerHandle = mgr.signerHandle, + ) + } catch (e: DashSdkError.PlatformWallet.InvitationClaimedByThisWallet) { + // The invitation's identity is this wallet's: one it + // records, or one an earlier claim at this index + // created without recording it, which is loaded like + // any identity of this wallet. Only the identity the + // error names counts. + val claimedId = Base58.decodeIdentifier(e.identityId) ?: throw e + walletOwned.firstOrNull { + it.walletId?.contentEquals(wallet.walletId) == true && + it.identityId.contentEquals(claimedId) + }?.identityId + ?: identityAt(wallet.handle, mgr, identityIndex) { cause -> + "This invitation already created identity ${e.identityId} " + + "in this wallet, but loading it failed: $cause. Try again." + }?.takeIf { it.contentEquals(claimedId) } + ?: throw e + } catch (e: DashSdkError.PlatformWallet.InvitationKeysAlreadyRegistered) { + // The keys at this index belong to an identity. When + // it is this wallet's own, unrecorded one, loading it + // records it, and the next claim takes the next index. + // Any other owner keeps the refusal. + val owner = e.identityId ?: throw e + val ownerId = Base58.decodeIdentifier(owner) ?: throw e + val loaded = identityAt(wallet.handle, mgr, identityIndex) { cause -> + "Identity $owner holds these keys, but checking whether it " + + "is this wallet's failed: $cause. Try again." + } + if (loaded?.contentEquals(ownerId) != true) throw e + throw ClaimRecoveryMessage( + "Identity $owner of this wallet already used these keys and " + + "is now loaded. Claim again once it is listed.", + ) + } } val username = preview.inviterUsername if (username != null) { @@ -177,7 +214,13 @@ fun ClaimInvitationSheet( onClose() } } catch (t: Throwable) { - errorMessage = t.message ?: "Claiming the invitation failed." + errorMessage = when (t) { + is DashSdkError.PlatformWallet.InvitationClaimedByThisWallet -> + "This invitation already created identity ${t.identityId} in this wallet. " + + "If it is not listed, try Search Wallets for Identities." + is ClaimRecoveryMessage -> t.message + else -> t.message ?: "Claiming the invitation failed." + } } finally { isClaiming = false appUiState.invitationClaimInFlight.value = false @@ -315,3 +358,29 @@ fun ClaimInvitationSheet( ) } } + + +/** + * Loads this wallet's identity at [identityIndex], recording it. A failed + * load is thrown as [ClaimRecoveryMessage] built by [failure] from its cause. + */ +private suspend fun identityAt( + walletHandle: Long, + mgr: PlatformWalletManager, + identityIndex: Int, + failure: (String) -> String, +): ByteArray? = try { + mgr.identityRegistration.loadIdentityAtIndex( + walletHandle = walletHandle, + mnemonicResolverHandle = mgr.mnemonicResolverHandle, + identityIndex = identityIndex, + ) +} catch (e: Exception) { + throw ClaimRecoveryMessage(failure(e.message ?: e.javaClass.simpleName), e) +} + +/** A recovery outcome of the claim, shown to the user as is. */ +private class ClaimRecoveryMessage( + override val message: String, + cause: Throwable? = null, +) : Exception(message, cause) diff --git a/packages/kotlin-sdk/PARITY_SUMMARY.md b/packages/kotlin-sdk/PARITY_SUMMARY.md index 4f8eef43841..8bb6f51b2b1 100644 --- a/packages/kotlin-sdk/PARITY_SUMMARY.md +++ b/packages/kotlin-sdk/PARITY_SUMMARY.md @@ -2,23 +2,23 @@ # Kotlin/Swift executable parity summary Audit baseline: `PR #3999 @ 6dbc72a54df72d26eb9c4a014b425d2b95134e4e` -Capabilities tracked: **30** +Capabilities tracked: **31** ## Status counts | Host | Surface | Supported | Partial | Unsupported | Not applicable | | --- | --- | ---: | ---: | ---: | ---: | -| Swift | SDK | 17 | 11 | 1 | 1 | -| Swift | Example app | 5 | 14 | 2 | 9 | -| Kotlin | SDK | 14 | 14 | 1 | 1 | -| Kotlin | Example app | 6 | 13 | 1 | 10 | +| Swift | SDK | 18 | 11 | 1 | 1 | +| Swift | Example app | 5 | 14 | 2 | 10 | +| Kotlin | SDK | 14 | 14 | 2 | 1 | +| Kotlin | Example app | 6 | 13 | 1 | 11 | ## Restart coverage | Host | Tested | Required | Not applicable | | --- | ---: | ---: | ---: | -| Swift | 2 | 10 | 18 | -| Kotlin | 5 | 8 | 17 | +| Swift | 2 | 10 | 19 | +| Kotlin | 5 | 8 | 18 | ## Capability status @@ -31,6 +31,7 @@ Capabilities tracked: **30** | `tokens.full_u64_domain` | partial / partial / required | supported / supported / tested | | `shielded.seedless_restart` | supported / partial / required | partial / partial / required | | `dashpay.invitations` | supported / partial / required | supported / partial / required | +| `dashpay.invitation_claim_status_for_identity` | supported / not-applicable / not_applicable | unsupported / not-applicable / not_applicable | | `core.provider_restore` | supported / partial / required | partial / partial / required | | `dashpay.deferred_contact_crypto` | partial / partial / required | partial / partial / required | | `dashpay.private_contact_requests` | partial / partial / required | partial / partial / required | diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt index 91547fb3e1d..a1247b88bc1 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt @@ -259,6 +259,57 @@ sealed class DashSdkError( class AssetLockRecipientMismatch(message: String, cause: Throwable? = null) : PlatformWallet(message, cause) + /** + * Code 63: a key of the DashPay invitation claim is already + * registered to another identity ([identityId], base58; `null` when + * Platform refused the broadcast without naming it). Definitive for + * these keys. + */ + class InvitationKeysAlreadyRegistered( + val identityId: String?, + cause: Throwable? = null, + ) : PlatformWallet( + if (identityId == null) { + "A key of this invitation claim is already registered to another identity." + } else { + "A key of this invitation claim is already registered to identity $identityId." + }, + cause, + ) + + /** + * Code 64: the invitation's identity ([identityId], base58) is this + * wallet's: it holds the claim's master key (an earlier claim landed) + * or the wallet already records it. Nothing was recorded, and nothing + * was broadcast unless a node that lagged behind let the claim + * through; load the identity like any of the wallet's own. + */ + class InvitationClaimedByThisWallet( + val identityId: String, + cause: Throwable? = null, + ) : PlatformWallet( + "This invitation was already claimed by this wallet as identity $identityId.", + cause, + ) + + /** + * Code 65: the invitation claim could not verify Platform's answers + * yet. Nothing was broadcast; retry once synced. + */ + class InvitationNotReady(message: String, cause: Throwable? = null) : + PlatformWallet(message, cause) { + override val isRetryable: Boolean get() = true + } + + /** + * Code 66: the asset lock is not usable yet (not propagated, or not + * chain-locked for a ChainLock proof). Retry later. + */ + class AssetLockNotChainLocked(message: String, cause: Throwable? = null) : + PlatformWallet(message, cause) { + override val isRetryable: Boolean get() = true + } + /** * `ErrorShieldedNoRecordedAnchor` (native code 19). A shielded spend * could not be built against a Platform-recorded anchor because the @@ -922,6 +973,24 @@ sealed class DashSdkError( 29 -> PlatformWallet.AssetLockInsufficientFunds(message, cause) // ErrorAssetLockInsufficientFunds 60 -> PlatformWallet.AssetLockTooManyInputs(message, cause) // ErrorAssetLockTooManyInputs 61 -> PlatformWallet.AssetLockRecipientMismatch(message, cause) // ErrorAssetLockRecipientMismatch + 63 -> parseErrorDetail(message)?.let { detail -> + runCatching { + PlatformWallet.InvitationKeysAlreadyRegistered( + identityId = detail.optionalString("identityId"), + cause = cause, + ) + }.getOrNull() + } ?: PlatformWallet.Generic(code, message, cause) + 64 -> parseErrorDetail(message)?.let { detail -> + runCatching { + PlatformWallet.InvitationClaimedByThisWallet( + identityId = requireNotNull(detail.optionalString("identityId")), + cause = cause, + ) + }.getOrNull() + } ?: PlatformWallet.Generic(code, message, cause) + 65 -> PlatformWallet.InvitationNotReady(message, cause) // ErrorInvitationNotReady + 66 -> PlatformWallet.AssetLockNotChainLocked(message, cause) // ErrorAssetLockNotChainLocked // The deferred-token trio sits at the contiguous block 34-36 because // 27-33 are claimed elsewhere: 27 ErrorShutdownIncomplete // (dashpay/platform#4268, merged), 29 ErrorAssetLockInsufficientFunds @@ -932,7 +1001,7 @@ sealed class DashSdkError( 35 -> PlatformWallet.ReservationTokenConsumed(message, cause) // ErrorReservationTokenConsumed 36 -> PlatformWallet.ReservationWalletMismatch(message, cause) // ErrorReservationWalletMismatch 37 -> PlatformWallet.DocumentNotForSale(message, cause) - 38 -> parseMarketplaceDetail(message)?.let { detail -> + 38 -> parseErrorDetail(message)?.let { detail -> runCatching { PlatformWallet.DocumentPriceChanged( documentId = detail.getString("documentId"), @@ -942,7 +1011,7 @@ sealed class DashSdkError( ) }.getOrNull() } ?: PlatformWallet.Generic(code, message, cause) - 39 -> parseMarketplaceDetail(message)?.let { detail -> + 39 -> parseErrorDetail(message)?.let { detail -> runCatching { PlatformWallet.InsufficientIdentityCredits( identityId = detail.getString("identityId"), @@ -952,7 +1021,7 @@ sealed class DashSdkError( ) }.getOrNull() } ?: PlatformWallet.Generic(code, message, cause) - 40 -> parseMarketplaceDetail(message)?.let { detail -> + 40 -> parseErrorDetail(message)?.let { detail -> runCatching { PlatformWallet.ContestedNameNotTradable( label = detail.getString("label"), @@ -1017,11 +1086,15 @@ sealed class DashSdkError( private fun isSigningKeyUnavailable(message: String): Boolean = message.contains(PlatformWallet.SigningKeyUnavailable.MESSAGE_MARKER) - private fun parseMarketplaceDetail(message: String): JSONObject? = + private fun parseErrorDetail(message: String): JSONObject? = runCatching { JSONObject(message) }.getOrNull() private fun JSONObject.requiredULong(name: String): ULong = get(name).toString().toULong() + + /** A string, or `null` when the key is JSON `null` or absent. */ + private fun JSONObject.optionalString(name: String): String? = + if (isNull(name)) null else requireNotNull(get(name) as? String) { "$name is not a string" } } } diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/IdentityNative.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/IdentityNative.kt index 3e6b8114b6b..2fefa404506 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/IdentityNative.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/IdentityNative.kt @@ -254,6 +254,17 @@ internal object IdentityNative { inputsBlob: ByteArray, ): ByteArray + /** + * Load the identity registered for this wallet at [identityIndex], + * recording it like discovery does. Returns its 32-byte id, or an + * empty array when no identity is registered at that index. + */ + external fun loadIdentityAtIndex( + walletHandle: Long, + resolverHandle: Long, + identityIndex: Int, + ): ByteArray + /** * Scan the wallet's identity-authentication tree for registered * identities (gap-limit walk, Rust-side). Returns the concatenated diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/identity/IdentityRegistration.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/identity/IdentityRegistration.kt index b8c4cd647f4..c7997348ccd 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/identity/IdentityRegistration.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/identity/IdentityRegistration.kt @@ -463,6 +463,24 @@ class IdentityRegistration internal constructor( } } + /** + * Load the identity registered for this wallet at [identityIndex] and + * record it like discovery does. Returns its 32-byte id, or `null` when + * no identity is registered there; throws when Platform does not + * answer. Mirrors Swift `ManagedPlatformWallet.loadIdentity(atIndex:)`. + */ + suspend fun loadIdentityAtIndex( + walletHandle: Long, + mnemonicResolverHandle: Long, + identityIndex: Int, + ): ByteArray? = gate.op { + require(identityIndex >= 0) { "identityIndex must be non-negative, got $identityIndex" } + val id = mapNativeErrors { + IdentityNative.loadIdentityAtIndex(walletHandle, mnemonicResolverHandle, identityIndex) + } + id.takeIf { it.size == 32 } + } + /** * Scan the wallet for registered identities (gap-limit walk). Returns * the discovered 32-byte identity ids. diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/InvitationClaimErrorTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/InvitationClaimErrorTest.kt new file mode 100644 index 00000000000..2662a71d294 --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/InvitationClaimErrorTest.kt @@ -0,0 +1,46 @@ +package org.dashfoundation.dashsdk.errors + +import org.dashfoundation.dashsdk.ffi.DashSDKException +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +/** Codes 63-66 from the DashPay invitation claim (`rs-platform-wallet-ffi/src/error.rs`). */ +@RunWith(RobolectricTestRunner::class) +class InvitationClaimErrorTest { + @Test + fun shouldPreserveInvitationClaimOutcomes() { + val id = "8eTDkBhpQjHeqgbVeriwLeZr1tCa6yBGw76SckvD1cwc" + fun map(code: Int, message: String) = + DashSdkError.fromNative(DashSDKException(DashSdkError.PLATFORM_WALLET_CODE_OFFSET + code, message)) + + val taken = map(63, "{\"identityId\":\"$id\"}") + assertTrue(taken is DashSdkError.PlatformWallet.InvitationKeysAlreadyRegistered) + assertEquals(id, (taken as DashSdkError.PlatformWallet.InvitationKeysAlreadyRegistered).identityId) + assertFalse(taken.isRetryable) + + val takenByUnknown = map(63, "{\"identityId\":null}") + assertTrue(takenByUnknown is DashSdkError.PlatformWallet.InvitationKeysAlreadyRegistered) + assertNull((takenByUnknown as DashSdkError.PlatformWallet.InvitationKeysAlreadyRegistered).identityId) + + val ours = map(64, "{\"identityId\":\"$id\"}") + assertTrue(ours is DashSdkError.PlatformWallet.InvitationClaimedByThisWallet) + assertEquals(id, (ours as DashSdkError.PlatformWallet.InvitationClaimedByThisWallet).identityId) + + // 64 always names its identity; a payload without one stays generic. + assertTrue(map(64, "{\"identityId\":null}") is DashSdkError.PlatformWallet.Generic) + assertTrue(map(64, "{}") is DashSdkError.PlatformWallet.Generic) + assertTrue(map(63, "not json") is DashSdkError.PlatformWallet.Generic) + + val notReady = map(65, "quorum not verified") + assertTrue(notReady is DashSdkError.PlatformWallet.InvitationNotReady) + assertTrue(notReady.isRetryable) + val notChainLocked = map(66, "retry later") + assertTrue(notChainLocked is DashSdkError.PlatformWallet.AssetLockNotChainLocked) + assertTrue(notChainLocked.isRetryable) + } +} diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/identity/IdentityLoadAtIndexTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/identity/IdentityLoadAtIndexTest.kt new file mode 100644 index 00000000000..8de9be7238c --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/identity/IdentityLoadAtIndexTest.kt @@ -0,0 +1,23 @@ +package org.dashfoundation.dashsdk.identity + +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Wrapper-seam tests for [IdentityRegistration.loadIdentityAtIndex]. */ +class IdentityLoadAtIndexTest { + + @Test + fun `load rejects a negative identity index before JNI`() = runTest { + // JVM tests never load the JNI library, so reaching the native call + // would fail with UnsatisfiedLinkError instead. + val failure = runCatching { + IdentityRegistration().loadIdentityAtIndex( + walletHandle = 1, + mnemonicResolverHandle = 2, + identityIndex = -1, + ) + } + assertTrue(failure.exceptionOrNull() is IllegalArgumentException) + } +} diff --git a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md index a5655430abd..146ed0ef26f 100644 --- a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md +++ b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md @@ -127,7 +127,7 @@ renumbered from 59 when #5322 took that number on `v5.1-dev`); 61 proposed by #5603 for `ErrorAssetLockRecipientMismatch`; 62–67 held by open branches with no row here yet (62 both `ErrorShieldedClaimBindingMismatch` and `ErrorIdentityRevisionMismatch`, -63–66 the invitation-claim preflight, 67 `ErrorShieldedTreeInconsistent`); 68 +63–66 the invitation-claim preflight, #5536, whose rows are below; 67 `ErrorShieldedTreeInconsistent`); 68 to 76 proposed for DashPay private contact requests; 28, 30, 32 and 33 reserved). **28, 30, 32 and 33 are RESERVED, not free**: 28 and 30 were vacated when the @@ -183,6 +183,10 @@ Fork-era numbers remain in the collision history, which is immutable record. | 59 | `ErrorSpvProcessRestartRequired` | #5322 | Proposed — SPV startup or teardown panicked; restart the host process. Not retryable, unlike 27, which SPV start, stop and storage clear now return while an SPV teardown is still running. Typed in Rust, Swift and Kotlin (the PR also types 27 on Kotlin) | | 60 | `ErrorAssetLockTooManyInputs` | Core-to-shielded pooled Max | Proposed — an asset lock needs more inputs than one may carry (100 on Dash Core relay policy, and in Platform consensus for an instant proof): the full drain, or since #5712 a fixed amount held only in many small coins (identity registration, top-up, invitation, platform-address funding). Two meanings. On a build: nothing was broadcast, the reservation is released, no partial drain, and a rebuild after consolidating is safe. On the resume of a tracked `Built` / `Broadcast` lock over the cap (since #5714): it is not re-sent, but an earlier attempt may have reached peers; the row stays tracked and nothing is released. Rust, Swift and Kotlin retain the typed refusal. Renumbered from 59 after #5322 claimed it | | 61 | `ErrorAssetLockRecipientMismatch` | dashpay/platform#5603 (tracked-lock shielded recipient) | Proposed — a shielded fund-from-asset-lock resume (the generic outpoint resume or a repeated-UUID wallet drain) names a different Orchard recipient than the one the tracked lock recorded when it was built. Nothing was submitted or paid; resume with the recorded recipient, which the row and `TrackedAssetLockFFI` expose. Rows tracked before recipients were recorded carry none and accept the caller's. Typed in Rust, Swift and Kotlin | +| 63 | `ErrorInvitationKeysAlreadyRegistered` | #5536 | Proposed — a key of the invitation claim is already registered to another identity, so Platform would refuse the claim and charge the voucher; nothing broadcast when the preflight found it; also reported from Platform's 40207/10501 refusal after a lagging node let the claim through, with that refusal in `consensus_code`/`consensus_kind`. Message is the JSON detail `{"identityId":""\|null}`. Rust value + pin test, Swift raw case + `init(ffi:)` arm + typed `invitationKeysAlreadyRegistered` + `ErrorHandlingTests` pin, Kotlin typed `PlatformWallet.InvitationKeysAlreadyRegistered` + `fromPlatformWalletNative` arm + `InvitationClaimErrorTest` pin | +| 64 | `ErrorInvitationClaimedByThisWallet` | #5536 | Proposed — the invitation's identity exists and holds the claim's master key (an earlier claim of this wallet landed) or the wallet already records it; not recorded, and not broadcast unless a lagging node let the claim through (then reported from Platform's consumed-outpoint refusal); the host loads the identity. Message is the JSON detail `{"identityId":""}`. Same three-layer mirrors as 63 | +| 65 | `ErrorInvitationNotReady` | #5536 | Proposed — the claim's identity lookups could not be verified yet (quorum source not ready); nothing broadcast, retry once synced. Same three-layer mirrors as 63 | +| 66 | `ErrorAssetLockNotChainLocked` | #5536 | Proposed — maps `PlatformWalletError::AssetLockNotChainLocked`, which used to flatten to 99: the asset lock is not usable yet (funding tx not propagated, or not chain-locked for a ChainLock proof). Only the invitation claim produces it today. Retryable. Same three-layer mirrors as 63 | | 68 | `ErrorPrivateContactRequestNeedsPrivateReply` | DashPay private contact requests | Proposed. The contact requests with that identity came or went privately (protocol version 15), so a `contactRequest` document to it, in reply or as a rotation, would publish the relationship: the public accept refuses a reply, and the public send refuses a request or a rotation. Nothing was sent; the request goes privately instead, and the in-kind accept picks the private reply itself. The shielded spend contract (`map_spend_result`) keeps the code, as the in-kind accept can raise it. Taken above 61–67, which open branches already hold. Returned by the public send and accept; the host sends with `platform_wallet_manager_send_private_contact_request`, or accepts with `platform_wallet_manager_accept_contact_request_replying_in_kind` (which picks the reply itself, so a host calling it does not route on 68) or `platform_wallet_manager_accept_private_contact_request`. Swift types it (`PlatformWalletError.privateContactRequestNeedsPrivateReply`, `ErrorHandlingTests` pin); Kotlin types it (`DashSdkError.PlatformWallet.PrivateContactRequestNeedsPrivateReply`, `DashSdkErrorTest` pin) | | 69 | `ErrorShieldedBuildRequired` | DashPay private contact requests | Proposed. The operation needs the shielded pool and the library was built without the `shielded` feature: accepting in kind a request that came privately, whose private reply is paid from the pool. Nothing was sent; a public or adopted reply works on such a build. Not retryable on the same build. No existing code meant "shielded unsupported" (`ErrorWalletOperation` with a not-configured message is a runtime state of a shielded build), so it takes the next free number. Returned by `platform_wallet_manager_accept_contact_request_replying_in_kind`, exported in every build. Swift types it (`PlatformWalletError.shieldedBuildRequired`, `ErrorHandlingTests` pin); Kotlin types it (`DashSdkError.PlatformWallet.ShieldedBuildRequired`, `DashSdkErrorTest` pin) | | 70 | `ErrorProtocolVersionNotActive` | DashPay private contact requests | Proposed. The SDK refused a request without sending it (`dash_sdk::Error::ProtocolVersionNotActive`, not pinned) because the network is proven at a protocol version below the one that serves it: for example the private contact request sync on a network before protocol version 15. Expected on such a network, so a host may stay quiet about it; it lifts when the network upgrades. An SDK pinned below the required version has its own code, 75. Mapped by the blanket conversion for every operation that propagates the SDK error. A refusal that may lift sooner (`is_transient_protocol_version_refusal`: the network's version could not be confirmed) keeps the catch-all `ErrorUnknown`, as before. Previously both fell to `ErrorUnknown`. Swift types it (`PlatformWalletError.protocolVersionNotActive`, `ErrorHandlingTests` pin) and SwiftExampleApp keeps a refresh quiet on it; Kotlin types it (`DashSdkError.PlatformWallet.ProtocolVersionNotActive`, `DashSdkErrorTest` pin) and KotlinExampleApp keeps a refresh quiet on it | diff --git a/packages/rs-platform-wallet-ffi/src/error.rs b/packages/rs-platform-wallet-ffi/src/error.rs index 58194bf7197..ba8087646ba 100644 --- a/packages/rs-platform-wallet-ffi/src/error.rs +++ b/packages/rs-platform-wallet-ffi/src/error.rs @@ -656,6 +656,41 @@ pub enum PlatformWalletFFIResultCode { /// carry none and accept the caller's. ErrorAssetLockRecipientMismatch = 61, + /// Maps `PlatformWalletError::InvitationKeysAlreadyRegistered`. A key of + /// the DashPay invitation claim is already registered to another + /// identity (usually one this wallet registered before at the same + /// index), so Platform would refuse the claim and charge the voucher. + /// Definitive for these keys. + /// + /// Message: a STABLE JSON detail object — + /// `{"identityId":""}`, or `{"identityId":null}` when Platform + /// refused the broadcast and the owner is unknown. Swift mirror: + /// `PlatformWalletError.invitationKeysAlreadyRegistered`. + ErrorInvitationKeysAlreadyRegistered = 63, + + /// Maps `PlatformWalletError::InvitationClaimedByThisWallet`. The + /// invitation's identity exists and holds this claim's master key: an + /// earlier claim of this wallet landed (or the wallet already records the + /// identity). Nothing was recorded, and nothing was broadcast unless a + /// node that lagged behind let the claim through; load the identity as + /// any of the wallet's own. + /// + /// Message: a STABLE JSON detail object — `{"identityId":""}`. + /// Swift mirror: `PlatformWalletError.invitationClaimedByThisWallet`. + ErrorInvitationClaimedByThisWallet = 64, + + /// Maps `PlatformWalletError::InvitationNotReady`. The invitation + /// claim's identity lookups could not be verified yet (the trusted + /// quorum source is not ready), so nothing was broadcast. Retry once the + /// wallet has synced. + ErrorInvitationNotReady = 65, + + /// Maps `PlatformWalletError::AssetLockNotChainLocked`. The asset lock + /// cannot be used yet: its transaction has not reached the queried node, + /// or it needs a ChainLock proof and is not chain-locked yet. Retry + /// later. Produced today by the DashPay invitation claim. + ErrorAssetLockNotChainLocked = 66, + /// Maps `PlatformWalletError::PrivateContactRequestNeedsPrivateReply`: /// the contact requests with that identity came or went privately /// (protocol version 15), so a public `contactRequest` to it, in reply or @@ -889,6 +924,20 @@ impl PlatformWalletFFIResult { } } + /// Platform's own verdict, for the variants that still hold the SDK + /// error it arrived in (`Sdk`, `TokenOperationFailed`, and + /// `InvitationKeysAlreadyRegistered` refused after the broadcast). It + /// rides alongside the code already chosen rather than replacing it, so a + /// host that branches on a dedicated code keeps seeing exactly what it + /// saw before and one that wants the rejection itself no longer has to + /// recognize it by its rendered text. + fn with_consensus_of(self, error: &PlatformWalletError) -> Self { + match error.consensus_error() { + Some(consensus_error) => self.with_consensus_error(consensus_error), + None => self, + } + } + /// Stamp Platform's own rejection onto an already-built result. /// /// Leaves `code` and `message` alone: the numeric result code is the host @@ -963,12 +1012,13 @@ impl From> for PlatformWalletFFIResult { } } -/// The value-carrying DPNS-marketplace rejections, rendered as -/// `(code, JSON detail)` instead of `(code, Display)`. +/// The value-carrying rejections (the DPNS-marketplace trio and the +/// invitation claim's identity outcomes), rendered as `(code, JSON detail)` +/// instead of `(code, Display)`. /// /// `PlatformWalletFFIResult` has no per-error value fields, so a /// host that needs the *values* — not prose naming them — can only get -/// them through the message. These three therefore put a stable JSON +/// them through the message. These therefore put a stable JSON /// object there; the exact shape is documented on each /// [`PlatformWalletFFIResultCode`] variant and parsed back by the Swift /// mirror. Returns `None` for every other error, leaving the `Display` @@ -976,9 +1026,7 @@ impl From> for PlatformWalletFFIResult { /// /// `DocumentNotForSale` (37) is deliberately absent: its only value is /// the document id the caller supplied, so its `Display` is enough. -fn trade_error_json_detail( - error: &PlatformWalletError, -) -> Option<(PlatformWalletFFIResultCode, String)> { +fn error_json_detail(error: &PlatformWalletError) -> Option<(PlatformWalletFFIResultCode, String)> { match error { PlatformWalletError::DocumentPriceChanged { document_id, @@ -1014,6 +1062,20 @@ fn trade_error_json_detail( }) .to_string(), )), + PlatformWalletError::InvitationKeysAlreadyRegistered { identity_id, .. } => Some(( + PlatformWalletFFIResultCode::ErrorInvitationKeysAlreadyRegistered, + serde_json::json!({ + "identityId": identity_id.map(|id| id.to_string(Encoding::Base58)), + }) + .to_string(), + )), + PlatformWalletError::InvitationClaimedByThisWallet { identity_id } => Some(( + PlatformWalletFFIResultCode::ErrorInvitationClaimedByThisWallet, + serde_json::json!({ + "identityId": identity_id.to_string(Encoding::Base58), + }) + .to_string(), + )), _ => None, } } @@ -1033,11 +1095,11 @@ impl From for PlatformWalletFFIResult { error.to_string(), ); } - // The three value-carrying marketplace rejections replace the - // Display rendering with a stable JSON detail object; everything - // else keeps Display as the message. - if let Some((code, detail)) = trade_error_json_detail(&error) { - return PlatformWalletFFIResult::err(code, detail); + // The value-carrying rejections replace the Display rendering with a + // stable JSON detail object; everything else keeps Display as the + // message. + if let Some((code, detail)) = error_json_detail(&error) { + return PlatformWalletFFIResult::err(code, detail).with_consensus_of(&error); } // Map the typed wallet error variants explicitly so they // don't flatten to ErrorUnknown at the FFI boundary. The @@ -1183,9 +1245,16 @@ impl From for PlatformWalletFFIResult { PlatformWalletError::InvitationNetworkMismatch { .. } => { PlatformWalletFFIResultCode::ErrorInvalidNetwork } - PlatformWalletError::AssetLockAlreadyConsumed(..) => { + PlatformWalletError::AssetLockAlreadyConsumed(..) + | PlatformWalletError::InvitationAlreadyClaimed { .. } => { PlatformWalletFFIResultCode::ErrorAssetLockAlreadyConsumed } + PlatformWalletError::InvitationNotReady(..) => { + PlatformWalletFFIResultCode::ErrorInvitationNotReady + } + PlatformWalletError::AssetLockNotChainLocked(..) => { + PlatformWalletFFIResultCode::ErrorAssetLockNotChainLocked + } PlatformWalletError::AssetLockFundingMismatch { .. } => { PlatformWalletFFIResultCode::ErrorAssetLockFundingMismatch } @@ -1316,7 +1385,7 @@ impl From for PlatformWalletFFIResult { } // DPNS marketplace: the one trade rejection whose Display is // sufficient (the other three are handled by - // `trade_error_json_detail` above and never reach this match). + // `error_json_detail` above and never reach this match). PlatformWalletError::DocumentNotForSale { .. } => { PlatformWalletFFIResultCode::ErrorDocumentNotForSale } @@ -1391,17 +1460,7 @@ impl From for PlatformWalletFFIResult { }) => PlatformWalletFFIResultCode::ErrorProtocolVersionNotActive, _ => PlatformWalletFFIResultCode::ErrorUnknown, }; - let result = PlatformWalletFFIResult::err(code, error.to_string()); - // Platform's own verdict, for the variants that still hold the SDK - // error it arrived in (`Sdk`, `TokenOperationFailed`). It rides - // alongside the code chosen above rather than replacing it, so a host - // that branches on a dedicated code keeps seeing exactly what it saw - // before and one that wants the rejection itself no longer has to - // recognize it by its rendered text. - match error.consensus_error() { - Some(consensus_error) => result.with_consensus_error(consensus_error), - None => result, - } + PlatformWalletFFIResult::err(code, error.to_string()).with_consensus_of(&error) } } @@ -2555,6 +2614,92 @@ mod tests { ); } + /// The invitation claim's outcomes keep their own pinned codes, so a + /// host can tell "this wallet already has an identity" (63) and "your + /// own claim landed" (64) from "someone else claimed it" (24), and the + /// two retry signals (65, 66) from an unknown failure. + #[test] + fn should_keep_distinct_pinned_codes_for_invitation_claim_outcomes() { + use dpp::prelude::Identifier; + + let id = Identifier::from([7u8; 32]); + let cases: [(PlatformWalletError, PlatformWalletFFIResultCode, i32); 6] = [ + ( + PlatformWalletError::InvitationKeysAlreadyRegistered { + identity_id: Some(id), + rejection: None, + }, + PlatformWalletFFIResultCode::ErrorInvitationKeysAlreadyRegistered, + 63, + ), + ( + PlatformWalletError::InvitationClaimedByThisWallet { identity_id: id }, + PlatformWalletFFIResultCode::ErrorInvitationClaimedByThisWallet, + 64, + ), + ( + PlatformWalletError::InvitationNotReady(dash_sdk::Error::Generic( + "quorum".to_string(), + )), + PlatformWalletFFIResultCode::ErrorInvitationNotReady, + 65, + ), + ( + PlatformWalletError::AssetLockNotChainLocked("later".to_string()), + PlatformWalletFFIResultCode::ErrorAssetLockNotChainLocked, + 66, + ), + ( + PlatformWalletError::InvitationAlreadyClaimed { identity_id: id }, + PlatformWalletFFIResultCode::ErrorAssetLockAlreadyConsumed, + 24, + ), + ( + PlatformWalletError::AssetLockAlreadyConsumed(dashcore::OutPoint::default()), + PlatformWalletFFIResultCode::ErrorAssetLockAlreadyConsumed, + 24, + ), + ]; + for (error, expected, raw) in cases { + let rendered = error.to_string(); + let result: PlatformWalletFFIResult = error.into(); + assert_eq!(result.code, expected, "{rendered}"); + assert_eq!(result.code as i32, raw, "{rendered}"); + } + } + + /// Codes 63/64 carry the identity they name as a STABLE JSON detail, + /// `null` when Platform refused the broadcast and named no owner. + #[test] + fn should_carry_the_documented_json_detail_for_invitation_identity_outcomes() { + use dpp::prelude::Identifier; + + let id = Identifier::from([7u8; 32]); + let detail = |error: PlatformWalletError| -> serde_json::Value { + let result: PlatformWalletFFIResult = error.into(); + serde_json::from_str(&message_of(&result)).expect("the message must parse as JSON") + }; + assert_eq!( + detail(PlatformWalletError::InvitationKeysAlreadyRegistered { + identity_id: Some(id), + rejection: None, + })["identityId"], + id.to_string(Encoding::Base58) + ); + assert!( + detail(PlatformWalletError::InvitationKeysAlreadyRegistered { + identity_id: None, + rejection: None, + })["identityId"] + .is_null() + ); + assert_eq!( + detail(PlatformWalletError::InvitationClaimedByThisWallet { identity_id: id }) + ["identityId"], + id.to_string(Encoding::Base58) + ); + } + #[test] fn shielded_insufficient_balance_code_is_pinned_at_41() { assert_eq!( @@ -2883,6 +3028,36 @@ mod tests { )) } + /// Platform's refusal of a claim whose keys are taken keeps code 63 and + /// its JSON detail, and carries the refusal's consensus code beside them. + #[test] + fn should_carry_the_consensus_code_of_a_taken_keys_refusal() { + use dpp::consensus::state::identity::duplicated_identity_public_key_id_state_error::DuplicatedIdentityPublicKeyIdStateError; + use dpp::consensus::state::state_error::StateError; + + let refusal = + ConsensusError::StateError(StateError::DuplicatedIdentityPublicKeyIdStateError( + DuplicatedIdentityPublicKeyIdStateError::new(vec![0]), + )); + let result: PlatformWalletFFIResult = + PlatformWalletError::InvitationKeysAlreadyRegistered { + identity_id: None, + rejection: Some(broadcast_rejection(refusal)), + } + .into(); + + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorInvitationKeysAlreadyRegistered + ); + assert_eq!(message_of(&result), r#"{"identityId":null}"#); + assert_eq!(result.consensus_code, 40207); + assert_eq!( + result.consensus_kind, + PlatformWalletFFIConsensusErrorKind::State + ); + } + /// The wait-stream shape a state rejection arrives in: accepted by /// CheckTx, rejected at block execution. fn broadcast_rejection(cause: ConsensusError) -> dash_sdk::Error { diff --git a/packages/rs-platform-wallet-ffi/src/invitation.rs b/packages/rs-platform-wallet-ffi/src/invitation.rs index 03d3a1eed18..edcfa3a9d81 100644 --- a/packages/rs-platform-wallet-ffi/src/invitation.rs +++ b/packages/rs-platform-wallet-ffi/src/invitation.rs @@ -43,6 +43,7 @@ use crate::core_wallet_types::OutPointFFI; use crate::dashpay::resolver_contact_crypto_provider; use crate::error::*; use crate::handle::*; +use crate::identity_keys_from_mnemonic::resolve_master_from_resolver; use crate::identity_registration_with_signer::{decode_identity_pubkeys, IdentityPubkeyFFI}; use crate::runtime::block_on_worker; use crate::{check_ptr, unwrap_option_or_return, unwrap_result_or_return}; @@ -250,6 +251,19 @@ pub unsafe extern "C" fn platform_wallet_create_invitation( /// contact-request path /// ([`crate::dashpay::platform_wallet_send_contact_request_with_signer`]). /// +/// Before broadcasting, the claim looks up the identities that would make +/// Platform refuse it and charge the voucher. Those outcomes have their own +/// codes, and none of them broadcast or record anything: +/// `ErrorInvitationClaimedByThisWallet` (an earlier claim of this wallet +/// landed, or the invitation's identity is one this wallet already records; +/// JSON detail names the identity), `ErrorAssetLockAlreadyConsumed` (claimed +/// by an identity that does not hold the master key at `identity_index` and +/// that this wallet does not record — usually someone else), `ErrorInvitationKeysAlreadyRegistered` (another +/// identity holds a submitted key; also returned when Platform refuses the +/// broadcast for that reason) and `ErrorInvitationNotReady` (the lookups +/// could not be verified yet). `ErrorAssetLockNotChainLocked` asks to retry +/// once the funding transaction propagates or is chain-locked. +/// /// On success writes the new identity id to `*out_identity_id` and a handle into /// `MANAGED_IDENTITY_STORAGE` to `*out_identity_handle` (release via /// [`crate::managed_identity_destroy`]). @@ -313,18 +327,18 @@ pub unsafe extern "C" fn platform_wallet_claim_invitation( let signer_addr = signer_handle as usize; - let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| { - let identity_wallet = wallet.identity().clone(); - block_on_worker(async move { - // SAFETY: see the fn-level safety doc — the caller pins - // `signer_handle` for the duration of this call. - let identity_signer: &VTableSigner = unsafe { &*(signer_addr as *const VTableSigner) }; - identity_wallet - .claim_invitation(invitation, identity_index, keys_map, identity_signer, None) - .await - }) + // Release the wallet storage before the claim's lookups and broadcast. + let option = + PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| wallet.identity().clone()); + let identity_wallet = unwrap_option_or_return!(option); + let result = block_on_worker(async move { + // SAFETY: see the fn-level safety doc — the caller pins + // `signer_handle` for the duration of this call. + let identity_signer: &VTableSigner = unsafe { &*(signer_addr as *const VTableSigner) }; + identity_wallet + .claim_invitation(invitation, identity_index, keys_map, identity_signer, None) + .await }); - let result = unwrap_option_or_return!(option); let identity = unwrap_result_or_return!(result); let id_bytes: [u8; 32] = identity.id().to_buffer(); unsafe { @@ -448,8 +462,25 @@ pub struct InvitationClaimStatusFFI { /// was claimed. `false` does NOT prove the voucher is unspent (see /// [`platform_wallet_invitation_prospective_identity_id`]). pub already_claimed: bool, + /// Whether this wallet made the claim, as + /// [`platform_wallet_invitation_claim_status_for_identity`] decides it: + /// [`INVITATION_CLAIMED_BY_THIS_WALLET_NO`] (also whenever + /// `already_claimed` is false), [`INVITATION_CLAIMED_BY_THIS_WALLET_YES`], + /// or [`INVITATION_CLAIMED_BY_THIS_WALLET_UNKNOWN`] (the wallet's master + /// key could not be derived). [`platform_wallet_invitation_claim_status`] + /// does not decide it and reports `UNKNOWN` for a claimed invitation. + pub claimed_by_this_wallet: u8, } +/// [`InvitationClaimStatusFFI::claimed_by_this_wallet`]: not this wallet's +/// claim, or not claimed at all. +pub const INVITATION_CLAIMED_BY_THIS_WALLET_NO: u8 = 0; +/// [`InvitationClaimStatusFFI::claimed_by_this_wallet`]: the invitation's +/// identity holds this wallet's master key at the asked identity index. +pub const INVITATION_CLAIMED_BY_THIS_WALLET_YES: u8 = 1; +/// [`InvitationClaimStatusFFI::claimed_by_this_wallet`]: unknown. +pub const INVITATION_CLAIMED_BY_THIS_WALLET_UNKNOWN: u8 = 2; + impl InvitationClaimStatusFFI { fn zeroed() -> Self { Self { @@ -458,22 +489,33 @@ impl InvitationClaimStatusFFI { is_instant: false, is_chain_locked: false, already_claimed: false, + claimed_by_this_wallet: INVITATION_CLAIMED_BY_THIS_WALLET_UNKNOWN, } } -} -impl From for InvitationClaimStatusFFI { - fn from(status: InvitationClaimStatus) -> Self { + fn new(status: InvitationClaimStatus, claimed_by_this_wallet: Option) -> Self { Self { prospective_identity_id: status.prospective_identity_id.to_buffer(), amount_duffs: status.amount_duffs, is_instant: status.is_instant, is_chain_locked: status.is_chain_locked, already_claimed: status.already_claimed, + claimed_by_this_wallet: match claimed_by_this_wallet { + Some(false) => INVITATION_CLAIMED_BY_THIS_WALLET_NO, + Some(true) => INVITATION_CLAIMED_BY_THIS_WALLET_YES, + None => INVITATION_CLAIMED_BY_THIS_WALLET_UNKNOWN, + }, } } } +impl From for InvitationClaimStatusFFI { + fn from(status: InvitationClaimStatus) -> Self { + let claimed_by_this_wallet = (!status.already_claimed).then_some(false); + Self::new(status, claimed_by_this_wallet) + } +} + /// What an invitation is worth and whether it was already claimed, without /// claiming it: one funding-tx fetch (with the claim's propagation retry) and /// one identity fetch. A ChainLock-only link whose funding tx is not @@ -523,6 +565,94 @@ pub unsafe extern "C" fn platform_wallet_invitation_claim_status( PlatformWalletFFIResult::ok() } +/// [`platform_wallet_invitation_claim_status`], plus whether this wallet +/// made the claim as its identity at `identity_index` +/// (`out_status.claimed_by_this_wallet`). +/// +/// Forwards to `IdentityWallet::invitation_claim_status_for_identity`, which +/// resolves the wallet's mnemonic through `mnemonic_resolver_handle` only +/// when the invitation was claimed and the wallet holds no resident private +/// keys, so a resolver that cannot answer (a locked Keychain) never turns an +/// unclaimed invitation into an unknown one. A null handle or a failed +/// resolve reports `INVITATION_CLAIMED_BY_THIS_WALLET_UNKNOWN`. Errors are +/// those of [`platform_wallet_invitation_claim_status`]. +/// +/// `YES` also covers an identity this wallet already records at another +/// index; `NO` otherwise covers only `identity_index`. +/// +/// The resolver is called on a runtime worker thread, after the wallet +/// storage is released. +/// +/// # Safety +/// - `uri` must be a valid NUL-terminated UTF-8 C string. +/// - `out_status` must be a valid `*mut InvitationClaimStatusFFI`. +/// - `mnemonic_resolver_handle` is null or comes from +/// [`rs_sdk_ffi::dash_sdk_mnemonic_resolver_create`] and stays valid for +/// the call. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_invitation_claim_status_for_identity( + wallet_handle: Handle, + mnemonic_resolver_handle: *mut MnemonicResolverHandle, + identity_index: u32, + uri: *const c_char, + out_status: *mut InvitationClaimStatusFFI, +) -> PlatformWalletFFIResult { + check_ptr!(out_status); + unsafe { + *out_status = InvitationClaimStatusFFI::zeroed(); + } + check_ptr!(uri); + + let uri = unwrap_result_or_return!(unsafe { CStr::from_ptr(uri) }.to_str()); + let invitation = match parse_invitation_for_query(uri) { + Ok(invitation) => invitation, + Err(e) => return e, + }; + + let resolver_addr = mnemonic_resolver_handle as usize; + // Take what the call needs and release the wallet storage before the + // network calls and the resolver callback run. + let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| { + ( + wallet.identity().clone(), + wallet.wallet_id(), + wallet.network(), + ) + }); + let (identity_wallet, wallet_id, network) = unwrap_option_or_return!(option); + let result = block_on_worker(async move { + identity_wallet + .invitation_claim_status_for_identity(&invitation, identity_index, || { + let resolver = resolver_addr as *mut MnemonicResolverHandle; + if resolver.is_null() { + return None; + } + // SAFETY: the caller keeps the resolver valid for the + // whole call, which blocks until this future completes. + match unsafe { resolve_master_from_resolver(resolver, &wallet_id, network) } { + Ok(master) => Some(master), + Err(failure) => { + tracing::warn!( + code = ?failure.code, + "could not resolve the wallet's mnemonic to tell whose \ + invitation claim it was" + ); + None + } + } + }) + .await + }) + .map(|(status, claimed_by_this_wallet)| { + InvitationClaimStatusFFI::new(status, claimed_by_this_wallet) + }); + let status = unwrap_result_or_return!(result); + unsafe { + *out_status = status; + } + PlatformWalletFFIResult::ok() +} + /// Read-only preview of a `dashpay://invite` link — decode + surface the /// invitation's metadata WITHOUT claiming it (no wallet handle, no network, no /// side effects). The claim UI uses this to show the amount, sender, and expiry @@ -999,6 +1129,69 @@ mod tests { assert!(!status.already_claimed, "the out-param is zeroed first"); } + /// The wallet-aware status refuses a malformed link and a null `uri` the + /// same way, after zeroing the out-param (including the tri-state). + #[test] + fn should_refuse_bad_input_in_the_wallet_aware_claim_status() { + let bad = std::ffi::CString::new("https://not-an-invite").unwrap(); + let mut status = InvitationClaimStatusFFI::zeroed(); + status.claimed_by_this_wallet = INVITATION_CLAIMED_BY_THIS_WALLET_YES; + let r = unsafe { + platform_wallet_invitation_claim_status_for_identity( + 0, + std::ptr::null_mut(), + 0, + bad.as_ptr(), + &mut status, + ) + }; + assert_eq!(r.code, PlatformWalletFFIResultCode::ErrorInvalidParameter); + assert_eq!( + status.claimed_by_this_wallet, INVITATION_CLAIMED_BY_THIS_WALLET_UNKNOWN, + "a failed call never reads as a definite answer" + ); + + let r = unsafe { + platform_wallet_invitation_claim_status_for_identity( + 0, + std::ptr::null_mut(), + 0, + std::ptr::null(), + &mut status, + ) + }; + assert_eq!(r.code, PlatformWalletFFIResultCode::ErrorNullPointer); + } + + /// The tri-state reaches hosts as 0/1/2. The wallet-unaware status + /// cannot say whose claim it was, so a claimed invitation is unknown + /// there, and an unclaimed one is never this wallet's. + #[test] + fn should_encode_whose_claim_it_was_as_a_tri_state() { + let status = |already_claimed: bool| InvitationClaimStatus { + prospective_identity_id: dpp::prelude::Identifier::new([3; 32]), + amount_duffs: 1, + is_instant: true, + is_chain_locked: false, + already_claimed, + }; + for (claimed_by_this_wallet, raw) in [(Some(false), 0), (Some(true), 1), (None, 2)] { + assert_eq!( + InvitationClaimStatusFFI::new(status(true), claimed_by_this_wallet) + .claimed_by_this_wallet, + raw + ); + } + assert_eq!( + InvitationClaimStatusFFI::from(status(true)).claimed_by_this_wallet, + INVITATION_CLAIMED_BY_THIS_WALLET_UNKNOWN + ); + assert_eq!( + InvitationClaimStatusFFI::from(status(false)).claimed_by_this_wallet, + INVITATION_CLAIMED_BY_THIS_WALLET_NO + ); + } + /// A link for the other network is refused by the library with a typed /// error that must reach hosts as the definitive `ErrorInvalidNetwork`, /// not the undetermined catch-all. diff --git a/packages/rs-platform-wallet/src/error.rs b/packages/rs-platform-wallet/src/error.rs index f9ed4a5b60f..71b6e6d8793 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -118,6 +118,38 @@ pub enum PlatformWalletError { wallet: Network, }, + /// The invitation's identity is this wallet's: it holds this claim's + /// master key (an earlier claim of this wallet landed), or the wallet + /// already records it. Nothing was recorded, and nothing was broadcast + /// unless a node that lagged behind let the claim through; the host loads + /// the identity the way it loads any of its own. + #[error("invitation was already claimed by this wallet as identity {identity_id}")] + InvitationClaimedByThisWallet { identity_id: Identifier }, + + /// Someone else claimed the invitation first; nothing was broadcast unless a node that lagged behind let the claim through. + #[error("invitation was already claimed by identity {identity_id}")] + InvitationAlreadyClaimed { identity_id: Identifier }, + + /// A key of the claim is already registered to another identity, so + /// Platform would refuse the claim and charge the voucher. `identity_id` + /// is that identity when the claim's lookup found it, `None` when + /// Platform refused the broadcast; `rejection` is then that refusal, + /// kept for its consensus code. + #[error("{}", match identity_id { + Some(id) => format!("a key of this invitation claim is already registered to identity {id}"), + None => "a key of this invitation claim is already registered to another identity".to_string(), + })] + InvitationKeysAlreadyRegistered { + identity_id: Option, + #[source] + rejection: Option, + }, + + /// The claim's identity lookups could not be verified yet (the trusted + /// quorum source is not ready). Nothing was broadcast; retry once synced. + #[error("cannot verify Platform's answer for the invitation claim yet: {0}")] + InvitationNotReady(#[source] dash_sdk::Error), + #[error("Failed to persist state: {0}")] /// A persister `store(...)` round failed. Returned (not swallowed) by /// user-initiated writes whose loss leaves a silent, non-self-healing @@ -1235,6 +1267,20 @@ impl From for PlatformWalletError { Self::InvitationNetworkMismatch { invitation, wallet } } InvitationError::NotChainLocked(message) => Self::AssetLockNotChainLocked(message), + InvitationError::ClaimedByThisWallet { identity_id } => { + Self::InvitationClaimedByThisWallet { identity_id } + } + InvitationError::AlreadyClaimed { identity_id } => { + Self::InvitationAlreadyClaimed { identity_id } + } + InvitationError::KeysAlreadyRegistered { + identity_id, + rejection, + } => Self::InvitationKeysAlreadyRegistered { + identity_id, + rejection, + }, + InvitationError::NotReady(error) => Self::InvitationNotReady(error), InvitationError::Sdk(error) => Self::Sdk(error), } } @@ -1311,12 +1357,18 @@ impl PlatformWalletError { /// /// `None` for the variants that stringified their cause, and for the /// typed promotions (`AddressNonceMismatch`, `DocumentNotForSale`, …), - /// which keep the values they need and have FFI codes of their own. + /// which keep the values they need and have FFI codes of their own. The + /// exception is [`Self::InvitationKeysAlreadyRegistered`] refused after + /// the broadcast, which keeps Platform's refusal beside its own code. pub fn consensus_error(&self) -> Option<&ConsensusError> { match self { Self::Sdk(source) | Self::TokenOperationFailed { source, .. } => { source.consensus_error() } + Self::InvitationKeysAlreadyRegistered { + rejection: Some(source), + .. + } => source.consensus_error(), _ => None, } } @@ -2059,6 +2111,35 @@ mod invitation_error_mapping_tests { PlatformWalletError::Sdk(dash_sdk::Error::Generic(message)) if message == "boom" )); } + + /// The claim's preflight outcomes keep the identity they name. + #[test] + fn should_keep_the_identity_a_preflight_outcome_names() { + let id = Identifier::new([5; 32]); + assert!(matches!( + PlatformWalletError::from(InvitationError::ClaimedByThisWallet { identity_id: id }), + PlatformWalletError::InvitationClaimedByThisWallet { identity_id } if identity_id == id + )); + assert!(matches!( + PlatformWalletError::from(InvitationError::AlreadyClaimed { identity_id: id }), + PlatformWalletError::InvitationAlreadyClaimed { identity_id } if identity_id == id + )); + for owner in [Some(id), None] { + assert!(matches!( + PlatformWalletError::from(InvitationError::KeysAlreadyRegistered { + identity_id: owner, + rejection: None, + }), + PlatformWalletError::InvitationKeysAlreadyRegistered { identity_id, .. } if identity_id == owner + )); + } + assert!(matches!( + PlatformWalletError::from(InvitationError::NotReady(dash_sdk::Error::Generic( + "later".to_string() + ))), + PlatformWalletError::InvitationNotReady(_) + )); + } } #[cfg(test)] diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs b/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs index c8e7937b2e6..f7c74720f3f 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs @@ -583,6 +583,16 @@ impl IdentityWallet { .ok_or_else(|| PlatformWalletError::WalletNotFound(hex::encode(self.wallet_id))) } + /// [`Self::current_wallet_info_mut`] for reading: this handle's wallet and + /// its info while it is still this handle's generation, else `None`. + pub(crate) fn current_wallet_and_info<'w>( + &self, + wm: &'w WalletManager, + ) -> Option<(&'w Wallet, &'w PlatformWalletInfo)> { + wm.get_wallet_and_info(&self.wallet_id) + .filter(|(_, info)| Arc::ptr_eq(&info.generation, &self.generation)) + } + /// [`Self::current_wallet_info_mut`], with the wallet itself. pub(crate) fn current_wallet_and_info_mut<'w>( &self, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/invitation.rs b/packages/rs-platform-wallet/src/wallet/identity/network/invitation.rs index 1c158cf7248..3b0b6800cb1 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/invitation.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/invitation.rs @@ -16,10 +16,12 @@ use std::collections::BTreeMap; use dpp::identity::accessors::IdentityGettersV0; +use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; use dpp::identity::signer::Signer; -use dpp::identity::{Identity, IdentityPublicKey, KeyID}; +use dpp::identity::{Identity, IdentityPublicKey, KeyID, KeyType, Purpose, SecurityLevel}; +use dpp::platform_value::BinaryData; use dpp::prelude::{AssetLockProof, Identifier}; -use key_wallet::bip32::{ChildNumber, DerivationPath}; +use key_wallet::bip32::{ChildNumber, DerivationPath, ExtendedPrivKey}; use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; use crate::changeset::{ @@ -28,6 +30,7 @@ use crate::changeset::{ use dash_sdk::platform::transition::put_settings::PutSettings; +use dash_sdk::platform::dashpay::{identity_holds_master_key, InvitationError}; pub use dash_sdk::platform::dashpay::{ InvitationClaimStatus, MAX_INVITATION_DUFFS, MAX_INVITATION_TTL_SECS, MIN_INVITATION_DUFFS, }; @@ -35,9 +38,36 @@ pub use dash_sdk::platform::dashpay::{ use crate::error::PlatformWalletError; use crate::wallet::identity::crypto::{encode_invitation_uri, InviterInfo, ParsedInvitation}; use crate::wallet::identity::network::contact_requests::ContactCryptoProvider; +use crate::wallet::identity::network::identity_handle::{ + derive_ecdsa_identity_auth_keypair_from_master, derive_identity_auth_keypair, MASTER_KEY_INDEX, +}; use super::*; +/// The wallet holds its private keys in process, so its master key derives +/// without a resolver. +fn has_resident_keys(wallet: &key_wallet::Wallet) -> bool { + !wallet.is_external_signable() && !wallet.is_watch_only() +} + +fn wallet_not_found() -> PlatformWalletError { + PlatformWalletError::WalletNotFound("Wallet not found in wallet manager".to_string()) +} + +/// Where [`IdentityWallet::invitation_claimed_by_this_wallet`] gets this +/// wallet's master key from. +#[derive(Clone, Copy)] +pub(crate) enum InvitationClaimantKey<'a> { + /// Derive it from the in-process wallet (a wallet with resident private + /// keys). + ResidentWallet, + /// Derive it from this master xpriv, resolved by the caller (a wallet + /// whose seed lives outside the process, such as the iOS Keychain). + Master(&'a ExtendedPrivKey), + /// The key cannot be had right now, so whose claim it was is unknown. + Unavailable, +} + /// A freshly-created invitation: the shareable link plus the bookkeeping the /// inviter tracks to reclaim an unclaimed voucher. pub struct Invitation { @@ -301,17 +331,254 @@ impl IdentityWallet { Ok(self.sdk.invitation_claim_status(invitation).await?) } + /// [`Self::invitation_claim_status`], plus the identity that claimed the + /// invitation when there is one. Pass it to + /// [`Self::invitation_claimed_by_this_wallet`] to tell whose claim it was. + pub(crate) async fn invitation_claim_status_with_identity( + &self, + invitation: &ParsedInvitation, + ) -> Result<(InvitationClaimStatus, Option), PlatformWalletError> { + Ok(self + .sdk + .invitation_claim_status_with_identity(invitation) + .await?) + } + + /// [`Self::invitation_claim_status`], plus whether this wallet made the + /// claim: the claimed identity is one this wallet already records, or it + /// holds the wallet's master key at `identity_index` + /// ([`Self::invitation_claimed_by_this_wallet`]). A "no" covers only that + /// index: a claim this wallet made at another index and has not recorded + /// yet reads as someone else's. + /// + /// The master key is needed only when the invitation was claimed, so + /// `resolve_master` is called only then, and only for a wallet without + /// resident private keys (whose seed lives outside the process, such as + /// the iOS Keychain). It returns `None` when the key cannot be had, which + /// makes the answer unknown rather than failing the status: a locked + /// Keychain never turns an unclaimed invitation into an unknown one. + pub async fn invitation_claim_status_for_identity( + &self, + invitation: &ParsedInvitation, + identity_index: u32, + resolve_master: R, + ) -> Result<(InvitationClaimStatus, Option), PlatformWalletError> + where + R: FnOnce() -> Option, + { + let (status, claimed) = self + .invitation_claim_status_with_identity(invitation) + .await?; + let claimed_by_this_wallet = self + .invitation_claimed_by_this_wallet_resolving( + claimed.as_ref(), + identity_index, + resolve_master, + ) + .await; + Ok((status, claimed_by_this_wallet)) + } + + /// The decision behind [`Self::invitation_claim_status_for_identity`], + /// once the claimed identity (if any) is known: + /// - nobody claimed it → `Some(false)`, without a key; + /// - this wallet already holds the identity (recorded at any index) → + /// `Some(true)`, without a key; + /// - otherwise the master key at `identity_index` decides, derived in + /// process for a wallet with resident keys, else from + /// `resolve_master()`; `None` from it makes the answer unknown. + async fn invitation_claimed_by_this_wallet_resolving( + &self, + claimed: Option<&Identity>, + identity_index: u32, + resolve_master: R, + ) -> Option + where + R: FnOnce() -> Option, + { + let Some(claimed) = claimed else { + return Some(false); + }; + if self.holds_identity(&claimed.id()).await { + return Some(true); + } + let has_resident_keys = { + let wm = self.wallet_manager.read().await; + self.current_wallet_and_info(&wm) + .is_some_and(|(wallet, _)| has_resident_keys(wallet)) + }; + if has_resident_keys { + return self + .invitation_claimed_by_this_wallet( + Some(claimed), + identity_index, + InvitationClaimantKey::ResidentWallet, + ) + .await; + } + // `ExtendedPrivKey` wipes its scalar on drop. + let master = resolve_master(); + let key = match &master { + Some(master) => InvitationClaimantKey::Master(master), + None => InvitationClaimantKey::Unavailable, + }; + self.invitation_claimed_by_this_wallet(Some(claimed), identity_index, key) + .await + } + + /// The wallet error for a refused claim. The invitation's identity may not + /// hold the key at the claimed index and still be one this wallet + /// already records (a claim it made at another index): that is its own + /// claim, not someone else's. + /// + /// "This wallet's claim" sends the host to load that identity through + /// this handle, so it is reported only while the handle's wallet is + /// still the one the manager holds: one removed, or re-created under its + /// id, while the claim ran is reported as not found instead. + async fn claim_refusal(&self, error: InvitationError) -> PlatformWalletError { + let refusal = match error { + InvitationError::AlreadyClaimed { identity_id } + if self.holds_identity(&identity_id).await => + { + PlatformWalletError::InvitationClaimedByThisWallet { identity_id } + } + error => error.into(), + }; + match refusal { + PlatformWalletError::InvitationClaimedByThisWallet { .. } + if !self.is_current_generation().await => + { + PlatformWalletError::WalletNotFound(hex::encode(self.wallet_id)) + } + refusal => refusal, + } + } + + /// This handle's wallet is still the one the manager holds under its id. + async fn is_current_generation(&self) -> bool { + let wm = self.wallet_manager.read().await; + self.current_wallet_and_info(&wm).is_some() + } + + /// This wallet records `identity_id` as one of its own identities. A + /// wallet re-created under this handle's id since it was taken is not + /// this wallet: its identities say nothing about this handle's claims. + async fn holds_identity(&self, identity_id: &Identifier) -> bool { + let wm = self.wallet_manager.read().await; + self.current_wallet_and_info(&wm) + .and_then(|(_, info)| info.identity_manager.managed_identity(identity_id)) + .is_some_and(|managed| managed.wallet_id == Some(self.wallet_id)) + } + + /// Whether this wallet claimed the invitation as its identity at + /// `identity_index`: the claimed identity holds the master key this + /// wallet derives for that index. The test is the one the claim's own + /// preflight uses ([`identity_holds_master_key`]), so the status and the + /// claim never disagree about the same identity. + /// + /// - `claimed` is `None` (nobody claimed it) → `Some(false)`, and `key` + /// is not used. + /// - The master key cannot be derived (`key` is + /// [`InvitationClaimantKey::Unavailable`], or the derivation fails) → + /// `None`: unknown. + pub(crate) async fn invitation_claimed_by_this_wallet( + &self, + claimed: Option<&Identity>, + identity_index: u32, + key: InvitationClaimantKey<'_>, + ) -> Option { + let claimed = match claimed { + Some(identity) => identity, + None => return Some(false), + }; + let master_key = match self.claimant_master_public_key(identity_index, key).await { + Ok(public_key) => public_key?, + Err(e) => { + tracing::warn!( + error = %e, + identity_index, + "could not derive the master key to check whose invitation claim it was" + ); + return None; + } + }; + Some(identity_holds_master_key(claimed, &master_key)) + } + + /// The master authentication key this wallet derives at `identity_index`, + /// as the identity key a claim submits at id 0. `Ok(None)` when `key` is + /// [`InvitationClaimantKey::Unavailable`]. + async fn claimant_master_public_key( + &self, + identity_index: u32, + key: InvitationClaimantKey<'_>, + ) -> Result, PlatformWalletError> { + let public_key: [u8; 33] = match key { + InvitationClaimantKey::Unavailable => return Ok(None), + InvitationClaimantKey::Master(master) => { + // Only the network comes from the manager; the derivation + // runs after its read guard is released. + let network = { + let wm = self.wallet_manager.read().await; + self.current_wallet_and_info(&wm) + .ok_or_else(wallet_not_found)? + .0 + .network + }; + derive_ecdsa_identity_auth_keypair_from_master( + master, + network, + identity_index, + MASTER_KEY_INDEX, + )? + .public_key + } + // The resident key material lives in the wallet the manager + // holds, so this derivation runs under its read guard. + InvitationClaimantKey::ResidentWallet => { + let wm = self.wallet_manager.read().await; + let (wallet, _) = self + .current_wallet_and_info(&wm) + .ok_or_else(wallet_not_found)?; + let (_path, _private, public_key) = derive_identity_auth_keypair( + wallet, + wallet.network, + identity_index, + MASTER_KEY_INDEX, + )?; + public_key.to_compressed() + } + }; + Ok(Some(IdentityPublicKey::V0(IdentityPublicKeyV0 { + id: 0, + purpose: Purpose::AUTHENTICATION, + security_level: SecurityLevel::MASTER, + contract_bounds: None, + key_type: KeyType::ECDSA_SECP256K1, + read_only: false, + data: BinaryData::new(public_key.to_vec()), + disabled_at: None, + }))) + } + /// Claim a DashPay invitation: register a NEW identity for the invitee, /// funded by the imported voucher, then record it in this wallet. /// /// The claim itself — refetching the funding transaction, rebuilding the - /// asset-lock proof, the IS → ChainLock fallback (a stale islock, a claim - /// too large with the IS proof, or a funding transaction over the input - /// cap) and adopting an earlier claim that - /// already landed — is + /// asset-lock proof, the lookups that keep a claim Platform would refuse + /// and charge for from being broadcast, the IS → ChainLock fallback (a + /// stale islock, a claim too large with the IS proof, or a funding + /// transaction over the input cap) and adopting an earlier claim that a + /// lagging node let through — is /// [`dash_sdk::Sdk::claim_invitation`]. This adds the identity and its /// keys to the wallet's identity manager at `identity_index`. /// + /// An earlier claim of this wallet that already landed is reported as + /// [`PlatformWalletError::InvitationClaimedByThisWallet`] and is not + /// recorded here: the host loads that identity the way it loads any of + /// its own (with its names). So is an invitation whose identity this + /// wallet already records at another index. + /// /// The contact-bootstrap is a separate step: on success the UI asks the /// invitee whether to establish contact with the sender and, if so, calls /// the existing contact-request path. @@ -326,10 +593,14 @@ impl IdentityWallet { where S: Signer + Send + Sync, { - let identity = self + let identity = match self .sdk .claim_invitation(invitation, keys_map, identity_signer, settings) - .await?; + .await + { + Ok(identity) => identity, + Err(error) => return Err(self.claim_refusal(error).await), + }; // Best-effort local bookkeeping — Platform has already accepted the // registration, so a local failure must NOT propagate (mirrors @@ -337,9 +608,11 @@ impl IdentityWallet { // the IdentityManager on the next re-sync if this is skipped. { let identity_id = identity.id(); + // Only into the wallet this handle was taken for: one removed, or + // re-created under its id, while the claim ran must not receive it. let mut wm = self.wallet_manager.write().await; - match wm.get_wallet_info_mut(&self.wallet_id) { - Some(info) => { + match self.current_wallet_info_mut(&mut wm) { + Ok(info) => { match info.identity_manager.add_identity( identity.clone(), identity_index, @@ -382,11 +655,11 @@ impl IdentityWallet { } } } - None => { + Err(_) => { tracing::warn!( %identity_id, - "claim_invitation: identity registered on Platform but wallet info \ - was not found locally; skipping local persistence" + "claim_invitation: identity registered on Platform but this wallet \ + was removed or replaced while it ran; skipping local persistence" ); } } @@ -443,6 +716,408 @@ mod tests { assert_eq!(funding_index_from_path(&path), None); } + // --- invitation_claimed_by_this_wallet: whose claim it was --- + + mod claimant { + use std::collections::BTreeMap; + use std::sync::Arc; + + use dash_sdk::platform::dashpay::InvitationError; + use dpp::identity::accessors::IdentityGettersV0; + use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; + use dpp::identity::v0::IdentityV0; + use dpp::identity::{Identity, IdentityPublicKey, KeyID}; + use dpp::prelude::Identifier; + use key_wallet::bip32::ExtendedPrivKey; + use key_wallet::mnemonic::Mnemonic; + use key_wallet::wallet::initialization::WalletAccountCreationOptions; + use key_wallet::Network; + + use super::super::InvitationClaimantKey; + use crate::events::{EventHandler, PlatformEventHandler}; + use crate::wallet::identity::network::IdentityWallet; + use crate::wallet::persister::NoPlatformPersistence; + use crate::PlatformWalletError; + + const TEST_MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon \ + abandon abandon abandon abandon abandon about"; + + struct NoopEventHandler; + impl EventHandler for NoopEventHandler {} + impl PlatformEventHandler for NoopEventHandler {} + + fn seed() -> zeroize::Zeroizing<[u8; 64]> { + Mnemonic::from_phrase(TEST_MNEMONIC) + .expect("valid mnemonic") + .to_seed("") + } + + fn master() -> ExtendedPrivKey { + ExtendedPrivKey::new_master(Network::Testnet, &seed()[..]).expect("master key") + } + + /// A registered wallet. The manager keeps its seed outside the + /// process (external-signable), so the master key is passed in. + async fn wallet() -> IdentityWallet { + wallet_in_manager().await.1 + } + + /// [`wallet`], with the manager that holds it. + async fn wallet_in_manager() -> ( + Arc>, + IdentityWallet, + ) { + let sdk = Arc::new(dash_sdk::SdkBuilder::new_mock().build().expect("mock sdk")); + let handler: Arc = Arc::new(NoopEventHandler); + let manager = Arc::new(crate::PlatformWalletManager::new( + sdk, + Arc::new(NoPlatformPersistence), + handler, + )); + let wallet = recreate(&manager).await; + (manager, wallet) + } + + /// Create the test wallet in `manager`, under the id it always gets. + async fn recreate( + manager: &crate::PlatformWalletManager, + ) -> IdentityWallet { + manager + .create_wallet_from_seed_bytes( + Network::Testnet, + &seed(), + WalletAccountCreationOptions::None, + Some(0), + ) + .await + .expect("wallet creation") + .identity() + .clone() + } + + fn identity(keys: BTreeMap) -> Identity { + Identity::V0(IdentityV0 { + id: Identifier::new([1; 32]), + public_keys: keys, + balance: 0, + revision: 0, + }) + } + + /// The testnet master key at identity index 0 of `TEST_MNEMONIC` + /// (`m/9'/1'/5'/0'/0'/0'/0'`), computed outside this code base. + const PINNED_INDEX_0_MASTER_KEY: &str = + "03a00f4853081aeb8c9debe37267303fa133bd7f6678bfb3299dfa001bfd0341db"; + + /// Record `identity` as this wallet's own at `identity_index`. + async fn record(wallet: &IdentityWallet, identity: &Identity, identity_index: u32) { + let mut wm = wallet.wallet_manager.write().await; + let info = wm + .get_wallet_info_mut(&wallet.wallet_id) + .expect("wallet info"); + info.identity_manager + .add_identity( + identity.clone(), + identity_index, + wallet.wallet_id, + &wallet.persister, + ) + .expect("recorded"); + info.identity_manager + .managed_identity_mut(&identity.id()) + .expect("managed") + .wallet_id = Some(wallet.wallet_id); + } + + /// The identity a claim from this wallet at `identity_index` creates: + /// its key 0 is the wallet's master key at that index. + async fn claimed_at(wallet: &IdentityWallet, identity_index: u32) -> Identity { + let master = master(); + let master_key = wallet + .claimant_master_public_key(identity_index, InvitationClaimantKey::Master(&master)) + .await + .expect("derivable") + .expect("a key"); + identity([(0, master_key)].into()) + } + + #[tokio::test] + async fn should_recognize_this_wallets_claim_only_at_its_index() { + let wallet = wallet().await; + let master = master(); + let ours = claimed_at(&wallet, 0).await; + assert_eq!( + wallet + .invitation_claimed_by_this_wallet( + Some(&ours), + 0, + InvitationClaimantKey::Master(&master) + ) + .await, + Some(true) + ); + assert_eq!( + wallet + .invitation_claimed_by_this_wallet( + Some(&ours), + 1, + InvitationClaimantKey::Master(&master) + ) + .await, + Some(false) + ); + } + + /// A wallet without resident keys cannot derive in process: the + /// answer is unknown, not "not ours". + #[tokio::test] + async fn should_answer_unknown_when_the_wallet_has_no_resident_keys() { + let wallet = wallet().await; + let ours = claimed_at(&wallet, 0).await; + assert_eq!( + wallet + .invitation_claimed_by_this_wallet( + Some(&ours), + 0, + InvitationClaimantKey::ResidentWallet + ) + .await, + None + ); + } + + /// The key is resolved only when the invitation was claimed, so an + /// unanswerable resolver (a locked Keychain) never makes an unclaimed + /// invitation unknown; and a resolver with no answer makes a claimed + /// one unknown, not "not ours". + #[tokio::test] + async fn should_resolve_the_master_key_only_for_a_claimed_invitation() { + let wallet = wallet().await; + let ours = claimed_at(&wallet, 0).await; + let resolves = std::cell::Cell::new(0); + let resolve = |answer: Option| { + let resolves = &resolves; + move || { + resolves.set(resolves.get() + 1); + answer + } + }; + + assert_eq!( + wallet + .invitation_claimed_by_this_wallet_resolving(None, 0, resolve(None)) + .await, + Some(false) + ); + assert_eq!(resolves.get(), 0); + + assert_eq!( + wallet + .invitation_claimed_by_this_wallet_resolving(Some(&ours), 0, resolve(None)) + .await, + None + ); + assert_eq!( + wallet + .invitation_claimed_by_this_wallet_resolving( + Some(&ours), + 0, + resolve(Some(master())) + ) + .await, + Some(true) + ); + assert_eq!( + wallet + .invitation_claimed_by_this_wallet_resolving( + Some(&ours), + 1, + resolve(Some(master())) + ) + .await, + Some(false) + ); + assert_eq!(resolves.get(), 3); + } + + /// An identity this wallet already records is its own claim at any + /// index, with no key needed. + #[tokio::test] + async fn should_recognize_an_identity_the_wallet_already_holds() { + let wallet = wallet().await; + let ours = claimed_at(&wallet, 2).await; + record(&wallet, &ours, 2).await; + assert_eq!( + wallet + .invitation_claimed_by_this_wallet_resolving(Some(&ours), 3, || { + panic!("a recorded identity needs no key") + }) + .await, + Some(true) + ); + } + + /// Nobody claimed it: not ours, and no key is needed to say so. + #[tokio::test] + async fn should_answer_no_for_an_unclaimed_invitation_without_a_key() { + let wallet = wallet().await; + assert_eq!( + wallet + .invitation_claimed_by_this_wallet(None, 0, InvitationClaimantKey::Unavailable) + .await, + Some(false) + ); + } + + #[tokio::test] + async fn should_answer_unknown_when_the_key_is_unavailable() { + let wallet = wallet().await; + let ours = claimed_at(&wallet, 0).await; + assert_eq!( + wallet + .invitation_claimed_by_this_wallet( + Some(&ours), + 0, + InvitationClaimantKey::Unavailable + ) + .await, + None + ); + } + + /// The key the status derives is the master key a registration at + /// that index submits as key 0 (DIP-13 identity authentication, + /// ECDSA, identity 0, key 0, on testnet), pinned by value so a + /// derivation drift cannot silently turn "ours" into "not ours". + #[tokio::test] + async fn should_derive_the_registration_master_key_for_the_index() { + let wallet = wallet().await; + let master = master(); + let key = wallet + .claimant_master_public_key(0, InvitationClaimantKey::Master(&master)) + .await + .expect("derivable") + .expect("a key"); + assert_eq!( + hex::encode(key.data().as_slice()), + PINNED_INDEX_0_MASTER_KEY + ); + } + + /// Only a wallet that holds its keys in process derives without a + /// resolver, and that in-process derivation gives the same pinned key. + #[test] + fn should_derive_in_process_only_for_a_wallet_with_resident_keys() { + use key_wallet::wallet::Wallet; + + let mnemonic = Mnemonic::from_phrase(TEST_MNEMONIC).expect("valid mnemonic"); + let resident = Wallet::from_mnemonic( + mnemonic, + Network::Testnet, + WalletAccountCreationOptions::None, + ) + .expect("wallet"); + assert!(super::super::has_resident_keys(&resident)); + let (_path, _private, public_key) = + crate::wallet::identity::network::derive_identity_auth_keypair( + &resident, + Network::Testnet, + 0, + 0, + ) + .expect("derivable"); + assert_eq!( + hex::encode(public_key.to_compressed()), + PINNED_INDEX_0_MASTER_KEY + ); + } + + /// A registered wallet keeps its seed outside the process. + #[tokio::test] + async fn should_not_treat_a_registered_wallet_as_holding_resident_keys() { + let wallet = wallet().await; + let wm = wallet.wallet_manager.read().await; + let registered = wm.get_wallet(&wallet.wallet_id).expect("registered"); + assert!(!super::super::has_resident_keys(registered)); + } + + /// An `AlreadyClaimed` naming an identity this wallet records (a claim + /// it made at another index) reaches the host as its own claim; any + /// other stays "claimed by someone else". + #[tokio::test] + async fn should_report_a_recorded_identity_as_this_wallets_claim() { + let wallet = wallet().await; + let ours = claimed_at(&wallet, 2).await; + let theirs = Identifier::new([9; 32]); + record(&wallet, &ours, 2).await; + assert!(matches!( + wallet + .claim_refusal(InvitationError::AlreadyClaimed { identity_id: ours.id() }) + .await, + PlatformWalletError::InvitationClaimedByThisWallet { identity_id } if identity_id == ours.id() + )); + assert!(matches!( + wallet + .claim_refusal(InvitationError::AlreadyClaimed { identity_id: theirs }) + .await, + PlatformWalletError::InvitationAlreadyClaimed { identity_id } if identity_id == theirs + )); + } + + /// A handle whose wallet was removed and re-created under its id does + /// not read the replacement's identities as its own claims: its + /// refusal stays "claimed by someone else", whose claim it was is + /// unknown, and a claim the SDK found to be this wallet's is reported + /// as a missing wallet, while the replacement's own handle recognizes + /// it. + #[tokio::test] + async fn should_not_read_a_replacement_wallets_identities_through_a_stale_handle() { + let (manager, old) = wallet_in_manager().await; + let ours = claimed_at(&old, 2).await; + manager + .remove_wallet(&old.wallet_id) + .await + .expect("removed"); + let replacement = recreate(&manager).await; + assert_eq!(replacement.wallet_id, old.wallet_id); + record(&replacement, &ours, 2).await; + + assert!(matches!( + old.claim_refusal(InvitationError::AlreadyClaimed { identity_id: ours.id() }) + .await, + PlatformWalletError::InvitationAlreadyClaimed { identity_id } if identity_id == ours.id() + )); + assert_eq!( + old.invitation_claimed_by_this_wallet_resolving(Some(&ours), 2, || Some(master())) + .await, + None + ); + assert!(matches!( + replacement + .claim_refusal(InvitationError::AlreadyClaimed { identity_id: ours.id() }) + .await, + PlatformWalletError::InvitationClaimedByThisWallet { identity_id } if identity_id == ours.id() + )); + + // The SDK's own "claimed by this wallet" (the identity holds the + // master key at the claimed index) does not send the host to load + // it through the stale handle; the replacement's handle gets it. + assert!(matches!( + old.claim_refusal(InvitationError::ClaimedByThisWallet { + identity_id: ours.id() + }) + .await, + PlatformWalletError::WalletNotFound(_) + )); + assert!(matches!( + replacement + .claim_refusal(InvitationError::ClaimedByThisWallet { identity_id: ours.id() }) + .await, + PlatformWalletError::InvitationClaimedByThisWallet { identity_id } if identity_id == ours.id() + )); + } + } + // --- create_invitation: the durable-persistence precondition --- mod durability_gate { diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs b/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs index c0d63b5afe3..6efa33d025c 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs @@ -241,14 +241,12 @@ impl IdentityWallet { ) .await?; - // Add the identity to the manager and enrich it. + // Add the identity to the manager and enrich it — only into this + // handle's wallet generation: the fetches above ran without the lock, + // and a wallet re-created under its id meanwhile must not receive it. { let mut wm = self.wallet_manager.write().await; - let info = wm.get_wallet_info_mut(&self.wallet_id).ok_or_else(|| { - crate::error::PlatformWalletError::WalletNotFound( - "Wallet info not found in wallet manager".to_string(), - ) - })?; + let info = self.current_wallet_info_mut(&mut wm)?; if info.identity_manager.identity(&identity_id).is_none() { // Stored below, with its verified keys, as one changeset. info.identity_manager.add_identity_unstored( @@ -296,11 +294,7 @@ impl IdentityWallet { match self.fetch_owned_dpns_names(identity_id, None).await { Ok((names, fetch)) => { let mut wm = self.wallet_manager.write().await; - let info = wm.get_wallet_info_mut(&self.wallet_id).ok_or_else(|| { - crate::error::PlatformWalletError::WalletNotFound( - "Wallet info not found in wallet manager".to_string(), - ) - })?; + let info = self.current_wallet_info_mut(&mut wm)?; if let Some(managed) = info.identity_manager.managed_identity_mut(&identity_id) { managed.apply_fetched_dpns_names(names, fetch, &self.persister); } diff --git a/packages/rs-sdk/src/mock/sdk.rs b/packages/rs-sdk/src/mock/sdk.rs index 75da6f48760..8f4b34cc0d7 100644 --- a/packages/rs-sdk/src/mock/sdk.rs +++ b/packages/rs-sdk/src/mock/sdk.rs @@ -66,6 +66,25 @@ impl MockDashPlatformSdk { self.dapi.lock().await.request_count(request) } + /// Expect a request that is not a proved fetch, such as a Core query, and + /// answer it with `response`. + #[cfg(test)] + pub(crate) async fn expect_request( + &mut self, + request: &R, + response: R::Response, + ) -> Result<&mut Self, Error> + where + R: TransportRequest + Mockable, + R::Response: Mockable, + { + self.dapi + .lock() + .await + .expect(request, &Ok(mock_execution_response(response)))?; + Ok(self) + } + /// Returns true when requests should use proofs. /// /// ## Panics @@ -603,11 +622,7 @@ impl MockDashPlatformSdk { let mut dapi_guard = self.dapi.lock().await; dapi_guard.expect( &wire_request, - &Ok(ExecutionResponse { - inner: Default::default(), - retries: 0, - address: "http://127.0.0.1".parse().expect("failed to parse address"), - }), + &Ok(mock_execution_response(Default::default())), )?; Ok(()) @@ -722,6 +737,15 @@ fn load_expectation( Ok(()) } +/// A transport answer from the mock DAPI client carrying `inner`. +fn mock_execution_response(inner: T) -> ExecutionResponse { + ExecutionResponse { + inner, + retries: 0, + address: "http://127.0.0.1".parse().expect("failed to parse address"), + } +} + #[cfg(test)] mod recording_tests { use super::*; diff --git a/packages/rs-sdk/src/platform/dashpay/invitation.rs b/packages/rs-sdk/src/platform/dashpay/invitation.rs index debf6d7536f..79d6c27e194 100644 --- a/packages/rs-sdk/src/platform/dashpay/invitation.rs +++ b/packages/rs-sdk/src/platform/dashpay/invitation.rs @@ -68,6 +68,9 @@ use std::collections::BTreeMap; +use dpp::consensus::basic::BasicError; +use dpp::consensus::state::state_error::StateError; +use dpp::consensus::ConsensusError; use dpp::dashcore::consensus::Decodable; use dpp::dashcore::transaction::special_transaction::TransactionPayload; use dpp::dashcore::{InstantLock, Network, OutPoint, PrivateKey, ScriptBuf, Transaction, TxOut}; @@ -75,13 +78,16 @@ use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::identity_public_key::accessors::v0::{ IdentityPublicKeyGettersV0, IdentityPublicKeySettersV0, }; +use dpp::identity::identity_public_key::methods::hash::IdentityPublicKeyHashMethodsV0; use dpp::identity::signer::Signer; use dpp::identity::state_transition::asset_lock_proof::chain::ChainAssetLockProof; use dpp::identity::state_transition::asset_lock_proof::InstantAssetLockProof; use dpp::identity::v0::IdentityV0; -use dpp::identity::{Identity, IdentityPublicKey, KeyID, Purpose, SecurityLevel}; +use dpp::identity::{Identity, IdentityPublicKey, KeyID, KeyType, Purpose, SecurityLevel}; use dpp::prelude::{AssetLockProof, Identifier}; use dpp::secp256k1::{PublicKey, SecretKey}; +use dpp::state_transition::public_key_in_creation::IdentityPublicKeyInCreation; +use dpp::version::{PlatformVersion, PLATFORM_VERSIONS}; use crate::core::FetchedCoreTransaction; use crate::platform::transition::asset_lock_submission::{ @@ -90,8 +96,9 @@ use crate::platform::transition::asset_lock_submission::{ }; use crate::platform::transition::put_identity::PutIdentity; use crate::platform::transition::put_settings::PutSettings; +use crate::platform::types::identity::PublicKeyHash; use crate::platform::Fetch; -use crate::{Error, Sdk}; +use crate::{Error, ProtocolVersionInfo, Sdk}; /// Hard cap on the amount an invitation can lock (0.26 DASH). The voucher is a /// bearer credential, so the blast radius of a leaked link is bounded here in @@ -161,6 +168,46 @@ pub enum InvitationError { #[error("{0}")] NotChainLocked(String), + /// The invitation's identity already exists and holds the claimant's + /// master key: an earlier claim of the claimant landed (for example one + /// whose result was lost when the app stopped). Usually found before the + /// broadcast; Platform's consumed-outpoint refusal also reports it when a + /// node that lagged behind let the claim through and the identity's keys + /// are not exactly the submitted ones. + /// The claim does not take the identity over; the caller loads it the + /// way it loads any identity of its own. + #[error("invitation was already claimed by this claimant as identity {identity_id}")] + ClaimedByThisWallet { identity_id: Identifier }, + + /// Someone else claimed the invitation: an identity exists at its id and + /// does not hold the claimant's master key. Usually found before the + /// broadcast, else from Platform's consumed-outpoint refusal. + #[error("invitation was already claimed by identity {identity_id}")] + AlreadyClaimed { identity_id: Identifier }, + + /// A submitted key is already registered to another identity, so + /// Platform would refuse the claim and charge the voucher for it. + /// `identity_id` is that identity when the claim's own lookup found it, + /// and `None` when the refusal came from Platform after the broadcast + /// (a node that had not seen the identity yet answered the lookup). + /// `rejection` is then Platform's refusal itself (consensus error 40207, + /// or 10501 before protocol v11), kept for its consensus code. + #[error( + "a key of this claim is already registered to {}", + key_owner(identity_id) + )] + KeysAlreadyRegistered { + identity_id: Option, + #[source] + rejection: Option, + }, + + /// The claim's identity lookups could not be verified yet: the trusted + /// quorum source is not ready (see [`Error::is_quorum_source_unavailable`]). + /// Nothing was broadcast; retry once the wallet has synced. + #[error("cannot verify Platform's answer yet, retry once synced: {0}")] + NotReady(#[source] Error), + /// An SDK call failed. #[error(transparent)] Sdk(#[from] Error), @@ -270,6 +317,14 @@ impl std::fmt::Debug for ParsedInvitation { } } +/// The owner [`InvitationError::KeysAlreadyRegistered`] names in its message. +fn key_owner(identity_id: &Option) -> String { + identity_id.map_or_else( + || "another identity".to_string(), + |id| format!("identity {id}"), + ) +} + fn invalid(msg: impl Into) -> InvitationError { InvitationError::Invalid(msg.into()) } @@ -704,9 +759,88 @@ fn preflight_keys_map(keys_map: &BTreeMap) -> Result<(), )) } } + // The transition carries each key's own id, not its map position, so a + // key filed under another slot is refused: the map's keys are then no + // longer a promise that the ids are unique. Two keys sharing an id would + // be refused by Platform with 10501, the code a key registered elsewhere + // also got before protocol v11, which the claim reads as + // `KeysAlreadyRegistered`. + if let Some((slot, key)) = keys_map.iter().find(|(slot, key)| key.id() != **slot) { + return Err(InvitationError::Invalid(format!( + "keys_map entry {slot} holds key id {}", + key.id() + ))); + } + // More keys than any protocol version this build knows lets an identity + // create carry are refused here, before a lookup is started for each: + // the network's version is known only after those lookups, and a version + // newer than this build is refused then anyway. + let most_keys = PLATFORM_VERSIONS + .iter() + .map(|version| { + version + .dpp + .state_transitions + .identities + .max_public_keys_in_creation + }) + .max() + .unwrap_or_default() as usize; + if keys_map.len() > most_keys { + return Err(InvitationError::Invalid(format!( + "keys_map holds {} keys; an identity is created with at most {most_keys}", + keys_map.len() + ))); + } Ok(()) } +/// The protocol version whose rules judge a claim's keys: the newer of the +/// version this SDK builds operations with and the one the network signed in a +/// verified answer, so neither an SDK that starts below its network nor one +/// pinned below it judges by older rules. Refused when no verified answer +/// showed the network's version, or when this build lacks its rules: the keys +/// cannot be checked, and Platform refuses bad ones only after charging part +/// of the voucher. +fn claim_keys_platform_version( + info: &ProtocolVersionInfo, +) -> Result<&'static PlatformVersion, InvitationError> { + let network = info.verified_version.ok_or_else(|| { + invalid("the network's protocol version was not verified, so the identity keys cannot be checked") + })?; + let version = network.max(info.effective_version); + PlatformVersion::get(version).map_err(|_| { + invalid(format!( + "the network runs protocol version {version}, newer than this SDK knows \ + (up to {}), so the identity keys cannot be checked", + info.maximum_supported_version + )) + }) +} + +/// Refuse a key set that Platform's structural validation of an identity +/// create would refuse (duplicate key data, too many keys, master key count, +/// security levels), using that validation itself. Platform refuses those +/// only after it has charged part of the voucher. +fn validate_claim_keys_structure( + keys_map: &BTreeMap, + platform_version: &PlatformVersion, +) -> Result<(), InvitationError> { + let keys: Vec = keys_map.values().map(Into::into).collect(); + let result = IdentityPublicKeyInCreation::validate_identity_public_keys_structure( + &keys, + true, + platform_version, + ) + .map_err(|e| invalid(format!("could not validate the identity keys: {e}")))?; + match result.errors.first() { + Some(error) => Err(invalid(format!( + "Platform would refuse these identity keys: {error}" + ))), + None => Ok(()), + } +} + /// Byte-reverse a txid hex string. Old iOS invitation links carry the funding /// txid in little-endian internal order; DAPI keys `getTransaction` by the /// big-endian display id, so the claim retries with the id reversed on a miss @@ -793,18 +927,32 @@ impl Sdk { &self, invitation: &ParsedInvitation, ) -> Result { + Ok(self + .invitation_claim_status_with_identity(invitation) + .await? + .0) + } + + /// [`Sdk::invitation_claim_status`], plus the identity that claimed the + /// invitation when there is one, so the caller can tell whose claim it + /// was with [`identity_holds_master_key`]. + pub async fn invitation_claim_status_with_identity( + &self, + invitation: &ParsedInvitation, + ) -> Result<(InvitationClaimStatus, Option), InvitationError> { let funding = inspect_invitation_funding(self, invitation).await?; let prospective_identity_id = identity_id_for_out_point(funding.out_point); - let already_claimed = Identity::fetch(self, prospective_identity_id) - .await? - .is_some(); - Ok(InvitationClaimStatus { + let claimed = Identity::fetch(self, prospective_identity_id) + .await + .map_err(lookup_failure)?; + let status = InvitationClaimStatus { prospective_identity_id, amount_duffs: funding.credit_output_duffs, is_instant: funding.instant_lock.is_some(), is_chain_locked: funding.is_chain_locked, - already_claimed, - }) + already_claimed: claimed.is_some(), + }; + Ok((status, claimed)) } /// Claim a DashPay invitation: register a NEW identity for the invitee, @@ -844,9 +992,24 @@ impl Sdk { /// lock's inputs nor its tracking. `keys_map[0]` must be a MASTER-level /// AUTHENTICATION key. /// - /// A claim repeated after an earlier one landed is refused by Platform - /// because its outpoint is consumed; the identity at the prospective id is - /// returned when it carries exactly the submitted keys. + /// Before anything is broadcast, the claim looks up the identity at the + /// invitation's id and every identity registered under a submitted key's + /// hash, because Platform would charge the voucher + /// for a claim whose keys are taken. It returns, without broadcasting: + /// - [`InvitationError::ClaimedByThisWallet`] when the invitation's + /// identity holds `keys_map[0]` (an earlier claim of ours landed); + /// - [`InvitationError::AlreadyClaimed`] when someone else's identity is + /// there; + /// - [`InvitationError::KeysAlreadyRegistered`] when another identity + /// already holds one of the keys; + /// - [`InvitationError::NotReady`] or [`InvitationError::Sdk`] when a + /// lookup fails. + /// + /// A node that lags behind can still miss either identity. Platform then + /// refuses the broadcast: taken keys come back as + /// [`InvitationError::KeysAlreadyRegistered`] with no id, and a consumed + /// outpoint whose identity carries exactly the submitted keys returns that + /// identity. /// /// The caller records the returned identity in its own wallet; nothing is /// persisted here. The contact-bootstrap is a separate step: on success the @@ -881,57 +1044,285 @@ impl Sdk { )?; let prospective_identity_id = identity_id_for_out_point(out_point); - // The voucher key signs the asset lock's outer ST signature (ECDSA over - // the credit-output pubkey hash), scrubbed on every exit path by the - // native secret-key owner. - let voucher_priv = - PrivateKey::from_byte_array(&invitation.voucher_key.to_secret_bytes(), self.network) - .map_err(|e| invalid(format!("invalid invitation voucher scalar: {e}")))?; - - // Build the placeholder identity ONCE so both the primary attempt and the - // IS→CL fallback submit the same key set without a `keys_map` clone. - let placeholder = Identity::V0(IdentityV0 { - id: Identifier::default(), - public_keys: keys_map, - balance: 0, - revision: 0, - }); + let key_hashes = claim_key_hashes(&keys_map)?; + let master_key = keys_map + .get(&0) + .ok_or_else(|| invalid("keys_map must include key id=0"))? + .clone(); + let preflight = preflight_claim( + prospective_identity_id, + &master_key, + &key_hashes, + || Identity::fetch(self, prospective_identity_id), + |hash| Identity::fetch(self, PublicKeyHash(hash)), + ); + let master_key = &master_key; + + claim_unless_refused(preflight, || async move { + // Checked here, after the preflight: its lookups are proved, so the + // network's signed protocol version is known, and the keys are + // judged by the rules Platform will apply rather than by the + // version an SDK starts with or is pinned to. + let rules = claim_keys_platform_version(&self.protocol_version_info())?; + validate_claim_keys_structure(&keys_map, rules)?; + + // The voucher key signs the asset lock's outer ST signature (ECDSA + // over the credit-output pubkey hash), scrubbed on every exit path + // by the native secret-key owner. + let voucher_priv = PrivateKey::from_byte_array( + &invitation.voucher_key.to_secret_bytes(), + self.network, + ) + .map_err(|e| invalid(format!("invalid invitation voucher scalar: {e}")))?; + + // Build the placeholder identity ONCE so both the primary attempt + // and the IS→CL fallback submit the same key set without a + // `keys_map` clone. + let placeholder = Identity::V0(IdentityV0 { + id: Identifier::default(), + public_keys: keys_map, + balance: 0, + revision: 0, + }); - // Submit the primary proof first and — only when the IS proof is - // unusable (a stale islock, a claim too large to submit with it, or a - // funding transaction over the input cap) — - // the ChainLock fallback over the SAME credit output. Each - // submission is wrapped in the CL-height-too-low retry (Platform's - // observed Core tip briefly behind the proof's chain-locked height; - // harmless for an IS proof, which never triggers it). - let placeholder = &placeholder; - let voucher_priv = &voucher_priv; - let submitted = - submit_claim_with_chain_lock_fallback(primary, chain_fallback, move |proof| { - submit_with_cl_height_retry(settings, move |s| { - placeholder.put_to_platform_and_wait_for_response_with_private_key( - self, - proof.clone(), - voucher_priv, - identity_signer, - s, - ) + // Submit the primary proof first and — only when the IS proof is + // unusable (a stale islock, a claim too large to submit with it, + // or a funding transaction over the input cap) — the ChainLock + // fallback over the SAME credit output. Each submission is wrapped + // in the CL-height-too-low retry (Platform's observed Core tip briefly + // behind the proof's chain-locked height; harmless for an IS + // proof, which never triggers it). + let placeholder = &placeholder; + let voucher_priv = &voucher_priv; + let submitted = + submit_claim_with_chain_lock_fallback(primary, chain_fallback, move |proof| { + submit_with_cl_height_retry(settings, move |s| { + placeholder.put_to_platform_and_wait_for_response_with_private_key( + self, + proof.clone(), + voucher_priv, + identity_signer, + s, + ) + }) }) - }) - .await; + .await; - // A lost-ACK duplicate of this very submission ("already in the - // mempool / in chain") is resolved inside the result wait. What - // reaches here is a claim repeated after an earlier one landed, refused - // because its outpoint is consumed: adopt the identity when it carries - // exactly the keys we submitted. - adopt_already_landed_claim(submitted, &out_point, placeholder.public_keys(), || { - Identity::fetch(self, prospective_identity_id) + // A lost-ACK duplicate of this very submission ("already in the + // mempool / in chain") is resolved inside the result wait. What + // reaches here is a claim repeated after an earlier one landed, + // refused because its outpoint is consumed: adopt the identity + // when it carries exactly the keys we submitted. + adopt_already_landed_claim( + submitted, + &out_point, + placeholder.public_keys(), + master_key, + || Identity::fetch(self, prospective_identity_id), + ) + .await }) .await } } +/// The 20-byte hash of every key a claim submits: what Platform checks +/// against its unique-key index before it creates the identity +/// (`validate_unique_identity_public_key_hashes_not_in_state`), deduplicated. +fn claim_key_hashes( + keys_map: &BTreeMap, +) -> Result, InvitationError> { + let mut hashes = Vec::with_capacity(keys_map.len()); + for (id, key) in keys_map { + let hash = key + .public_key_hash() + .map_err(|e| invalid(format!("identity key {id} has no public key hash: {e}")))?; + if !hashes.contains(&hash) { + hashes.push(hash); + } + } + Ok(hashes) +} + +/// Broadcast the claim only when its preflight lets it through, and read +/// Platform's refusal of taken keys as [`InvitationError::KeysAlreadyRegistered`]. +/// +/// `preflight` and `submit` are the injectable seams (production passes +/// [`preflight_claim`] and the signed submission with its adopt path). +async fn claim_unless_refused( + preflight: P, + submit: S, +) -> Result +where + P: std::future::Future>, + S: FnOnce() -> SFut, + SFut: std::future::Future>, +{ + preflight.await?; + keys_taken_on_broadcast(submit().await) +} + +/// Whether `identity` holds `master_key`: a key of the same signing type +/// (ECDSA or BLS) with the same key data. +/// +/// This is how a claimant recognizes the identity its own earlier claim +/// created, both in the claim's preflight and in the claim status. Only the +/// key type and data count, not the purpose, security level or bounds, +/// because Platform accepts an ECDSA or BLS key into an identity only with a +/// signature made by its private key: nobody else can put our key into their +/// identity. A hash-only key type proves nothing and never matches. +pub fn identity_holds_master_key(identity: &Identity, master_key: &IdentityPublicKey) -> bool { + matches!( + master_key.key_type(), + KeyType::ECDSA_SECP256K1 | KeyType::BLS12_381 + ) && identity + .public_keys() + .values() + .any(|key| key.key_type() == master_key.key_type() && key.data() == master_key.data()) +} + +/// Look the claim up before it is broadcast, so that it is never sent when +/// Platform would refuse it and charge the voucher. +/// +/// Fetches the identity at the invitation's id and the identity under every +/// submitted key hash, concurrently, and decides from all the answers, the +/// invitation's identity first: +/// 1. it exists and holds `master_key` → [`InvitationError::ClaimedByThisWallet`]; +/// 2. it exists otherwise → [`InvitationError::AlreadyClaimed`]; +/// 3. any key hash names the invitation's identity → as in 1 and 2 (the +/// lookup by id failed or reached a node that had not seen it yet), +/// whatever the other key hashes found; +/// 4. a key hash names another identity → +/// [`InvitationError::KeysAlreadyRegistered`] (the first such identity); +/// 5. a lookup failed → [`InvitationError::NotReady`] when any failed +/// lookup could not be verified yet, else [`InvitationError::Sdk`]. +/// +/// Nothing is adopted or recorded here. +/// +/// `fetch_by_id` and `fetch_by_hash` are the injectable seams (production +/// passes `Identity::fetch` by id and by `PublicKeyHash`). +async fn preflight_claim( + prospective_identity_id: Identifier, + master_key: &IdentityPublicKey, + key_hashes: &[[u8; 20]], + fetch_by_id: FI, + fetch_by_hash: FH, +) -> Result<(), InvitationError> +where + FI: FnOnce() -> FIFut, + FIFut: std::future::Future, Error>>, + FH: Fn([u8; 20]) -> FHFut, + FHFut: std::future::Future, Error>>, +{ + let (claimed, by_hash) = futures::future::join( + fetch_by_id(), + futures::future::join_all(key_hashes.iter().map(|hash| fetch_by_hash(*hash))), + ) + .await; + + // A failed lookup by id does not stop the key-hash answers from + // deciding: one of them may name the invitation's identity or a taken key. + let mut lookup_error = None; + let mut foreign_owner = None; + match claimed { + Ok(Some(identity)) => return Err(claimed_by(&identity, master_key)), + Ok(None) => {} + Err(error) => lookup_error = Some(error), + } + for result in by_hash { + match result { + // Each lookup may reach a different node: one that already has + // the invitation's identity can answer a key hash while the one + // asked by id had not seen it yet. + Ok(Some(identity)) if identity.id() == prospective_identity_id => { + return Err(claimed_by(&identity, master_key)); + } + // A later key hash may still name the invitation's identity, + // which decides first. + Ok(Some(identity)) => { + foreign_owner.get_or_insert(identity.id()); + } + Ok(None) => {} + // Keep "not verified yet" over any other failure: it is the one + // that tells the caller to retry once synced. + Err(error) => { + let keep = lookup_error + .as_ref() + .is_some_and(Error::is_quorum_source_unavailable); + if !keep { + lookup_error = Some(error); + } + } + } + } + if let Some(identity_id) = foreign_owner { + return Err(InvitationError::KeysAlreadyRegistered { + identity_id: Some(identity_id), + rejection: None, + }); + } + match lookup_error { + Some(error) => Err(lookup_failure(error)), + None => Ok(()), + } +} + +/// Whose claim the invitation's existing identity is. +fn claimed_by(identity: &Identity, master_key: &IdentityPublicKey) -> InvitationError { + if identity_holds_master_key(identity, master_key) { + InvitationError::ClaimedByThisWallet { + identity_id: identity.id(), + } + } else { + InvitationError::AlreadyClaimed { + identity_id: identity.id(), + } + } +} + +/// A preflight lookup that failed: [`InvitationError::NotReady`] when the +/// trusted quorum source could not vouch for the answer yet. +fn lookup_failure(error: Error) -> InvitationError { + if error.is_quorum_source_unavailable() { + InvitationError::NotReady(error) + } else { + InvitationError::Sdk(error) + } +} + +/// Platform refused the broadcast claim because one of its keys is already +/// registered to another identity: 40207 (`DuplicatedIdentityPublicKeyIdStateError`), +/// or 10501 (`DuplicatedIdentityPublicKeyIdBasicError`) before protocol v11. +/// That refusal is final for these keys, so it becomes +/// [`InvitationError::KeysAlreadyRegistered`], which keeps the refusal for +/// its consensus code. 10501 is also Platform's answer +/// to two keys sharing an id inside one transition, which +/// [`preflight_keys_map`] refuses before anything is sent. +fn keys_taken_on_broadcast( + result: Result, +) -> Result { + match result { + Err(InvitationError::Sdk(error)) if is_identity_key_already_registered(&error) => { + Err(InvitationError::KeysAlreadyRegistered { + identity_id: None, + rejection: Some(error), + }) + } + other => other, + } +} + +fn is_identity_key_already_registered(error: &Error) -> bool { + matches!( + error.consensus_error(), + Some(ConsensusError::StateError( + StateError::DuplicatedIdentityPublicKeyIdStateError(_) + )) | Some(ConsensusError::BasicError( + BasicError::DuplicatedIdentityPublicKeyIdBasicError(_) + )) + ) +} + /// The wrong-network guard, the funding-tx fetch and its inspection: what /// the invitee's read-only queries need, without requiring the tx to be /// claimable yet (see [`inspect_funding_tx`]). @@ -1113,15 +1504,18 @@ fn identity_id_for_out_point(out_point: OutPoint) -> Identifier { /// earlier attempt landed (reported as a failure, or interrupted) is refused /// because its outpoint is consumed; the identity at the prospective id is /// ours when it carries exactly the keys we submitted, and is then the -/// claim's result. Anything else (no identity, someone else's, a failed -/// lookup) reports the original rejection. +/// claim's result. Another identity there is reported as whose claim it is +/// ([`InvitationError::ClaimedByThisWallet`] when it holds our master key, +/// else [`InvitationError::AlreadyClaimed`]); no identity or a failed lookup +/// reports the original rejection. /// -/// `fetch` looks up the identity at the prospective id: the injectable seam -/// (production passes `Identity::fetch`). +/// `master_key` is the submitted key 0. `fetch` looks up the identity at the +/// prospective id: the injectable seam (production passes `Identity::fetch`). async fn adopt_already_landed_claim( submitted: Result, out_point: &OutPoint, submitted_keys: &BTreeMap, + master_key: &IdentityPublicKey, fetch: F, ) -> Result where @@ -1142,7 +1536,10 @@ where ); Ok(identity) } - Ok(_) => Err(InvitationError::Sdk(error)), + // Not exactly our submission, but whose claim it is still matters: + // our master key at another index, or keys changed since, is ours. + Ok(Some(identity)) => Err(claimed_by(&identity, master_key)), + Ok(None) => Err(InvitationError::Sdk(error)), Err(lookup) => { tracing::warn!( error = %lookup, @@ -2095,6 +2492,563 @@ mod tests { ); } + /// Two keys with the same id would be refused by Platform with the code + /// the claim reads as "keys already registered", so they never leave. + #[test] + fn should_refuse_a_keys_map_whose_key_ids_differ_from_their_slots() { + let mut keys = our_keys(); + keys.insert(2, test_key(1, 3)); + assert!(matches!( + preflight_keys_map(&keys), + Err(InvitationError::Invalid(_)) + )); + assert!(preflight_keys_map(&our_keys()).is_ok()); + } + + /// A keys map larger than any known protocol version lets an identity + /// create carry is refused before a lookup is started for each key; one + /// at the limit passes. + #[test] + fn should_refuse_more_keys_than_any_version_allows_before_the_lookups() { + let most = PLATFORM_VERSIONS + .iter() + .map(|v| { + v.dpp + .state_transitions + .identities + .max_public_keys_in_creation + }) + .max() + .expect("versions") as u32; + let mut keys = our_keys(); + for id in 1..most { + keys.insert(id, test_key(id, id as u8 + 1)); + } + assert!(preflight_keys_map(&keys).is_ok()); + keys.insert(most, test_key(most, most as u8 + 1)); + assert!(matches!( + preflight_keys_map(&keys), + Err(InvitationError::Invalid(_)) + )); + } + + /// A key set Platform's structural validation refuses (here two keys with + /// the same data, refused with 10500 after part of the voucher is charged) + /// never leaves; a valid set passes. + #[test] + fn should_refuse_keys_platform_refuses_structurally() { + let high = |id: KeyID, byte: u8| { + let mut key = test_key(id, byte); + key.set_security_level(SecurityLevel::HIGH); + key + }; + let platform_version = PlatformVersion::latest(); + let valid: BTreeMap = + [(0, test_key(0, 1)), (1, high(1, 2))].into(); + assert!(validate_claim_keys_structure(&valid, platform_version).is_ok()); + + let duplicate_data: BTreeMap = + [(0, test_key(0, 1)), (1, high(1, 1))].into(); + assert!(matches!( + validate_claim_keys_structure(&duplicate_data, platform_version), + Err(InvitationError::Invalid(_)) + )); + } + + /// The claim's keys are judged by the newer of the SDK's version and the + /// network's verified one, so an SDK started or pinned at an older version + /// still refuses keys the network's rules refuse. A hash key whose data is + /// not 20 bytes passes protocol version 13 and is refused by the latest. + /// Without a verified version, or with one this build has no rules for, + /// the keys cannot be checked and the claim is refused. + #[test] + fn should_judge_claim_keys_by_the_networks_verified_version() { + use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; + use dpp::platform_value::BinaryData; + + let latest = PlatformVersion::latest().protocol_version; + let info = |verified: Option, effective: u32| ProtocolVersionInfo { + verified_version: verified, + effective_version: effective, + maximum_supported_version: latest, + newer_protocol_available: verified.is_some_and(|v| v > latest), + }; + let short_hash_key = IdentityPublicKey::V0(IdentityPublicKeyV0 { + id: 1, + purpose: Purpose::AUTHENTICATION, + security_level: SecurityLevel::HIGH, + contract_bounds: None, + key_type: KeyType::ECDSA_HASH160, + read_only: false, + data: BinaryData::new(vec![7; 19]), + disabled_at: None, + }); + let keys: BTreeMap = + [(0, test_key(0, 1)), (1, short_hash_key)].into(); + + let v13 = PlatformVersion::get(13).expect("v13"); + assert!(validate_claim_keys_structure(&keys, v13).is_ok()); + + // Started or pinned at 13, network verified at the latest. + let rules = claim_keys_platform_version(&info(Some(latest), 13)).expect("known"); + assert_eq!(rules.protocol_version, latest); + assert!(matches!( + validate_claim_keys_structure(&keys, rules), + Err(InvitationError::Invalid(_)) + )); + + // Pinned ahead of the network: its own, newer rules. + let rules = claim_keys_platform_version(&info(Some(13), latest)).expect("known"); + assert_eq!(rules.protocol_version, latest); + + assert!(matches!( + claim_keys_platform_version(&info(None, latest)), + Err(InvitationError::Invalid(_)) + )); + assert!(matches!( + claim_keys_platform_version(&info(Some(latest + 1), 13)), + Err(InvitationError::Invalid(_)) + )); + } + + /// The claim looks up the hash of every key it submits, once each, and a + /// key with no valid hash stops the claim before any lookup. + #[test] + fn should_hash_every_submitted_key_once() { + use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; + use dpp::platform_value::BinaryData; + + let hash_key = |id: KeyID, byte: u8| { + IdentityPublicKey::V0(IdentityPublicKeyV0 { + id, + purpose: Purpose::AUTHENTICATION, + security_level: SecurityLevel::HIGH, + contract_bounds: None, + key_type: KeyType::ECDSA_HASH160, + read_only: false, + data: BinaryData::new(vec![byte; 20]), + disabled_at: None, + }) + }; + let keys: BTreeMap = [ + (0, hash_key(0, 1)), + (1, hash_key(1, 2)), + (2, hash_key(2, 1)), + ] + .into(); + assert_eq!(claim_key_hashes(&keys).unwrap(), vec![[1u8; 20], [2u8; 20]]); + + // `test_key` data is 33 bytes that are not a secp256k1 point. + assert!(matches!( + claim_key_hashes(&our_keys()), + Err(InvitationError::Invalid(_)) + )); + } + + /// Our identity is recognized by the master key's type and data alone, + /// whatever the key's other fields; a hash-only key never matches. + #[test] + fn should_recognize_our_identity_by_the_master_key_data() { + let master = test_key(0, 1); + let mut moved = test_key(5, 1); + moved.set_security_level(SecurityLevel::HIGH); + moved.set_purpose(Purpose::TRANSFER); + assert!(identity_holds_master_key( + &identity_with_keys([(5, moved)].into()), + &master + )); + assert!(!identity_holds_master_key( + &identity_with_keys([(0, test_key(0, 9))].into()), + &master + )); + + let mut hash_only = test_key(0, 1); + hash_only.set_key_type(KeyType::ECDSA_HASH160); + assert!(!identity_holds_master_key( + &identity_with_keys([(0, hash_only)].into()), + &master + )); + + // A BLS master key is signed into its identity too; the same bytes + // under another key type are not the same key. + let mut bls_master = test_key(0, 1); + bls_master.set_key_type(KeyType::BLS12_381); + let bls_identity = identity_with_keys([(0, bls_master.clone())].into()); + assert!(identity_holds_master_key(&bls_identity, &bls_master)); + assert!(!identity_holds_master_key(&bls_identity, &master)); + assert!(!identity_holds_master_key( + &identity_with_keys([(0, test_key(0, 1))].into()), + &bls_master + )); + } + + // --- preflight_claim: never broadcast a claim Platform would charge for --- + + mod claim_preflight { + use std::cell::RefCell; + + use super::super::{claim_unless_refused, preflight_claim, Error, InvitationError}; + use super::{identity_with_keys, our_keys, test_key}; + use crate::error::ContextProviderError; + use dpp::identity::accessors::{IdentityGettersV0, IdentitySettersV0}; + use dpp::identity::{Identity, IdentityPublicKey, KeyID}; + use dpp::prelude::Identifier; + use std::collections::BTreeMap; + + const OUR_HASH: [u8; 20] = [1u8; 20]; + const OTHER_HASH: [u8; 20] = [2u8; 20]; + + fn identity(id: u8, keys: BTreeMap) -> Identity { + let mut identity = identity_with_keys(keys); + identity.set_id(Identifier::new([id; 32])); + identity + } + + fn ours() -> Identity { + identity(1, our_keys()) + } + + fn theirs() -> Identity { + identity(2, [(0, test_key(0, 9))].into()) + } + + fn not_ready() -> Error { + Error::ContextProviderError(ContextProviderError::QuorumSourceUnavailable( + "not verified yet".to_string(), + )) + } + + fn timeout() -> Error { + Error::Generic("timeout".to_string()) + } + + /// Run the preflight with a scripted lookup by id and by each hash, + /// recording the hashes it looked up. + async fn preflight( + by_id: Result, Error>, + by_hash: impl Fn([u8; 20]) -> Result, Error>, + ) -> (Result<(), InvitationError>, Vec<[u8; 20]>) { + let looked_up = RefCell::new(Vec::new()); + let master = test_key(0, 1); + let result = preflight_claim( + ours().id(), + &master, + &[OUR_HASH, OTHER_HASH], + || async { by_id }, + |hash| { + looked_up.borrow_mut().push(hash); + let answer = by_hash(hash); + async move { answer } + }, + ) + .await; + (result, looked_up.into_inner()) + } + + #[tokio::test] + async fn should_let_the_claim_through_when_nothing_is_registered() { + let (result, looked_up) = preflight(Ok(None), |_| Ok(None)).await; + assert!(result.is_ok()); + assert_eq!(looked_up, vec![OUR_HASH, OTHER_HASH]); + } + + #[tokio::test] + async fn should_report_our_own_landed_claim_without_adopting_it() { + let (result, _) = preflight(Ok(Some(ours())), |_| Ok(Some(ours()))).await; + assert!(matches!( + result, + Err(InvitationError::ClaimedByThisWallet { identity_id }) + if identity_id == ours().id() + )); + } + + /// The invitation's identity is fetched by its id, so our claim is + /// recognized even when no key-hash lookup finds it (its master key + /// sits in the non-unique index, or under another security level). + #[tokio::test] + async fn should_recognize_our_claim_that_no_key_hash_finds() { + let (result, _) = preflight(Ok(Some(ours())), |_| Ok(None)).await; + assert!(matches!( + result, + Err(InvitationError::ClaimedByThisWallet { .. }) + )); + } + + #[tokio::test] + async fn should_report_a_claim_by_someone_else() { + let (result, _) = preflight(Ok(Some(theirs())), |_| Ok(None)).await; + assert!(matches!( + result, + Err(InvitationError::AlreadyClaimed { identity_id }) if identity_id == theirs().id() + )); + } + + /// The invitation's identity decides before any key hash does. + #[tokio::test] + async fn should_put_the_invitations_identity_before_taken_keys() { + let (result, _) = preflight(Ok(Some(theirs())), |_| Ok(Some(ours()))).await; + assert!(matches!( + result, + Err(InvitationError::AlreadyClaimed { .. }) + )); + + // The lookup by id failed, but a key hash names the invitation's + // own identity: that answer stands. + let (result, _) = preflight(Err(timeout()), |_| Ok(Some(ours()))).await; + assert!(matches!( + result, + Err(InvitationError::ClaimedByThisWallet { .. }) + )); + let (result, _) = preflight(Err(timeout()), |_| Ok(None)).await; + assert!(matches!(result, Err(InvitationError::Sdk(_)))); + } + + /// Another identity of this wallet already holds the keys (the slot + /// was registered before): Platform would refuse the claim and charge + /// the voucher, so it is never sent. + #[tokio::test] + async fn should_refuse_keys_another_identity_holds() { + let (result, _) = preflight(Ok(None), |hash| { + Ok((hash == OTHER_HASH).then(|| identity(3, our_keys()))) + }) + .await; + assert!(matches!( + result, + Err(InvitationError::KeysAlreadyRegistered { identity_id: Some(id), .. }) + if id == Identifier::new([3; 32]) + )); + } + + /// A key that is known to be taken is the answer, even when another + /// key's lookup failed. + #[tokio::test] + async fn should_prefer_a_taken_key_over_a_failed_lookup() { + let (result, _) = preflight(Ok(None), |hash| { + if hash == OUR_HASH { + Err(timeout()) + } else { + Ok(Some(theirs())) + } + }) + .await; + assert!(matches!( + result, + Err(InvitationError::KeysAlreadyRegistered { + identity_id: Some(_), + .. + }) + )); + } + + #[tokio::test] + async fn should_not_claim_when_a_lookup_cannot_be_verified_yet() { + let (result, _) = preflight(Err(not_ready()), |_| Ok(None)).await; + assert!(matches!(result, Err(InvitationError::NotReady(_)))); + + let (result, _) = preflight(Ok(None), |hash| { + if hash == OTHER_HASH { + Err(Error::NoAvailableAddressesToRetry(Box::new(not_ready()))) + } else { + Ok(None) + } + }) + .await; + assert!(matches!(result, Err(InvitationError::NotReady(_)))); + } + + /// The node asked by id has not seen the invitation's identity yet, + /// but a node asked by key hash has: it is still whose claim it is + /// that counts, not "keys taken". + #[tokio::test] + async fn should_read_the_invitations_identity_found_by_hash_as_a_claim() { + let (result, _) = preflight(Ok(None), |_| Ok(Some(ours()))).await; + assert!(matches!( + result, + Err(InvitationError::ClaimedByThisWallet { identity_id }) if identity_id == ours().id() + )); + + let squatter = identity(1, [(0, test_key(0, 9))].into()); + let (result, _) = preflight(Ok(None), move |_| Ok(Some(squatter.clone()))).await; + assert!(matches!( + result, + Err(InvitationError::AlreadyClaimed { .. }) + )); + } + + /// A key hash that names the invitation's identity decides whatever + /// an earlier key hash found: the order the keys were submitted in + /// does not turn our claim into "keys taken". + #[tokio::test] + async fn should_put_the_invitations_identity_before_an_earlier_taken_key() { + for by_id in [Ok(None), Err(timeout())] { + let (result, _) = preflight(by_id, |hash| { + Ok(Some(if hash == OUR_HASH { theirs() } else { ours() })) + }) + .await; + assert!(matches!( + result, + Err(InvitationError::ClaimedByThisWallet { identity_id }) + if identity_id == ours().id() + )); + } + } + + /// A refused preflight never reaches the submission (which signs and + /// broadcasts), and Platform's refusal of taken keys is typed. + #[tokio::test] + async fn should_broadcast_only_after_the_preflight_lets_the_claim_through() { + let refused = claim_unless_refused( + async { + Err(InvitationError::AlreadyClaimed { + identity_id: ours().id(), + }) + }, + || async { panic!("a refused claim must never be broadcast") }, + ) + .await; + assert!(matches!( + refused, + Err(InvitationError::AlreadyClaimed { .. }) + )); + + let taken = claim_unless_refused(async { Ok(()) }, || async { + Err(super::taken_keys_refusal()) + }) + .await; + assert!(matches!( + taken, + Err(InvitationError::KeysAlreadyRegistered { + identity_id: None, + rejection: Some(_), + }) + )); + + let claimed = claim_unless_refused(async { Ok(()) }, || async { Ok(ours()) }).await; + assert!(claimed.is_ok()); + } + + /// "Not verified yet" outlives any other failed key-hash lookup, so + /// the caller keeps its retry-once-synced signal. + #[tokio::test] + async fn should_keep_not_ready_over_a_failed_lookup_by_id() { + let (result, _) = preflight(Err(timeout()), |_| Err(not_ready())).await; + assert!(matches!(result, Err(InvitationError::NotReady(_)))); + + let (result, _) = preflight(Err(not_ready()), |_| Err(timeout())).await; + assert!(matches!(result, Err(InvitationError::NotReady(_)))); + } + + /// A key known to be taken decides even when the lookup by id failed. + #[tokio::test] + async fn should_refuse_taken_keys_when_the_lookup_by_id_failed() { + let (result, _) = preflight(Err(timeout()), |_| Ok(Some(theirs()))).await; + assert!(matches!( + result, + Err(InvitationError::KeysAlreadyRegistered { + identity_id: Some(_), + .. + }) + )); + } + + #[tokio::test] + async fn should_keep_not_ready_over_another_failed_lookup() { + for not_ready_hash in [OUR_HASH, OTHER_HASH] { + let (result, _) = preflight(Ok(None), |hash| { + if hash == not_ready_hash { + Err(not_ready()) + } else { + Err(timeout()) + } + }) + .await; + assert!(matches!(result, Err(InvitationError::NotReady(_)))); + } + } + + #[tokio::test] + async fn should_not_claim_when_a_lookup_fails() { + let (result, _) = preflight(Ok(None), |_| Err(timeout())).await; + assert!(matches!( + result, + Err(InvitationError::Sdk(Error::Generic(_))) + )); + } + } + + /// Platform's 40207 refusal of a claim whose keys are taken. + fn taken_keys_refusal() -> InvitationError { + use dpp::consensus::state::identity::duplicated_identity_public_key_id_state_error::DuplicatedIdentityPublicKeyIdStateError; + use dpp::consensus::state::state_error::StateError; + use dpp::consensus::ConsensusError; + + InvitationError::Sdk(Error::Protocol(dpp::ProtocolError::ConsensusError( + Box::new(ConsensusError::StateError( + StateError::DuplicatedIdentityPublicKeyIdStateError( + DuplicatedIdentityPublicKeyIdStateError::new(vec![0]), + ), + )), + ))) + } + + // --- keys_taken_on_broadcast: Platform's refusal of taken keys --- + + mod taken_keys_backstop { + use super::super::{keys_taken_on_broadcast, Error, InvitationError}; + use super::{identity_with_keys, our_keys}; + use dpp::consensus::basic::identity::{ + DataContractBoundsNotPresentError, DuplicatedIdentityPublicKeyIdBasicError, + }; + use dpp::consensus::basic::BasicError; + use dpp::consensus::codes::ErrorWithCode; + use dpp::consensus::state::identity::duplicated_identity_public_key_id_state_error::DuplicatedIdentityPublicKeyIdStateError; + use dpp::consensus::state::state_error::StateError; + use dpp::consensus::ConsensusError; + use dpp::prelude::Identifier; + + fn refused(error: ConsensusError) -> InvitationError { + InvitationError::Sdk(Error::Protocol(dpp::ProtocolError::ConsensusError( + Box::new(error), + ))) + } + + #[test] + fn should_read_a_duplicate_key_refusal_as_taken_keys() { + for error in [ + ConsensusError::StateError(StateError::DuplicatedIdentityPublicKeyIdStateError( + DuplicatedIdentityPublicKeyIdStateError::new(vec![0]), + )), + ConsensusError::BasicError(BasicError::DuplicatedIdentityPublicKeyIdBasicError( + DuplicatedIdentityPublicKeyIdBasicError::new(vec![0]), + )), + ] { + let code = error.code(); + // The refusal stays with the typed outcome, for its consensus code. + match keys_taken_on_broadcast(Err(refused(error))) { + Err(InvitationError::KeysAlreadyRegistered { + identity_id: None, + rejection: Some(rejection), + }) => assert_eq!(rejection.consensus_error().map(|e| e.code()), Some(code)), + other => panic!("expected taken keys, got {other:?}"), + } + } + } + + /// Platform charges the voucher for other refusals too (a key's + /// contract bounds); those are not about taken keys. + #[test] + fn should_pass_other_refusals_and_successes_through() { + let bounds = ConsensusError::BasicError(BasicError::DataContractBoundsNotPresentError( + DataContractBoundsNotPresentError::new(Identifier::new([4; 32])), + )); + assert!(matches!( + keys_taken_on_broadcast(Err(refused(bounds))), + Err(InvitationError::Sdk(Error::Protocol(_))) + )); + assert!(keys_taken_on_broadcast(Ok(identity_with_keys(our_keys()))).is_ok()); + } + } + // --- adopt_already_landed_claim: recognizing our own earlier claim --- mod claim_adoption { @@ -2139,11 +3093,12 @@ mod tests { ) -> (Result, u32) { let calls = Cell::new(0); let keys = our_keys(); - let result = adopt_already_landed_claim(submitted, &out_point(), &keys, || { - calls.set(calls.get() + 1); - async { lookup } - }) - .await; + let result = + adopt_already_landed_claim(submitted, &out_point(), &keys, &keys[&0], || { + calls.set(calls.get() + 1); + async { lookup } + }) + .await; (result, calls.get()) } @@ -2166,14 +3121,35 @@ mod tests { } #[tokio::test] - async fn should_report_the_rejection_when_someone_else_claimed_first() { + async fn should_report_a_claim_by_someone_else_first() { let theirs: BTreeMap = [(0, test_key(0, 9))].into(); let (result, _) = adopt( Err(consumed(out_point())), Ok(Some(identity_with_keys(theirs))), ) .await; - assert!(is_consumed(&result)); + assert!(matches!( + result, + Err(InvitationError::AlreadyClaimed { .. }) + )); + } + + /// An identity that holds our master key but not exactly the keys we + /// submitted (keys changed since, or our claim at another index) is + /// ours, though not adopted as this claim's result. + #[tokio::test] + async fn should_report_our_master_key_with_other_keys_as_our_claim() { + let changed: BTreeMap = + [(0, test_key(0, 1)), (1, test_key(1, 7))].into(); + let (result, _) = adopt( + Err(consumed(out_point())), + Ok(Some(identity_with_keys(changed))), + ) + .await; + assert!(matches!( + result, + Err(InvitationError::ClaimedByThisWallet { .. }) + )); } /// A reclaim top-up consumes the outpoint without creating the @@ -2753,4 +3729,313 @@ mod tests { assert_eq!(submitted.len(), 2, "no third submission may follow"); } } + + /// `Sdk::claim_invitation` against a mock SDK: the funding transaction + /// comes from Core, the preflight looks up the invitation's id and every + /// submitted key hash, and a refusal ends the claim before anything is + /// signed. The mock answers no broadcast and the signer signs nothing, so + /// a claim that reached the submission would fail with another error. + #[cfg(feature = "mocks")] + mod claim_through_the_sdk { + use super::super::{claim_key_hashes, identity_id_for_out_point, Error, InvitationError}; + use super::{asset_lock_tx_paying_voucher_at, identity_with_keys, parsed, voucher}; + use crate::platform::types::identity::PublicKeyHash; + use crate::SdkBuilder; + use dapi_grpc::core::v0::{GetTransactionRequest, GetTransactionResponse}; + use dapi_grpc::platform::v0::ResponseMetadata; + use dpp::address_funds::AddressWitness; + use dpp::dashcore::consensus::Encodable; + use dpp::dashcore::{Network, OutPoint}; + use dpp::identity::accessors::IdentitySettersV0; + use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; + use dpp::identity::signer::Signer; + use dpp::identity::{Identity, IdentityPublicKey, KeyID, KeyType, Purpose, SecurityLevel}; + use dpp::platform_value::BinaryData; + use dpp::prelude::Identifier; + use dpp::secp256k1::{PublicKey, SecretKey}; + use dpp::version::PlatformVersion; + use dpp::ProtocolError; + use std::collections::BTreeMap; + + #[derive(Debug)] + struct UnusedSigner; + + #[async_trait::async_trait] + impl Signer for UnusedSigner { + async fn sign( + &self, + _key: &IdentityPublicKey, + _data: &[u8], + ) -> Result { + Err(ProtocolError::Generic( + "not signing in this test".to_string(), + )) + } + + async fn sign_create_witness( + &self, + _key: &IdentityPublicKey, + _data: &[u8], + ) -> Result { + Err(ProtocolError::Generic( + "not signing in this test".to_string(), + )) + } + + fn can_sign_with(&self, _key: &IdentityPublicKey) -> bool { + true + } + } + + /// Two keys with real secp256k1 points, which Platform hashes for + /// its unique-key index: the master key and one more. + fn claim_keys() -> BTreeMap { + [0x31u8, 0x32] + .into_iter() + .zip(0..) + .map(|(byte, id)| { + let secret = SecretKey::from_secret_bytes([byte; 32]).expect("valid scalar"); + let key = IdentityPublicKey::V0(IdentityPublicKeyV0 { + id, + purpose: Purpose::AUTHENTICATION, + security_level: if id == 0 { + SecurityLevel::MASTER + } else { + SecurityLevel::HIGH + }, + contract_bounds: None, + key_type: KeyType::ECDSA_SECP256K1, + read_only: false, + data: BinaryData::new( + PublicKey::from_secret_key(&secret).serialize().to_vec(), + ), + disabled_at: None, + }); + (id, key) + }) + .collect() + } + + fn identity_at(id: Identifier) -> Identity { + let mut identity = identity_with_keys(claim_keys()); + identity.set_id(id); + identity + } + + /// Claim a chain-locked invitation with `claim_keys()`. `by_id` answers + /// the lookup of the invitation's identity and `by_hash` the lookup of + /// each submitted key hash; it gets the invitation's id. + async fn claim( + by_id: impl FnOnce(Identifier) -> Option, + by_hash: impl Fn([u8; 20], Identifier) -> Option, + ) -> (Result, Identifier) { + claim_with_keys(claim_keys(), by_id, by_hash).await + } + + /// [`claim`] with the given keys, on a network whose verified answers + /// are signed at the latest protocol version. + async fn claim_with_keys( + keys: BTreeMap, + by_id: impl FnOnce(Identifier) -> Option, + by_hash: impl Fn([u8; 20], Identifier) -> Option, + ) -> (Result, Identifier) { + claim_on( + None, + Some(PlatformVersion::latest().protocol_version), + keys, + by_id, + by_hash, + ) + .await + } + + /// [`claim_with_keys`] with an SDK pinned to `pinned` (else unpinned), + /// on a network whose verified answers are signed at `network` (else + /// none was verified). The mock answers without proofs, so the + /// network's version is recorded as a verified answer would record it. + async fn claim_on( + pinned: Option<&'static PlatformVersion>, + network: Option, + keys: BTreeMap, + by_id: impl FnOnce(Identifier) -> Option, + by_hash: impl Fn([u8; 20], Identifier) -> Option, + ) -> (Result, Identifier) { + let key = voucher(); + let tx = asset_lock_tx_paying_voucher_at(&key, 0); + let txid = tx.txid().to_string(); + let invitation_id = identity_id_for_out_point(OutPoint::new(tx.txid(), 0)); + let mut raw = Vec::new(); + tx.consensus_encode(&mut raw) + .expect("encode the funding tx"); + + let mut builder = SdkBuilder::new_mock().with_network(Network::Testnet); + if let Some(version) = pinned { + builder = builder.with_version(version); + } + let mut sdk = builder.build().expect("mock sdk"); + if let Some(protocol_version) = network { + let metadata = ResponseMetadata { + protocol_version, + height: 1, + time_ms: chrono::Utc::now().timestamp_millis() as u64, + ..Default::default() + }; + sdk.accept_verified_metadata("test", &metadata, None) + .expect("fresh metadata"); + } + sdk.mock() + .expect_request( + &GetTransactionRequest { id: txid.clone() }, + GetTransactionResponse { + transaction: raw, + height: 100, + is_chain_locked: true, + ..Default::default() + }, + ) + .await + .expect("expect the funding tx"); + sdk.mock() + .expect_fetch(invitation_id, by_id(invitation_id)) + .await + .expect("expect the lookup by id"); + for hash in claim_key_hashes(&keys).expect("key hashes") { + sdk.mock() + .expect_fetch(PublicKeyHash(hash), by_hash(hash, invitation_id)) + .await + .expect("expect the lookup by key hash"); + } + + let result = sdk + .claim_invitation(parsed(key, txid, None), keys, &UnusedSigner, None) + .await; + (result, invitation_id) + } + + #[tokio::test] + async fn should_stop_the_claim_at_our_identity_found_by_id() { + let (result, invitation_id) = claim(|id| Some(identity_at(id)), |_, _| None).await; + assert!( + matches!( + result, + Err(InvitationError::ClaimedByThisWallet { identity_id }) + if identity_id == invitation_id + ), + "got {result:?}" + ); + } + + /// The lookup of the last submitted key, not only the master key, + /// decides: another identity holding it stops the claim. + #[tokio::test] + async fn should_stop_the_claim_at_a_taken_key_found_by_its_hash() { + let foreign = Identifier::new([9; 32]); + let last_hash = *claim_key_hashes(&claim_keys()) + .expect("key hashes") + .last() + .expect("a key hash"); + let (result, _) = claim( + |_| None, + |hash, _| (hash == last_hash).then(|| identity_at(foreign)), + ) + .await; + assert!( + matches!( + result, + Err(InvitationError::KeysAlreadyRegistered { identity_id: Some(id), rejection: None }) + if id == foreign + ), + "got {result:?}" + ); + } + + /// Keys Platform's structural validation refuses (two with the same + /// data) pass the preflight lookups but stop before anything is signed. + #[tokio::test] + async fn should_refuse_structurally_invalid_keys_before_signing() { + use dpp::identity::identity_public_key::accessors::v0::{ + IdentityPublicKeyGettersV0, IdentityPublicKeySettersV0, + }; + + let mut keys = claim_keys(); + let master_data = keys[&0].data().clone(); + keys.get_mut(&1).expect("key 1").set_data(master_data); + let (result, _) = claim_with_keys(keys, |_| None, |_, _| None).await; + assert!( + matches!(&result, Err(InvitationError::Invalid(message)) + if message.starts_with("Platform would refuse these identity keys")), + "got {result:?}" + ); + } + + /// A master key with a budget passes protocol version 13's structural + /// validation and is refused by the latest. An SDK pinned to 13 on a + /// network that signed its answers at the latest still refuses it + /// before signing; on a network at 13 the claim goes on to the signer. + #[tokio::test] + async fn should_judge_keys_by_the_networks_version_on_a_pinned_sdk() { + use dpp::identity::identity_public_key::v1::IdentityPublicKeyV1; + + let mut keys = claim_keys(); + let IdentityPublicKey::V0(master) = keys[&0].clone() else { + panic!("claim_keys() builds V0 keys"); + }; + keys.insert( + 0, + IdentityPublicKey::V1(IdentityPublicKeyV1::from_v0_with_limits( + master, + Some(1_000), + None, + )), + ); + let v13 = PlatformVersion::get(13).expect("v13"); + let latest = PlatformVersion::latest().protocol_version; + + let (result, _) = + claim_on(Some(v13), Some(latest), keys.clone(), |_| None, |_, _| None).await; + assert!( + matches!(&result, Err(InvitationError::Invalid(message)) + if message.starts_with("Platform would refuse these identity keys")), + "got {result:?}" + ); + + let (result, _) = claim_on(Some(v13), Some(13), keys, |_| None, |_, _| None).await; + assert!( + matches!( + &result, + Err(InvitationError::Sdk(Error::Protocol(ProtocolError::Generic(message)))) + if message == "not signing in this test" + ), + "got {result:?}" + ); + } + + /// Without a verified answer the network's protocol version is not + /// known, so the keys cannot be checked and nothing is signed. + #[tokio::test] + async fn should_refuse_when_the_networks_version_was_not_verified() { + let (result, _) = claim_on(None, None, claim_keys(), |_| None, |_, _| None).await; + assert!( + matches!(&result, Err(InvitationError::Invalid(message)) + if message.contains("protocol version was not verified")), + "got {result:?}" + ); + } + + /// With nothing registered the claim goes on to the submission and + /// fails only at the signer: the mock answers the lookups the two + /// tests above stopped at. + #[tokio::test] + async fn should_reach_the_submission_when_nothing_is_registered() { + let (result, _) = claim(|_| None, |_, _| None).await; + assert!( + matches!( + &result, + Err(InvitationError::Sdk(Error::Protocol(ProtocolError::Generic(message)))) + if message == "not signing in this test" + ), + "got {result:?}" + ); + } + } } diff --git a/packages/rs-sdk/src/platform/dashpay/mod.rs b/packages/rs-sdk/src/platform/dashpay/mod.rs index 83352890a63..74680bb2503 100644 --- a/packages/rs-sdk/src/platform/dashpay/mod.rs +++ b/packages/rs-sdk/src/platform/dashpay/mod.rs @@ -19,9 +19,9 @@ pub use contact_request::{ }; pub use contact_request_queries::{ContactRequestDocuments, ResumableContactRequests}; pub use invitation::{ - encode_invitation_uri, parse_invitation_uri, voucher_credit_output, voucher_output_index, - wif_network_matches, InvitationClaimStatus, InvitationError, InviterInfo, ParsedInvitation, - MAX_INVITATION_DUFFS, MAX_INVITATION_TTL_SECS, MIN_INVITATION_DUFFS, + encode_invitation_uri, identity_holds_master_key, parse_invitation_uri, voucher_credit_output, + voucher_output_index, wif_network_matches, InvitationClaimStatus, InvitationError, InviterInfo, + ParsedInvitation, MAX_INVITATION_DUFFS, MAX_INVITATION_TTL_SECS, MIN_INVITATION_DUFFS, }; pub use private_contact_request::{ private_contact_request_identities, private_contact_request_outgoing_viewing_key, diff --git a/packages/rs-unified-sdk-jni/src/identity.rs b/packages/rs-unified-sdk-jni/src/identity.rs index f7249a3118d..ee70dbbffc5 100644 --- a/packages/rs-unified-sdk-jni/src/identity.rs +++ b/packages/rs-unified-sdk-jni/src/identity.rs @@ -999,6 +999,43 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_IdentityNative_discov }) } +/// Load the identity registered for this wallet at one identity index, +/// recording it like discovery does. Returns its 32-byte id, or an empty +/// `byte[]` when no identity is registered at that index. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_IdentityNative_loadIdentityAtIndex( + mut env: JNIEnv, + _class: JClass, + wallet_handle: jlong, + resolver_handle: jlong, + identity_index: jint, +) -> jbyteArray { + guard(&mut env, ptr::null_mut(), |env| { + if identity_index < 0 { + throw_sdk_exception(env, 1, "identityIndex must be non-negative"); + return ptr::null_mut(); + } + let mut found = false; + let mut id = [0u8; 32]; + let result = unsafe { + platform_wallet_ffi::platform_wallet_load_identity_at_index( + wallet_handle as Handle, + resolver_handle as *mut MnemonicResolverHandle, + identity_index as u32, + &mut found as *mut bool, + id.as_mut_ptr(), + ) + }; + if take_pwffi_error(env, result) { + return ptr::null_mut(); + } + let out: &[u8] = if found { &id } else { &[] }; + env.byte_array_from_slice(out) + .map(|a| a.into_raw()) + .unwrap_or(ptr::null_mut()) + }) +} + // ── DPNS name registration ──────────────────────────────────────────── /// Register a DPNS name for an identity, signed via the external signer. diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift index f1b6599554e..591d58dd918 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift @@ -2736,19 +2736,48 @@ extension ManagedPlatformWallet { /// unspent (a reclaim top-up consumes it without creating this /// identity), so the claim can still fail late. public let alreadyClaimed: Bool - + /// Whether this wallet made the claim: the invitation's identity is one + /// the wallet already records, or holds the wallet's master key at the + /// identity index asked about (a "no" covers only that index). `false` + /// whenever `alreadyClaimed` is false; `nil` when it could not be + /// decided (the wallet's key was unavailable), and always `nil` for a + /// claimed invitation from ``invitationClaimStatus(uri:)``, which does + /// not ask. + public let claimedByThisWallet: Bool? + + /// `claimedByThisWallet` defaults to unknown; Rust reports `false` + /// for an unclaimed invitation. public init( prospectiveIdentityId: Data, amountDuffs: UInt64, isInstant: Bool, isChainLocked: Bool, - alreadyClaimed: Bool + alreadyClaimed: Bool, + claimedByThisWallet: Bool? = nil ) { self.prospectiveIdentityId = prospectiveIdentityId self.amountDuffs = amountDuffs self.isInstant = isInstant self.isChainLocked = isChainLocked self.alreadyClaimed = alreadyClaimed + self.claimedByThisWallet = claimedByThisWallet + } + + init(_ ffi: InvitationClaimStatusFFI) { + let claimedByThisWallet: Bool? + switch ffi.claimed_by_this_wallet { + case UInt8(INVITATION_CLAIMED_BY_THIS_WALLET_NO): claimedByThisWallet = false + case UInt8(INVITATION_CLAIMED_BY_THIS_WALLET_YES): claimedByThisWallet = true + default: claimedByThisWallet = nil + } + self.init( + prospectiveIdentityId: withUnsafeBytes(of: ffi.prospective_identity_id) { Data($0) }, + amountDuffs: ffi.amount_duffs, + isInstant: ffi.is_instant, + isChainLocked: ffi.is_chain_locked, + alreadyClaimed: ffi.already_claimed, + claimedByThisWallet: claimedByThisWallet + ) } } @@ -2854,6 +2883,21 @@ extension ManagedPlatformWallet { /// sender?") is NOT done here — after a successful claim the UI asks the /// invitee and, on confirm, calls `sendContactRequest` for the reciprocal. /// + /// Nothing is broadcast when Platform would refuse the claim and charge + /// the voucher: it throws `.invitationClaimedByThisWallet` (an earlier + /// claim of this wallet landed, or the wallet already records the + /// invitation's identity; load that identity), + /// `.assetLockAlreadyConsumed` (claimed by an identity that does not hold + /// the master key at `identityIndex` and that the wallet does not record — + /// usually someone else), + /// `.invitationKeysAlreadyRegistered` (another identity holds these keys) + /// or `.invitationNotReady` (retry once synced). `.assetLockNotChainLocked` + /// means retry later. A node that has not seen an earlier landed claim + /// lets the retry through; Platform then refuses it, and the identity is + /// returned as the claim's result when it carries exactly these keys, or + /// reported as `.invitationClaimedByThisWallet` / `.assetLockAlreadyConsumed` + /// as above when it does not. + /// /// Returns the freshly-registered invitee `ManagedIdentity`. public func claimInvitation( uri: String, @@ -2971,13 +3015,43 @@ extension ManagedPlatformWallet { platform_wallet_invitation_claim_status(handle, uriPtr, &out) } try result.check() - return InvitationClaimStatus( - prospectiveIdentityId: withUnsafeBytes(of: out.prospective_identity_id) { Data($0) }, - amountDuffs: out.amount_duffs, - isInstant: out.is_instant, - isChainLocked: out.is_chain_locked, - alreadyClaimed: out.already_claimed - ) + return InvitationClaimStatus(out) + } + }.value + } + + /// ``invitationClaimStatus(uri:)``, plus whether this wallet made the + /// claim as its identity at `identityIndex` + /// (``InvitationClaimStatus/claimedByThisWallet``). + /// + /// Rust reads the wallet's master key only when the invitation was + /// claimed, through a ``MnemonicResolver`` when the seed lives in the + /// Keychain, so an unclaimed invitation never needs it. A key that cannot + /// be read makes `claimedByThisWallet` `nil`, not an error. Same error + /// contract as ``invitationClaimStatus(uri:)``. + public func invitationClaimStatus( + uri: String, + identityIndex: UInt32, + storage: WalletStorage = WalletStorage() + ) async throws -> InvitationClaimStatus { + let resolver = MnemonicResolver(storage: storage) + // `self` and the resolver stay alive for the whole synchronous FFI + // call (up to ~12 s of funding-tx retries): the resolver's FFI ctx is + // a `passUnretained` pointer. + return try await Task.detached(priority: .userInitiated) { [self] () -> InvitationClaimStatus in + try withExtendedLifetime((self, resolver)) { + var out = InvitationClaimStatusFFI() + let result = uri.withCString { uriPtr in + platform_wallet_invitation_claim_status_for_identity( + handle, + resolver.handle, + identityIndex, + uriPtr, + &out + ) + } + try result.check() + return InvitationClaimStatus(out) } }.value } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift index ee130585d2d..56fdc6ede0f 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift @@ -270,6 +270,18 @@ public enum PlatformWalletResultCode: Int32, Sendable { /// A shielded fund-from-asset-lock resume named a different Orchard /// recipient than the one its tracked lock recorded; nothing was paid. case errorAssetLockRecipientMismatch = 61 + /// A key of a DashPay invitation claim already belongs to another + /// identity; the message is a JSON detail naming it. + case errorInvitationKeysAlreadyRegistered = 63 + /// An earlier DashPay invitation claim of this wallet landed; the message + /// is a JSON detail naming its identity. Nothing was recorded. + case errorInvitationClaimedByThisWallet = 64 + /// The invitation claim could not verify Platform's answers yet; nothing + /// was broadcast. Retry once synced. + case errorInvitationNotReady = 65 + /// The asset lock is not usable yet (not propagated, or not chain-locked + /// for a ChainLock proof). Retry later. + case errorAssetLockNotChainLocked = 66 /// The contact requests with that identity came or went privately, so a /// public request to it, in reply or as a rotation, would publish the /// relationship. Nothing was sent; accept or send it privately. @@ -455,6 +467,14 @@ public enum PlatformWalletResultCode: Int32, Sendable { self = .errorAssetLockTooManyInputs case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_ASSET_LOCK_RECIPIENT_MISMATCH: self = .errorAssetLockRecipientMismatch + case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_INVITATION_KEYS_ALREADY_REGISTERED: + self = .errorInvitationKeysAlreadyRegistered + case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_INVITATION_CLAIMED_BY_THIS_WALLET: + self = .errorInvitationClaimedByThisWallet + case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_INVITATION_NOT_READY: + self = .errorInvitationNotReady + case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_ASSET_LOCK_NOT_CHAIN_LOCKED: + self = .errorAssetLockNotChainLocked case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_PRIVATE_CONTACT_REQUEST_NEEDS_PRIVATE_REPLY: self = .errorPrivateContactRequestNeedsPrivateReply case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_SHIELDED_BUILD_REQUIRED: @@ -672,6 +692,26 @@ public enum PlatformWalletError: LocalizedError { /// `TrackedAssetLock.shieldedRecipientRaw43`). Locks tracked before the /// recipient was recorded carry none and accept the caller's. case assetLockRecipientMismatch(String) + /// The asset lock cannot be used yet: its transaction has not reached the + /// queried node, or it needs a ChainLock proof and is not chain-locked + /// yet. Retry later. Produced today by `claimInvitation`. + case assetLockNotChainLocked(String) + /// A key of the DashPay invitation claim is already registered to + /// another identity (base58 `identityId`, `nil` when Platform refused the + /// broadcast without naming it), so the claim cannot be made with these + /// keys. `consensus` is Platform's refusal (40207, or 10501 before + /// protocol v11) when it came from the broadcast, `nil` when the claim's + /// own lookup found the owner and nothing was sent. + case invitationKeysAlreadyRegistered(identityId: String?, consensus: PlatformConsensusError?) + /// The invitation's identity (base58 `identityId`) is this wallet's: it + /// holds this claim's master key (an earlier claim landed) or the wallet + /// already records it. Nothing was recorded, and nothing was broadcast + /// unless a node that lagged behind let the claim through; load the + /// identity like any of the wallet's own. + case invitationClaimedByThisWallet(identityId: String) + /// The invitation claim could not verify Platform's answers yet (the + /// quorum is not verified). Nothing was broadcast; retry once synced. + case invitationNotReady(String) /// The contact requests with that identity came or went privately /// (protocol version 15): a public request to it, in reply or as a /// rotation, would publish the relationship, so the public accept and @@ -945,12 +985,18 @@ public enum PlatformWalletError: LocalizedError { /// Platform's verdict when this error is a consensus rejection the wallet /// layer left untyped, so a caller can write - /// `error.consensusError?.code == 40722` without pattern matching. `nil` - /// for every other case, including the typed promotions of specific - /// rejections. + /// `error.consensusError?.code == 40722` without pattern matching, and + /// the refusal behind `.invitationKeysAlreadyRegistered` when Platform + /// refused the broadcast. `nil` for every other case, including the + /// other typed promotions of specific rejections. public var consensusError: PlatformConsensusError? { - guard case .consensusRejection(let consensus, _) = self else { return nil } - return consensus + switch self { + case .consensusRejection(let consensus, _), + .invitationKeysAlreadyRegistered(_, let consensus?): + return consensus + default: + return nil + } } /// What to show a person. For most cases this is still the diagnostic @@ -971,6 +1017,7 @@ public enum PlatformWalletError: LocalizedError { .assetLockNotTracked(let m), .assetLockAlreadyConsumed(let m), .assetLockFundingMismatch(let m), .assetLockInsufficientFunds(let m), .assetLockTooManyInputs(let m), .assetLockRecipientMismatch(let m), + .assetLockNotChainLocked(let m), .invitationNotReady(let m), .privateContactRequestNeedsPrivateReply(let m), .shieldedBuildRequired(let m), .protocolVersionNotActive(let m), .privateContactRequestPending(let m), .privateContactPaymentsNotRestored(let m), @@ -1022,6 +1069,13 @@ public enum PlatformWalletError: LocalizedError { + "could be confirmed. Nothing was purchased." case .insufficientIdentityCredits(let identityId, let required, let available): return "Identity \(identityId) has \(available) credits but \(required) are required." + case .invitationKeysAlreadyRegistered(let identityId, _): + guard let identityId else { + return "A key of this invitation claim is already registered to another identity." + } + return "A key of this invitation claim is already registered to identity \(identityId)." + case .invitationClaimedByThisWallet(let identityId): + return "This invitation was already claimed by this wallet as identity \(identityId)." case .contestedNameNotTradable(let label, let endsAtMs): if endsAtMs == 0 { return "\"\(label)\" is in an active contested-name vote and cannot be traded " @@ -1060,8 +1114,9 @@ public enum PlatformWalletError: LocalizedError { /// Production callers continue to enter through `init(result:)`. /// /// `consensus` is Platform's verdict when the result carried one, and is - /// consulted on the catch-all code alone: every other code is a - /// classification the wallet layer chose deliberately and must keep + /// consulted on the catch-all code, where it picks the case, and on code + /// 63, which keeps it beside its own classification. Every other code is + /// a classification the wallet layer chose deliberately and must keep /// reaching its own case. init( code: PlatformWalletResultCode, @@ -1096,6 +1151,24 @@ public enum PlatformWalletError: LocalizedError { case .errorAssetLockInsufficientFunds: self = .assetLockInsufficientFunds(detail) case .errorAssetLockTooManyInputs: self = .assetLockTooManyInputs(detail) case .errorAssetLockRecipientMismatch: self = .assetLockRecipientMismatch(detail) + case .errorAssetLockNotChainLocked: self = .assetLockNotChainLocked(detail) + case .errorInvitationNotReady: self = .invitationNotReady(detail) + // Codes 63/64 carry a stable JSON detail naming the identity; a + // payload that does not decode degrades to `.unknown(detail)`. + case .errorInvitationKeysAlreadyRegistered: + if let d = InvitationErrorDetail.decode(detail) { + self = .invitationKeysAlreadyRegistered( + identityId: d.identityId, consensus: consensus + ) + } else { + self = .unknown(detail) + } + case .errorInvitationClaimedByThisWallet: + if let identityId = InvitationErrorDetail.decode(detail)?.identityId { + self = .invitationClaimedByThisWallet(identityId: identityId) + } else { + self = .unknown(detail) + } case .errorPrivateContactRequestNeedsPrivateReply: self = .privateContactRequestNeedsPrivateReply(detail) case .errorShieldedBuildRequired: @@ -1273,6 +1346,22 @@ private enum TradeErrorDetail { } } +// MARK: - Invitation-claim error detail decoding + +/// Decoder for the JSON detail FFI result codes 63/64 put in the result +/// `message`: `{"identityId":""}`, with `null` when code 63 could not +/// name the identity. +private enum InvitationErrorDetail { + struct Detail: Decodable { + let identityId: String? + } + + static func decode(_ message: String?) -> Detail? { + guard let data = message?.data(using: .utf8) else { return nil } + return try? JSONDecoder().decode(Detail.self, from: data) + } +} + // MARK: - Convenience extensions extension PlatformWalletFFIResult { diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift index a8ccb49c5ba..42ed5b4ea8f 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift @@ -28,6 +28,8 @@ struct ClaimInvitationSheet: View { /// Existing identities on this network — used to pick the next unused /// registration index for the new identity. @Query private var identities: [PersistentIdentity] + /// Accounts, for the identity-registration slot rows the claim reserves. + @Query private var accounts: [PersistentAccount] @State private var uri: String @State private var preview: ManagedPlatformWallet.InvitationPreview? @@ -201,6 +203,7 @@ struct ClaimInvitationSheet: View { } let signer = KeychainSigner(modelContainer: modelContext.container) let identityIndex = nextUnusedIdentityIndex() + try reserveIdentitySlot(identityIndex) // Register the invitee's own keys exactly like a normal // registration: master + auth keys, plus a DashPay enc/dec pair @@ -218,14 +221,66 @@ struct ClaimInvitationSheet: View { network: network )) - let managed = try await wallet.claimInvitation( - uri: submittedURI, - identityIndex: identityIndex, - identityPubkeys: keys, - signer: signer, - nowUnix: UInt32(Date().timeIntervalSince1970) - ) - let newIdentityId = try managed.getId() + let newIdentityId: Identifier + do { + let managed = try await wallet.claimInvitation( + uri: submittedURI, + identityIndex: identityIndex, + identityPubkeys: keys, + signer: signer, + nowUnix: UInt32(Date().timeIntervalSince1970) + ) + newIdentityId = try managed.getId() + } catch PlatformWalletError.invitationClaimedByThisWallet(let claimedId) { + // The invitation's identity is this wallet's: one it + // records, or one an earlier claim at this index created + // without recording it, which is loaded like any identity + // of this wallet. Only the identity the error names counts. + if let recorded = identities.first(where: { + $0.identityIdBase58 == claimedId && $0.wallet?.walletId == walletId + }) { + newIdentityId = recorded.identityId + } else { + let loaded: Identifier? + do { + loaded = try await wallet.loadIdentity(atIndex: identityIndex) + } catch { + // A failed load says nothing about the identity, + // so it is reported as a failure to retry. + errorMessage = "This invitation already created identity \(claimedId) " + + "in this wallet, but loading it failed: " + + "\(error.localizedDescription). Try again." + return + } + guard let loaded, loaded.toBase58String() == claimedId else { + errorMessage = "This invitation already created identity \(claimedId) " + + "in this wallet. If it is not listed, try Re-scan for Identities." + return + } + newIdentityId = loaded + } + } catch let refusal as PlatformWalletError { + // The keys at this index belong to an identity. When it is + // this wallet's own, unrecorded one, loading it records it, + // and the next claim takes the next index. Any other owner + // keeps the refusal. + guard case .invitationKeysAlreadyRegistered(let ownerId?, _) = refusal else { + throw refusal + } + let loaded: Identifier? + do { + loaded = try await wallet.loadIdentity(atIndex: identityIndex) + } catch { + errorMessage = "Identity \(ownerId) holds these keys, but checking whether " + + "it is this wallet's failed: \(error.localizedDescription). Try again." + return + } + guard let loaded, loaded.toBase58String() == ownerId else { throw refusal } + kickDashPaySync(walletManager) + errorMessage = "Identity \(ownerId) of this wallet already used these keys " + + "and is now loaded. Claim again once it is listed." + return + } kickDashPaySync(walletManager) // Offer the contact-bootstrap when the link carried an inviter @@ -288,11 +343,36 @@ struct ClaimInvitationSheet: View { /// One past the highest used registration index on this wallet, else 0. /// Registration keys aren't gap-limited, so "next unused" is `max + 1`. + /// A slot held by an in-flight registration counts as used: its identity + /// row only lands after Platform accepts it, and reusing the slot would + /// register the same keys twice. private func nextUnusedIdentityIndex() -> UInt32 { - let used = identities + let recorded = identities .filter { $0.wallet?.walletId == walletId } .map(\.identityIndex) - guard let highest = used.max() else { return 0 } + let held = walletManager.registrationCoordinator.controllers.keys + .filter { $0.walletId == walletId } + .map(\.identityIndex) + guard let highest = (recorded + held).max() else { return 0 } return highest == UInt32.max ? UInt32.max : highest + 1 } + + /// Mark the claim's slot used before its keys are derived, so a normal + /// registration started meanwhile skips it: `CreateIdentityView` treats a + /// slot whose identity-registration address is `isUsed` as taken. A no-op + /// when the slot row is beyond the derived lookahead, as there. Saved at + /// once, so the reservation outlives an app exit during the claim. + /// + /// This sheet's own selector does not read the marker: a retry after a + /// lost result must come back to the same slot, where the landed claim's + /// keys are, to be recognized as this wallet's claim. + private func reserveIdentitySlot(_ identityIndex: UInt32) throws { + let slot = accounts + .first { $0.wallet.walletId == walletId && $0.accountType == 2 }? + .coreAddresses + .first { $0.addressIndex == identityIndex } + guard let slot, !slot.isUsed else { return } + slot.isUsed = true + try modelContext.save() + } } diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift index b3bbb2a7d64..ce4e9c38f98 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift @@ -439,6 +439,86 @@ final class ErrorHandlingTests: XCTestCase { XCTAssertEqual(keyMessage, detail) } + /// The invitation claim's outcomes keep pinned raw values and typed + /// cases, so the app branches on codes rather than on error text. + func testShouldPreserveInvitationClaimOutcomesFromFFI() { + let codes: [(PlatformWalletFFIResultCode, PlatformWalletResultCode, Int32)] = [ + (PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_INVITATION_KEYS_ALREADY_REGISTERED, + .errorInvitationKeysAlreadyRegistered, 63), + (PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_INVITATION_CLAIMED_BY_THIS_WALLET, + .errorInvitationClaimedByThisWallet, 64), + (PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_INVITATION_NOT_READY, + .errorInvitationNotReady, 65), + (PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_ASSET_LOCK_NOT_CHAIN_LOCKED, + .errorAssetLockNotChainLocked, 66), + ] + for (ffi, code, raw) in codes { + XCTAssertEqual(PlatformWalletResultCode(ffi: ffi), code) + XCTAssertEqual(code.rawValue, raw) + } + + let id = "8eTDkBhpQjHeqgbVeriwLeZr1tCa6yBGw76SckvD1cwc" + // Found by the claim's own lookup: nothing was broadcast, so there is + // no refusal to carry. + let found = PlatformWalletError( + code: .errorInvitationKeysAlreadyRegistered, message: "{\"identityId\":\"\(id)\"}" + ) + guard case .invitationKeysAlreadyRegistered(let owner, nil) = found + else { return XCTFail("lost typed keys-already-registered error") } + XCTAssertEqual(owner, id) + XCTAssertNil(found.consensusError) + // Refused by Platform after the broadcast: the typed case keeps the + // refusal, before and after protocol v11. + for refusal in [ + PlatformConsensusError(code: 40207, kind: .state), + PlatformConsensusError(code: 10501, kind: .basic), + ] { + let refused = PlatformWalletError( + code: .errorInvitationKeysAlreadyRegistered, + message: "{\"identityId\":null}", + consensus: refusal + ) + guard case .invitationKeysAlreadyRegistered(nil, refusal) = refused + else { return XCTFail("lost the refusal behind keys-already-registered") } + XCTAssertEqual(refused.consensusError, refusal) + } + guard case .invitationClaimedByThisWallet(let claimed) = PlatformWalletError( + code: .errorInvitationClaimedByThisWallet, message: "{\"identityId\":\"\(id)\"}" + ) else { return XCTFail("lost typed claimed-by-this-wallet error") } + XCTAssertEqual(claimed, id) + guard case .invitationNotReady = PlatformWalletError( + code: .errorInvitationNotReady, message: "quorum not verified" + ) else { return XCTFail("lost typed not-ready error") } + guard case .assetLockNotChainLocked = PlatformWalletError( + code: .errorAssetLockNotChainLocked, message: "retry later" + ) else { return XCTFail("lost typed not-chain-locked error") } + } + + /// 64 always names its identity; a payload without one degrades to + /// `.unknown` instead of inventing an id. + func testShouldDegradeAnUndecodableInvitationDetailToUnknown() { + guard case .unknown = PlatformWalletError( + code: .errorInvitationClaimedByThisWallet, message: "{\"identityId\":null}" + ) else { return XCTFail("a claim with no identity must not be typed") } + guard case .unknown = PlatformWalletError( + code: .errorInvitationKeysAlreadyRegistered, message: "not json" + ) else { return XCTFail("a prose payload must not be typed") } + } + + /// The FFI tri-state maps to `false` / `true` / `nil`. + func testShouldDecodeWhoseInvitationClaimItWas() { + func status(claimed: Bool, by: UInt8) -> ManagedPlatformWallet.InvitationClaimStatus { + var ffi = InvitationClaimStatusFFI() + ffi.already_claimed = claimed + ffi.claimed_by_this_wallet = by + return ManagedPlatformWallet.InvitationClaimStatus(ffi) + } + XCTAssertEqual(status(claimed: true, by: UInt8(INVITATION_CLAIMED_BY_THIS_WALLET_NO)).claimedByThisWallet, false) + XCTAssertEqual(status(claimed: true, by: UInt8(INVITATION_CLAIMED_BY_THIS_WALLET_YES)).claimedByThisWallet, true) + XCTAssertNil(status(claimed: true, by: UInt8(INVITATION_CLAIMED_BY_THIS_WALLET_UNKNOWN)).claimedByThisWallet) + XCTAssertEqual(status(claimed: false, by: UInt8(INVITATION_CLAIMED_BY_THIS_WALLET_NO)).claimedByThisWallet, false) + } + func testShouldPreserveSpvProcessRestartRequiredFromFFI() { let code = PlatformWalletResultCode( ffi: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_SPV_PROCESS_RESTART_REQUIRED