From 4178e0986d4c6494bea43b9639087c47c06ceded Mon Sep 17 00:00:00 2001 From: Roman <51091564+jeanpierreroma@users.noreply.github.com> Date: Thu, 22 Oct 2026 13:42:33 +0300 Subject: [PATCH 01/15] fix(platform-wallet): check an invitation claim against Platform before broadcasting it The claim used to broadcast blindly. When a submitted key was already registered to another identity, Platform refused it with 40207/10501 and charged the voucher on every attempt. Hosts also could not tell their own landed claim from someone else's. - rs-sdk: before signing, look up the identity at the invitation's id and under every submitted key hash, and return ClaimedByThisWallet / AlreadyClaimed / KeysAlreadyRegistered / NotReady without broadcasting. Map 40207/10501 after a broadcast to KeysAlreadyRegistered, and classify a consumed-outpoint refusal by whose identity is there. One shared identity_holds_master_key predicate. - rs-platform-wallet: typed error variants; invitation_claim_status_for_identity with a claimed_by_this_wallet tri-state, resolving the master key only when the invitation was claimed; an identity the wallet already records counts as its own. - FFI: codes 63-66 (JSON detail on 63/64), AlreadyClaimed -> 24, and platform_wallet_invitation_claim_status_for_identity. - Swift/Kotlin mirrors, example-app message for 64, parity manifest gap for the missing Kotlin status binding. Refs dashpay/dashwallet-ios#1224 Co-Authored-By: Claude Opus 5.5 --- docs/sdk/sdk-parity-manifest.json | 42 + .../ui/dashpay/ClaimInvitationSheet.kt | 10 +- packages/kotlin-sdk/PARITY_SUMMARY.md | 15 +- .../dashsdk/errors/DashSdkError.kt | 81 +- .../errors/InvitationClaimErrorTest.kt | 46 + .../ERROR_CODE_REGISTRY.md | 8 +- packages/rs-platform-wallet-ffi/src/error.rs | 161 +++- .../rs-platform-wallet-ffi/src/invitation.rs | 199 ++++- packages/rs-platform-wallet/src/error.rs | 65 ++ .../src/wallet/identity/network/invitation.rs | 584 +++++++++++- .../src/wallet/identity/network/mod.rs | 4 +- .../rs-sdk/src/platform/dashpay/invitation.rs | 835 ++++++++++++++++-- packages/rs-sdk/src/platform/dashpay/mod.rs | 6 +- .../ManagedPlatformWallet.swift | 92 +- .../PlatformWallet/PlatformWalletResult.swift | 80 +- .../Views/DashPay/ClaimInvitationSheet.swift | 5 + .../ErrorHandlingTests.swift | 64 ++ 17 files changed, 2193 insertions(+), 104 deletions(-) create mode 100644 packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/InvitationClaimErrorTest.kt diff --git a/docs/sdk/sdk-parity-manifest.json b/docs/sdk/sdk-parity-manifest.json index aa26292d4b4..538446aa22b 100644 --- a/docs/sdk/sdk-parity-manifest.json +++ b/docs/sdk/sdk-parity-manifest.json @@ -40,6 +40,7 @@ "platform_wallet_create_document_with_signer": "packages/rs-platform-wallet-ffi/src/document.rs", "platform_wallet_create_invitation": "packages/rs-platform-wallet-ffi/src/invitation.rs", "platform_wallet_drain_pending_contact_crypto": "packages/rs-platform-wallet-ffi/src/dashpay.rs", + "platform_wallet_invitation_claim_status_for_identity": "packages/rs-platform-wallet-ffi/src/invitation.rs", "platform_wallet_manager_create_with_persistence_capabilities": "packages/rs-platform-wallet-ffi/src/manager.rs", "platform_wallet_manager_persistence_capabilities": "packages/rs-platform-wallet-ffi/src/manager.rs", "platform_wallet_manager_shielded_fund_from_wallet_drain": "packages/rs-platform-wallet-ffi/src/shielded_wallet_drain.rs", @@ -643,6 +644,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 bcf176f8985..63375e2ae2c 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,6 +25,7 @@ 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.example.di.LocalAppContainer @@ -177,7 +178,14 @@ fun ClaimInvitationSheet( onClose() } } catch (t: Throwable) { - errorMessage = t.message ?: "Claiming the invitation failed." + errorMessage = if (t is DashSdkError.PlatformWallet.InvitationClaimedByThisWallet) { + // An earlier claim from this wallet already created the + // identity, which this claim did not record. + "This invitation already created an identity in this wallet. " + + "It appears once identities are refreshed." + } else { + t.message ?: "Claiming the invitation failed." + } } finally { isClaiming = false appUiState.invitationClaimInFlight.value = false diff --git a/packages/kotlin-sdk/PARITY_SUMMARY.md b/packages/kotlin-sdk/PARITY_SUMMARY.md index ff6bef9ca6e..c0bdbd76b7c 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: **27** +Capabilities tracked: **28** ## Status counts | Host | Surface | Supported | Partial | Unsupported | Not applicable | | --- | --- | ---: | ---: | ---: | ---: | -| Swift | SDK | 16 | 9 | 1 | 1 | -| Swift | Example app | 4 | 12 | 2 | 9 | -| Kotlin | SDK | 13 | 12 | 1 | 1 | -| Kotlin | Example app | 5 | 12 | 1 | 9 | +| Swift | SDK | 17 | 9 | 1 | 1 | +| Swift | Example app | 4 | 12 | 2 | 10 | +| Kotlin | SDK | 13 | 12 | 2 | 1 | +| Kotlin | Example app | 5 | 12 | 1 | 10 | ## Restart coverage | Host | Tested | Required | Not applicable | | --- | ---: | ---: | ---: | -| Swift | 1 | 8 | 18 | -| Kotlin | 4 | 6 | 17 | +| Swift | 1 | 8 | 19 | +| Kotlin | 4 | 6 | 18 | ## Capability status @@ -31,6 +31,7 @@ Capabilities tracked: **27** | `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 | | `identity.asset_lock_resume` | supported / 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 3227c3d606b..2098f0f6e57 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 @@ -240,6 +240,57 @@ sealed class DashSdkError( class AssetLockTooManyInputs(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 @@ -768,6 +819,24 @@ sealed class DashSdkError( 27 -> PlatformWallet.ShutdownIncomplete(message, cause) // ErrorShutdownIncomplete 29 -> PlatformWallet.AssetLockInsufficientFunds(message, cause) // ErrorAssetLockInsufficientFunds 60 -> PlatformWallet.AssetLockTooManyInputs(message, cause) // ErrorAssetLockTooManyInputs + 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 @@ -778,7 +847,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"), @@ -788,7 +857,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"), @@ -798,7 +867,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"), @@ -852,11 +921,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/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/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md index a916a4eb433..e3490f7a866 100644 --- a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md +++ b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md @@ -114,7 +114,9 @@ These are shipped ABI. Do not renumber. | 98 | `NotFound` | Sentinel — `Option` returned as an error | | 99 | `ErrorUnknown` | Sentinel — unmapped/flattened errors | -**Next allocatable integer: 61** — 27–60 are all claimed (27, 29, 31, 34–42 +**Next allocatable integer: 67** — 27–66 are all claimed (63–66 proposed by +the DashPay invitation-claim preflight; 61 is held by open #5395 and 62 by open +#5487, which record their own rows; 27, 29, 31, 34–42 and 46 merged; 43–45 proposed by active #4313 at head `0302b188ab`; 47 and 48 proposed by active #4356 (47 renumbered from 42, 48 from 43 — see their rows below); 49–54 proposed by active #4586 (the persister @@ -177,6 +179,10 @@ Fork-era numbers remain in the collision history, which is immutable record. | 58 | `ErrorIdentityBalanceUnavailable` | #4799 | Proposed — Platform returned no balance for a managed identity. Retrying the read is safe; this is distinct from missing wallet ownership and must not trigger registration or funding | | 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 — the full drain needs more inputs than an asset lock may carry (100 on Dash Core relay policy and Platform consensus); no partial drain was broadcast. Rust, Swift and Kotlin retain the typed refusal. Renumbered from 59 after #5322 claimed it | +| 63 | `ErrorInvitationKeysAlreadyRegistered` | DashPay invitation-claim preflight | 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. 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` | DashPay invitation-claim preflight | 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` | DashPay invitation-claim preflight | 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` | DashPay invitation-claim preflight | 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 | **Code 31 left this table on 2026-08-04.** `ErrorSigningKeyUnavailable` sat here as #4183's proposal until #4183 merged (`189a3abb1c`); it is now in the merged diff --git a/packages/rs-platform-wallet-ffi/src/error.rs b/packages/rs-platform-wallet-ffi/src/error.rs index 0bc67f532c9..d71e2adf025 100644 --- a/packages/rs-platform-wallet-ffi/src/error.rs +++ b/packages/rs-platform-wallet-ffi/src/error.rs @@ -614,6 +614,41 @@ pub enum PlatformWalletFFIResultCode { /// host must not silently substitute a partial drain. ErrorAssetLockTooManyInputs = 60, + /// 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, + /// The named thing does not exist. /// /// Originally (and still mostly) the code for every `Option` returned as an @@ -809,12 +844,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` @@ -822,9 +858,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, @@ -860,16 +894,30 @@ 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, } } impl From for PlatformWalletFFIResult { fn from(error: PlatformWalletError) -> Self { - // 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) { + // 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); } // Map the typed wallet error variants explicitly so they @@ -996,9 +1044,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 } @@ -1091,7 +1146,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 } @@ -2186,6 +2241,88 @@ 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), + }, + 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) + })["identityId"], + id.to_string(Encoding::Base58) + ); + assert!( + detail(PlatformWalletError::InvitationKeysAlreadyRegistered { identity_id: 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!( diff --git a/packages/rs-platform-wallet-ffi/src/invitation.rs b/packages/rs-platform-wallet-ffi/src/invitation.rs index 03d3a1eed18..b8ebf26e229 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`]). @@ -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 5696d681d2b..bc9705ef58f 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -94,6 +94,33 @@ 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. + #[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 }, + + /// 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 @@ -1050,6 +1077,16 @@ 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 } => { + Self::InvitationKeysAlreadyRegistered { identity_id } + } + InvitationError::NotReady(error) => Self::InvitationNotReady(error), InvitationError::Sdk(error) => Self::Sdk(error), } } @@ -1855,6 +1892,34 @@ 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, + }), + 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/invitation.rs b/packages/rs-platform-wallet/src/wallet/identity/network/invitation.rs index 2e475a55f86..97954d076a1 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,32 @@ 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() +} + +/// Where [`IdentityWallet::invitation_claimed_by_this_wallet`] gets this +/// wallet's master key from. +#[derive(Clone, Copy)] +pub 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,15 +327,224 @@ 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 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; + wm.get_wallet(&self.wallet_id) + .is_some_and(has_resident_keys) + }; + 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. + async fn claim_refusal(&self, error: InvitationError) -> PlatformWalletError { + match error { + InvitationError::AlreadyClaimed { identity_id } + if self.holds_identity(&identity_id).await => + { + PlatformWalletError::InvitationClaimedByThisWallet { identity_id } + } + error => error.into(), + } + } + + /// This wallet records `identity_id` as one of its own identities. + async fn holds_identity(&self, identity_id: &Identifier) -> bool { + let wm = self.wallet_manager.read().await; + wm.get_wallet_info(&self.wallet_id) + .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 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> { + if matches!(key, InvitationClaimantKey::Unavailable) { + return Ok(None); + } + let wm = self.wallet_manager.read().await; + let wallet = wm.get_wallet(&self.wallet_id).ok_or_else(|| { + PlatformWalletError::WalletNotFound("Wallet not found in wallet manager".to_string()) + })?; + let public_key: [u8; 33] = match key { + InvitationClaimantKey::Unavailable => return Ok(None), + InvitationClaimantKey::Master(master) => { + derive_ecdsa_identity_auth_keypair_from_master( + master, + wallet.network, + identity_index, + MASTER_KEY_INDEX, + )? + .public_key + } + InvitationClaimantKey::ResidentWallet => { + 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 stale-islock → ChainLock fallback 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 stale-islock → ChainLock + /// fallback 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. @@ -324,10 +559,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 @@ -441,6 +680,339 @@ 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() -> [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 { + 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, + )); + 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 + )); + } + } + // --- create_invitation: the durable-persistence precondition --- mod durability_gate { diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs index 8e121a95005..b90c3b86c7e 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs @@ -61,8 +61,8 @@ mod contacts; mod dashpay_view; mod invitation; pub use invitation::{ - Invitation, InvitationClaimStatus, MAX_INVITATION_DUFFS, MAX_INVITATION_TTL_SECS, - MIN_INVITATION_DUFFS, + Invitation, InvitationClaimStatus, InvitationClaimantKey, MAX_INVITATION_DUFFS, + MAX_INVITATION_TTL_SECS, MIN_INVITATION_DUFFS, }; mod payment_handler; pub(crate) use payment_handler::DashPayPaymentHandler; diff --git a/packages/rs-sdk/src/platform/dashpay/invitation.rs b/packages/rs-sdk/src/platform/dashpay/invitation.rs index 23f29a33744..b55e36e6e6e 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,11 +78,12 @@ 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}; @@ -89,6 +93,7 @@ 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}; @@ -160,6 +165,40 @@ 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). + #[error( + "a key of this claim is already registered to {}", + key_owner(identity_id) + )] + KeysAlreadyRegistered { identity_id: 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), @@ -269,6 +308,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()) } @@ -703,6 +750,18 @@ 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 the same consensus code as a key + // registered elsewhere (10501 before protocol v7), 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() + ))); + } Ok(()) } @@ -792,18 +851,30 @@ 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?; + 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, @@ -838,9 +909,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 @@ -875,55 +961,255 @@ 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}")))?; + 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)), + ); - // 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, - }); + claim_unless_refused(preflight, || async move { + // 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 on Platform's stale-islock - // rejection — 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_stale_islock_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 on Platform's + // stale-islock rejection — 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_stale_islock_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; + + // 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) }) - .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) + .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`: an ECDSA key 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 data counts, not the purpose, security level or bounds, because Platform +/// accepts an ECDSA 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 { + master_key.key_type() == KeyType::ECDSA_SECP256K1 + && identity.public_keys().values().any(|key| { + key.key_type() == KeyType::ECDSA_SECP256K1 && 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. a 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); any other +/// identity → [`InvitationError::KeysAlreadyRegistered`]; +/// 4. 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; + 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)); + } + Ok(Some(identity)) => { + return Err(InvitationError::KeysAlreadyRegistered { + identity_id: Some(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); + } + } + } + } + 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 v7. +/// That refusal is final for these keys, so it becomes +/// [`InvitationError::KeysAlreadyRegistered`]. 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 }) + } + 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`]). @@ -1082,8 +1368,10 @@ 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`). @@ -1111,7 +1399,13 @@ 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)) => match submitted_keys.get(&0) { + Some(master_key) => Err(claimed_by(&identity, master_key)), + None => Err(InvitationError::Sdk(error)), + }, + Ok(None) => Err(InvitationError::Sdk(error)), Err(lookup) => { tracing::warn!( error = %lookup, @@ -2061,6 +2355,416 @@ 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()); + } + + /// 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 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 + )); + } + + // --- 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 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 }) + )); + + 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::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]), + )), + ] { + assert!(matches!( + keys_taken_on_broadcast(Err(refused(error))), + Err(InvitationError::KeysAlreadyRegistered { identity_id: None }) + )); + } + } + + /// 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 { @@ -2133,14 +2837,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 diff --git a/packages/rs-sdk/src/platform/dashpay/mod.rs b/packages/rs-sdk/src/platform/dashpay/mod.rs index 3789065cd31..27e6efbe4ae 100644 --- a/packages/rs-sdk/src/platform/dashpay/mod.rs +++ b/packages/rs-sdk/src/platform/dashpay/mod.rs @@ -16,9 +16,9 @@ pub use contact_request::{ }; pub use contact_request_queries::ContactRequestDocuments; 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 profile::ProfileFields; diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift index 548e2d19c83..20d5906209e 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift @@ -2575,19 +2575,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 + ) } } @@ -2693,6 +2722,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, @@ -2810,13 +2854,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 e7e746105e6..8cb476df4a4 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift @@ -264,6 +264,18 @@ public enum PlatformWalletResultCode: Int32, Sendable { case errorSpvProcessRestartRequired = 59 /// A whole-wallet asset lock exceeds the input cap; nothing was broadcast. case errorAssetLockTooManyInputs = 60 + /// 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 named thing does not exist. Besides the handle/lookup failures this /// has always covered, BOTH deferred-send paths report the /// wallet-was-REMOVED case here. @@ -395,6 +407,14 @@ public enum PlatformWalletResultCode: Int32, Sendable { self = .errorSpvProcessRestartRequired case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_ASSET_LOCK_TOO_MANY_INPUTS: self = .errorAssetLockTooManyInputs + 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_NOT_FOUND: self = .notFound case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_UNKNOWN: @@ -581,6 +601,24 @@ public enum PlatformWalletError: LocalizedError { case assetLockInsufficientFunds(String) /// A drain cannot fit every eligible input in one transaction. No partial drain occurred. case assetLockTooManyInputs(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. + case invitationKeysAlreadyRegistered(identityId: String?) + /// 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) case walletAlreadyExists(String) /// Definitive shielded-broadcast failure: the shielded transition /// (identity-create or a spend — unshield / transfer / withdrawal) was @@ -805,7 +843,8 @@ public enum PlatformWalletError: LocalizedError { .coreInsufficientFunds(let m), .assetLockNotTracked(let m), .assetLockAlreadyConsumed(let m), .assetLockFundingMismatch(let m), .assetLockInsufficientFunds(let m), - .assetLockTooManyInputs(let m), + .assetLockTooManyInputs(let m), .assetLockNotChainLocked(let m), + .invitationNotReady(let m), .walletAlreadyExists(let m), .shieldedBroadcastFailed(let m), .shieldedBroadcastUnconfirmed(let m), .shieldedSpendUnconfirmed(let m), .shieldedNoRecordedAnchor(let m), .shieldedInsufficientBalance(let m), @@ -851,6 +890,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 " @@ -924,6 +970,22 @@ public enum PlatformWalletError: LocalizedError { case .errorAssetLockFundingMismatch: self = .assetLockFundingMismatch(detail) case .errorAssetLockInsufficientFunds: self = .assetLockInsufficientFunds(detail) case .errorAssetLockTooManyInputs: self = .assetLockTooManyInputs(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) + } else { + self = .unknown(detail) + } + case .errorInvitationClaimedByThisWallet: + if let identityId = InvitationErrorDetail.decode(detail)?.identityId { + self = .invitationClaimedByThisWallet(identityId: identityId) + } else { + self = .unknown(detail) + } case .errorWalletAlreadyExists: self = .walletAlreadyExists(detail) case .errorShieldedBroadcastFailed: self = .shieldedBroadcastFailed(detail) case .errorShieldedBroadcastUnconfirmed: self = .shieldedBroadcastUnconfirmed(detail) @@ -1083,6 +1145,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 6953c89e694..ff7c043aaa3 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift @@ -240,6 +240,11 @@ struct ClaimInvitationSheet: View { } else { dismiss() } + } catch PlatformWalletError.invitationClaimedByThisWallet { + // An earlier claim from this wallet already created the + // identity, which this claim did not record. + errorMessage = "This invitation already created an identity in this wallet. " + + "It appears once identities are refreshed." } catch { errorMessage = error.localizedDescription } diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift index f18b44a9fce..08097ba7d02 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift @@ -439,6 +439,70 @@ 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" + guard case .invitationKeysAlreadyRegistered(let owner) = PlatformWalletError( + code: .errorInvitationKeysAlreadyRegistered, message: "{\"identityId\":\"\(id)\"}" + ) else { return XCTFail("lost typed keys-already-registered error") } + XCTAssertEqual(owner, id) + guard case .invitationKeysAlreadyRegistered(let unknownOwner) = PlatformWalletError( + code: .errorInvitationKeysAlreadyRegistered, message: "{\"identityId\":null}" + ) else { return XCTFail("lost the owner-less keys-already-registered error") } + XCTAssertNil(unknownOwner) + 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 From 4bfbb24b81404ca59bc17abdafe068031251bde6 Mon Sep 17 00:00:00 2001 From: Roman <51091564+jeanpierreroma@users.noreply.github.com> Date: Thu, 22 Oct 2026 13:42:53 +0300 Subject: [PATCH 02/15] docs(platform-wallet): name #5536 as the owner of codes 63-66 Co-Authored-By: Claude Opus 5.5 --- packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md index e3490f7a866..ff650933ace 100644 --- a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md +++ b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md @@ -115,7 +115,7 @@ These are shipped ABI. Do not renumber. | 99 | `ErrorUnknown` | Sentinel — unmapped/flattened errors | **Next allocatable integer: 67** — 27–66 are all claimed (63–66 proposed by -the DashPay invitation-claim preflight; 61 is held by open #5395 and 62 by open +#5536, the DashPay invitation-claim preflight; 61 is held by open #5395 and 62 by open #5487, which record their own rows; 27, 29, 31, 34–42 and 46 merged; 43–45 proposed by active #4313 at head `0302b188ab`; 47 and 48 proposed by active #4356 (47 renumbered from 42, 48 from 43 — see their @@ -179,10 +179,10 @@ Fork-era numbers remain in the collision history, which is immutable record. | 58 | `ErrorIdentityBalanceUnavailable` | #4799 | Proposed — Platform returned no balance for a managed identity. Retrying the read is safe; this is distinct from missing wallet ownership and must not trigger registration or funding | | 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 — the full drain needs more inputs than an asset lock may carry (100 on Dash Core relay policy and Platform consensus); no partial drain was broadcast. Rust, Swift and Kotlin retain the typed refusal. Renumbered from 59 after #5322 claimed it | -| 63 | `ErrorInvitationKeysAlreadyRegistered` | DashPay invitation-claim preflight | 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. 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` | DashPay invitation-claim preflight | 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` | DashPay invitation-claim preflight | 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` | DashPay invitation-claim preflight | 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 | +| 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. 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 | **Code 31 left this table on 2026-08-04.** `ErrorSigningKeyUnavailable` sat here as #4183's proposal until #4183 merged (`189a3abb1c`); it is now in the merged From 7863d1fe1cf74837d75a1fbf399981f9b216de7a Mon Sep 17 00:00:00 2001 From: Roman <51091564+jeanpierreroma@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:55:26 +0300 Subject: [PATCH 03/15] fix(platform-wallet): address review of the invitation claim preflight - Recognize a landed claim whose master key is BLS: Platform signs BLS keys into an identity like ECDSA ones. - Check every key-hash result for the invitation's identity before reporting a taken key, whatever order the keys were submitted in. - Keep Platform's 40207/10501 refusal on KeysAlreadyRegistered and stamp its consensus code on FFI code 63. - Classify an unverifiable claim-status lookup as NotReady, as the claim does. - Release the wallet storage before the claim's network round, and the wallet-manager guard before deriving from a resolved master key. - Correct the protocol version the duplicate-key refusal changed in (v11), narrow the wallet-internal claimant API to pub(crate), fix doc placement. Co-Authored-By: Claude Opus 5.5 --- .../ERROR_CODE_REGISTRY.md | 2 +- packages/rs-platform-wallet-ffi/src/error.rs | 70 ++++++--- .../rs-platform-wallet-ffi/src/invitation.rs | 22 +-- packages/rs-platform-wallet/src/error.rs | 30 +++- .../src/wallet/identity/network/invitation.rs | 33 +++-- .../src/wallet/identity/network/mod.rs | 4 +- .../rs-sdk/src/platform/dashpay/invitation.rs | 134 +++++++++++++----- 7 files changed, 213 insertions(+), 82 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md index ff650933ace..279b464723f 100644 --- a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md +++ b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md @@ -179,7 +179,7 @@ Fork-era numbers remain in the collision history, which is immutable record. | 58 | `ErrorIdentityBalanceUnavailable` | #4799 | Proposed — Platform returned no balance for a managed identity. Retrying the read is safe; this is distinct from missing wallet ownership and must not trigger registration or funding | | 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 — the full drain needs more inputs than an asset lock may carry (100 on Dash Core relay policy and Platform consensus); no partial drain was broadcast. Rust, Swift and Kotlin retain the typed refusal. Renumbered from 59 after #5322 claimed it | -| 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. 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 | +| 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 | diff --git a/packages/rs-platform-wallet-ffi/src/error.rs b/packages/rs-platform-wallet-ffi/src/error.rs index d71e2adf025..c98e2f8f898 100644 --- a/packages/rs-platform-wallet-ffi/src/error.rs +++ b/packages/rs-platform-wallet-ffi/src/error.rs @@ -770,6 +770,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 @@ -894,7 +908,7 @@ fn error_json_detail(error: &PlatformWalletError) -> Option<(PlatformWalletFFIRe }) .to_string(), )), - PlatformWalletError::InvitationKeysAlreadyRegistered { identity_id } => Some(( + PlatformWalletError::InvitationKeysAlreadyRegistered { identity_id, .. } => Some(( PlatformWalletFFIResultCode::ErrorInvitationKeysAlreadyRegistered, serde_json::json!({ "identityId": identity_id.map(|id| id.to_string(Encoding::Base58)), @@ -918,7 +932,7 @@ impl From for PlatformWalletFFIResult { // 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); + 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 @@ -1197,17 +1211,7 @@ impl From for PlatformWalletFFIResult { // mid-string and is deliberately not matched. _ => 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) } } @@ -2254,6 +2258,7 @@ mod tests { ( PlatformWalletError::InvitationKeysAlreadyRegistered { identity_id: Some(id), + rejection: None, }, PlatformWalletFFIResultCode::ErrorInvitationKeysAlreadyRegistered, 63, @@ -2307,13 +2312,16 @@ mod tests { }; assert_eq!( detail(PlatformWalletError::InvitationKeysAlreadyRegistered { - identity_id: Some(id) + identity_id: Some(id), + rejection: None, })["identityId"], id.to_string(Encoding::Base58) ); assert!( - detail(PlatformWalletError::InvitationKeysAlreadyRegistered { identity_id: None }) - ["identityId"] + detail(PlatformWalletError::InvitationKeysAlreadyRegistered { + identity_id: None, + rejection: None, + })["identityId"] .is_null() ); assert_eq!( @@ -2622,6 +2630,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 b8ebf26e229..edcfa3a9d81 100644 --- a/packages/rs-platform-wallet-ffi/src/invitation.rs +++ b/packages/rs-platform-wallet-ffi/src/invitation.rs @@ -327,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 { diff --git a/packages/rs-platform-wallet/src/error.rs b/packages/rs-platform-wallet/src/error.rs index bc9705ef58f..c0fffc3e3b5 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -109,12 +109,17 @@ pub enum PlatformWalletError { /// 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. + /// 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 }, + 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. @@ -1083,9 +1088,13 @@ impl From for PlatformWalletError { InvitationError::AlreadyClaimed { identity_id } => { Self::InvitationAlreadyClaimed { identity_id } } - InvitationError::KeysAlreadyRegistered { identity_id } => { - Self::InvitationKeysAlreadyRegistered { identity_id } - } + InvitationError::KeysAlreadyRegistered { + identity_id, + rejection, + } => Self::InvitationKeysAlreadyRegistered { + identity_id, + rejection, + }, InvitationError::NotReady(error) => Self::InvitationNotReady(error), InvitationError::Sdk(error) => Self::Sdk(error), } @@ -1163,12 +1172,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, } } @@ -1909,8 +1924,9 @@ mod invitation_error_mapping_tests { assert!(matches!( PlatformWalletError::from(InvitationError::KeysAlreadyRegistered { identity_id: owner, + rejection: None, }), - PlatformWalletError::InvitationKeysAlreadyRegistered { identity_id } if identity_id == owner + PlatformWalletError::InvitationKeysAlreadyRegistered { identity_id, .. } if identity_id == owner )); } assert!(matches!( 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 97954d076a1..64adf232a4e 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/invitation.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/invitation.rs @@ -50,10 +50,14 @@ 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 enum InvitationClaimantKey<'a> { +pub(crate) enum InvitationClaimantKey<'a> { /// Derive it from the in-process wallet (a wallet with resident private /// keys). ResidentWallet, @@ -330,7 +334,7 @@ impl IdentityWallet { /// [`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 async fn invitation_claim_status_with_identity( + pub(crate) async fn invitation_claim_status_with_identity( &self, invitation: &ParsedInvitation, ) -> Result<(InvitationClaimStatus, Option), PlatformWalletError> { @@ -456,7 +460,7 @@ impl IdentityWallet { /// - The master key cannot be derived (`key` is /// [`InvitationClaimantKey::Unavailable`], or the derivation fails) → /// `None`: unknown. - pub async fn invitation_claimed_by_this_wallet( + pub(crate) async fn invitation_claimed_by_this_wallet( &self, claimed: Option<&Identity>, identity_index: u32, @@ -488,25 +492,32 @@ impl IdentityWallet { identity_index: u32, key: InvitationClaimantKey<'_>, ) -> Result, PlatformWalletError> { - if matches!(key, InvitationClaimantKey::Unavailable) { - return Ok(None); - } - let wm = self.wallet_manager.read().await; - let wallet = wm.get_wallet(&self.wallet_id).ok_or_else(|| { - PlatformWalletError::WalletNotFound("Wallet not found in wallet manager".to_string()) - })?; 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; + wm.get_wallet(&self.wallet_id) + .ok_or_else(wallet_not_found)? + .network + }; derive_ecdsa_identity_auth_keypair_from_master( master, - wallet.network, + 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 = wm + .get_wallet(&self.wallet_id) + .ok_or_else(wallet_not_found)?; let (_path, _private, public_key) = derive_identity_auth_keypair( wallet, wallet.network, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs index b90c3b86c7e..8e121a95005 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs @@ -61,8 +61,8 @@ mod contacts; mod dashpay_view; mod invitation; pub use invitation::{ - Invitation, InvitationClaimStatus, InvitationClaimantKey, MAX_INVITATION_DUFFS, - MAX_INVITATION_TTL_SECS, MIN_INVITATION_DUFFS, + Invitation, InvitationClaimStatus, MAX_INVITATION_DUFFS, MAX_INVITATION_TTL_SECS, + MIN_INVITATION_DUFFS, }; mod payment_handler; pub(crate) use payment_handler::DashPayPaymentHandler; diff --git a/packages/rs-sdk/src/platform/dashpay/invitation.rs b/packages/rs-sdk/src/platform/dashpay/invitation.rs index b55e36e6e6e..44c5a7ee2aa 100644 --- a/packages/rs-sdk/src/platform/dashpay/invitation.rs +++ b/packages/rs-sdk/src/platform/dashpay/invitation.rs @@ -187,11 +187,17 @@ pub enum InvitationError { /// `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 }, + 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`]). @@ -753,9 +759,9 @@ 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 the same consensus code as a key - // registered elsewhere (10501 before protocol v7), which the claim reads - // as `KeysAlreadyRegistered`. + // 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 {}", @@ -866,7 +872,9 @@ impl Sdk { ) -> 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 claimed = Identity::fetch(self, prospective_identity_id).await?; + 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, @@ -1066,19 +1074,23 @@ where keys_taken_on_broadcast(submit().await) } -/// Whether `identity` holds `master_key`: an ECDSA key with the same key data. +/// 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 data counts, not the purpose, security level or bounds, because Platform -/// accepts an ECDSA 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. +/// 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 { - master_key.key_type() == KeyType::ECDSA_SECP256K1 - && identity.public_keys().values().any(|key| { - key.key_type() == KeyType::ECDSA_SECP256K1 && key.data() == master_key.data() - }) + 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 @@ -1089,10 +1101,12 @@ pub fn identity_holds_master_key(identity: &Identity, master_key: &IdentityPubli /// invitation's identity first: /// 1. it exists and holds `master_key` → [`InvitationError::ClaimedByThisWallet`]; /// 2. it exists otherwise → [`InvitationError::AlreadyClaimed`]; -/// 3. a 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); any other -/// identity → [`InvitationError::KeysAlreadyRegistered`]; -/// 4. a lookup failed → [`InvitationError::NotReady`] when any failed +/// 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. @@ -1121,6 +1135,7 @@ where // 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) => {} @@ -1134,10 +1149,10 @@ where 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)) => { - return Err(InvitationError::KeysAlreadyRegistered { - identity_id: Some(identity.id()), - }); + foreign_owner.get_or_insert(identity.id()); } Ok(None) => {} // Keep "not verified yet" over any other failure: it is the one @@ -1152,6 +1167,12 @@ where } } } + 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(()), @@ -1183,9 +1204,10 @@ fn lookup_failure(error: Error) -> InvitationError { /// Platform refused the broadcast claim because one of its keys is already /// registered to another identity: 40207 (`DuplicatedIdentityPublicKeyIdStateError`), -/// or 10501 (`DuplicatedIdentityPublicKeyIdBasicError`) before protocol v7. +/// or 10501 (`DuplicatedIdentityPublicKeyIdBasicError`) before protocol v11. /// That refusal is final for these keys, so it becomes -/// [`InvitationError::KeysAlreadyRegistered`]. 10501 is also Platform's answer +/// [`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( @@ -1193,7 +1215,10 @@ fn keys_taken_on_broadcast( ) -> Result { match result { Err(InvitationError::Sdk(error)) if is_identity_key_already_registered(&error) => { - Err(InvitationError::KeysAlreadyRegistered { identity_id: None }) + Err(InvitationError::KeysAlreadyRegistered { + identity_id: None, + rejection: Some(error), + }) } other => other, } @@ -2402,8 +2427,8 @@ mod tests { )); } - /// Our identity is recognized by the master key's data alone, whatever - /// the key's other fields; a hash-only key never matches. + /// 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); @@ -2425,6 +2450,18 @@ mod tests { &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 --- @@ -2559,7 +2596,7 @@ mod tests { .await; assert!(matches!( result, - Err(InvitationError::KeysAlreadyRegistered { identity_id: Some(id) }) + Err(InvitationError::KeysAlreadyRegistered { identity_id: Some(id), .. }) if id == Identifier::new([3; 32]) )); } @@ -2579,7 +2616,8 @@ mod tests { assert!(matches!( result, Err(InvitationError::KeysAlreadyRegistered { - identity_id: Some(_) + identity_id: Some(_), + .. }) )); } @@ -2619,6 +2657,24 @@ mod tests { )); } + /// 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] @@ -2643,7 +2699,10 @@ mod tests { .await; assert!(matches!( taken, - Err(InvitationError::KeysAlreadyRegistered { identity_id: None }) + Err(InvitationError::KeysAlreadyRegistered { + identity_id: None, + rejection: Some(_), + }) )); let claimed = claim_unless_refused(async { Ok(()) }, || async { Ok(ours()) }).await; @@ -2668,7 +2727,8 @@ mod tests { assert!(matches!( result, Err(InvitationError::KeysAlreadyRegistered { - identity_id: Some(_) + identity_id: Some(_), + .. }) )); } @@ -2722,6 +2782,7 @@ mod tests { 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; @@ -2743,10 +2804,15 @@ mod tests { DuplicatedIdentityPublicKeyIdBasicError::new(vec![0]), )), ] { - assert!(matches!( - keys_taken_on_broadcast(Err(refused(error))), - Err(InvitationError::KeysAlreadyRegistered { identity_id: None }) - )); + 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:?}"), + } } } From 5be60e7cde1f95684d324f5e974ba8545e7f329e Mon Sep 17 00:00:00 2001 From: Roman <51091564+jeanpierreroma@users.noreply.github.com> Date: Thu, 22 Oct 2026 16:51:20 +0300 Subject: [PATCH 04/15] fix(swift-sdk): keep Platform's refusal on invitationKeysAlreadyRegistered Code 63 refused after the broadcast now carries Platform's 40207/10501 consensus verdict; the typed Swift case keeps it beside the classification and `consensusError` returns it. Co-Authored-By: Claude Opus 5.5 --- .../PlatformWallet/PlatformWalletResult.swift | 33 ++++++++++++------- .../ErrorHandlingTests.swift | 28 ++++++++++++---- 2 files changed, 44 insertions(+), 17 deletions(-) diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift index 8cb476df4a4..b0985dd0615 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift @@ -608,8 +608,10 @@ public enum PlatformWalletError: LocalizedError { /// 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. - case invitationKeysAlreadyRegistered(identityId: String?) + /// 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 @@ -818,12 +820,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 @@ -890,7 +898,7 @@ 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): + case .invitationKeysAlreadyRegistered(let identityId, _): guard let identityId else { return "A key of this invitation claim is already registered to another identity." } @@ -935,8 +943,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, @@ -976,7 +985,9 @@ public enum PlatformWalletError: LocalizedError { // payload that does not decode degrades to `.unknown(detail)`. case .errorInvitationKeysAlreadyRegistered: if let d = InvitationErrorDetail.decode(detail) { - self = .invitationKeysAlreadyRegistered(identityId: d.identityId) + self = .invitationKeysAlreadyRegistered( + identityId: d.identityId, consensus: consensus + ) } else { self = .unknown(detail) } diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift index 08097ba7d02..435ab7bdabb 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift @@ -458,14 +458,30 @@ final class ErrorHandlingTests: XCTestCase { } let id = "8eTDkBhpQjHeqgbVeriwLeZr1tCa6yBGw76SckvD1cwc" - guard case .invitationKeysAlreadyRegistered(let owner) = PlatformWalletError( + // 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)\"}" - ) else { return XCTFail("lost typed keys-already-registered error") } + ) + guard case .invitationKeysAlreadyRegistered(let owner, nil) = found + else { return XCTFail("lost typed keys-already-registered error") } XCTAssertEqual(owner, id) - guard case .invitationKeysAlreadyRegistered(let unknownOwner) = PlatformWalletError( - code: .errorInvitationKeysAlreadyRegistered, message: "{\"identityId\":null}" - ) else { return XCTFail("lost the owner-less keys-already-registered error") } - XCTAssertNil(unknownOwner) + 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") } From b96690e14fea5a5e380ee08d943f66914e66eb16 Mon Sep 17 00:00:00 2001 From: Roman <51091564+jeanpierreroma@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:57:50 +0300 Subject: [PATCH 05/15] fix(sdk): pin the claim's preflight wiring and load our own identity on code 64 - Test `Sdk::claim_invitation` against a mock SDK: our identity found by id and a taken key found by the last key's hash both end the claim before signing; with nothing registered it reaches the signer. `MockDashPlatformSdk::expect_request` (test-only) answers the Core funding-transaction request. - `adopt_already_landed_claim` takes the master key from its caller, dropping an arm that could not be reached. - Both example apps continue with the identity a code 64 names: the one the wallet records, or the one loaded from Platform when its id matches; otherwise they show its id and point to the re-scan screen. Co-Authored-By: Claude Opus 5.5 --- .../ui/dashpay/ClaimInvitationSheet.kt | 40 +++- packages/rs-sdk/src/mock/sdk.rs | 34 ++- .../rs-sdk/src/platform/dashpay/invitation.rs | 223 ++++++++++++++++-- .../Views/DashPay/ClaimInvitationSheet.swift | 39 ++- 4 files changed, 293 insertions(+), 43 deletions(-) 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 63375e2ae2c..831400956d7 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 @@ -31,6 +31,7 @@ import org.dashfoundation.dashsdk.tokens.InvitationPreview 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 /** @@ -163,13 +164,32 @@ 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 created without + // recording it, which discovery loads like any + // identity of this wallet. Only the identity the + // error names counts. + val claimedId = Base58.decodeIdentifier(e.identityId) ?: throw e + walletOwned.firstOrNull { it.identityId.contentEquals(claimedId) } + ?.identityId + ?: runCatching { + mgr.identityRegistration.discoverIdentities( + walletHandle = wallet.handle, + mnemonicResolverHandle = mgr.mnemonicResolverHandle, + ) + }.getOrNull() + ?.firstOrNull { it.contentEquals(claimedId) } + ?: throw e + } } val username = preview.inviterUsername if (username != null) { @@ -179,10 +199,8 @@ fun ClaimInvitationSheet( } } catch (t: Throwable) { errorMessage = if (t is DashSdkError.PlatformWallet.InvitationClaimedByThisWallet) { - // An earlier claim from this wallet already created the - // identity, which this claim did not record. - "This invitation already created an identity in this wallet. " + - "It appears once identities are refreshed." + "This invitation already created identity ${t.identityId} in this wallet. " + + "If it is not listed, try Search Wallets for Identities." } else { t.message ?: "Claiming the invitation failed." } diff --git a/packages/rs-sdk/src/mock/sdk.rs b/packages/rs-sdk/src/mock/sdk.rs index 49d781b3a47..fb0e1dd45b1 100644 --- a/packages/rs-sdk/src/mock/sdk.rs +++ b/packages/rs-sdk/src/mock/sdk.rs @@ -53,6 +53,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 @@ -534,11 +553,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(()) @@ -638,3 +653,12 @@ fn load_expectation( dapi_guard.expect(&data.0, &data.1)?; 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"), + } +} diff --git a/packages/rs-sdk/src/platform/dashpay/invitation.rs b/packages/rs-sdk/src/platform/dashpay/invitation.rs index 44c5a7ee2aa..ca01cbcb2cf 100644 --- a/packages/rs-sdk/src/platform/dashpay/invitation.rs +++ b/packages/rs-sdk/src/platform/dashpay/invitation.rs @@ -981,6 +981,7 @@ impl Sdk { || Identity::fetch(self, prospective_identity_id), |hash| Identity::fetch(self, PublicKeyHash(hash)), ); + let master_key = &master_key; claim_unless_refused(preflight, || async move { // The voucher key signs the asset lock's outer ST signature (ECDSA @@ -1029,9 +1030,13 @@ impl Sdk { // 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) - }) + adopt_already_landed_claim( + submitted, + &out_point, + placeholder.public_keys(), + master_key, + || Identity::fetch(self, prospective_identity_id), + ) .await }) .await @@ -1398,12 +1403,13 @@ fn identity_id_for_out_point(out_point: OutPoint) -> Identifier { /// 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 @@ -1426,10 +1432,7 @@ where } // 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)) => match submitted_keys.get(&0) { - Some(master_key) => Err(claimed_by(&identity, master_key)), - None => Err(InvitationError::Sdk(error)), - }, + Ok(Some(identity)) => Err(claimed_by(&identity, master_key)), Ok(None) => Err(InvitationError::Sdk(error)), Err(lookup) => { tracing::warn!( @@ -2876,11 +2879,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()) } @@ -3344,4 +3348,195 @@ 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. + 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 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::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) { + 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 sdk = SdkBuilder::new_mock() + .with_network(Network::Testnet) + .build() + .expect("mock sdk"); + 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(&claim_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), claim_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:?}" + ); + } + + /// 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/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift index ff7c043aaa3..250762aaf13 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift @@ -218,14 +218,32 @@ 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 }) { + newIdentityId = recorded.identityId + } else if let loaded = try? await wallet.loadIdentity(atIndex: identityIndex), + loaded.toBase58String() == claimedId { + newIdentityId = loaded + } else { + errorMessage = "This invitation already created identity \(claimedId) " + + "in this wallet. If it is not listed, try Re-scan for Identities." + return + } + } kickDashPaySync(walletManager) // Offer the contact-bootstrap when the link carried an inviter @@ -240,11 +258,6 @@ struct ClaimInvitationSheet: View { } else { dismiss() } - } catch PlatformWalletError.invitationClaimedByThisWallet { - // An earlier claim from this wallet already created the - // identity, which this claim did not record. - errorMessage = "This invitation already created an identity in this wallet. " - + "It appears once identities are refreshed." } catch { errorMessage = error.localizedDescription } From a51289bcccb7c7fa40355556194a4f15f30210b9 Mon Sep 17 00:00:00 2001 From: Roman <51091564+jeanpierreroma@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:24:02 +0200 Subject: [PATCH 06/15] fix(sdk): keep a failed identity load apart from a missing identity in the claim sheets On code 64 a failed load of the claimed identity is now reported as a failure to retry instead of "not listed". On code 63 both example apps load the identity at the claim's index; when it is the key owner, it is recorded and the user claims again at the next index. Kotlin gains a bridge to platform_wallet_load_identity_at_index, which the Swift app already calls, so both apps probe exactly the claim's index. Co-Authored-By: Claude Opus 5.5 --- .../ui/dashpay/ClaimInvitationSheet.kt | 68 +++++++++++++++---- .../dashsdk/ffi/IdentityNative.kt | 11 +++ .../dashsdk/identity/IdentityRegistration.kt | 17 +++++ packages/rs-unified-sdk-jni/src/identity.rs | 33 +++++++++ .../Views/DashPay/ClaimInvitationSheet.swift | 42 ++++++++++-- 5 files changed, 151 insertions(+), 20 deletions(-) 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 831400956d7..83a472e3525 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 @@ -28,6 +28,7 @@ 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 @@ -174,21 +175,34 @@ fun ClaimInvitationSheet( ) } catch (e: DashSdkError.PlatformWallet.InvitationClaimedByThisWallet) { // The invitation's identity is this wallet's: one it - // records, or one an earlier claim created without - // recording it, which discovery loads like any - // identity of this wallet. Only the identity the + // 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.identityId.contentEquals(claimedId) } ?.identityId - ?: runCatching { - mgr.identityRegistration.discoverIdentities( - walletHandle = wallet.handle, - mnemonicResolverHandle = mgr.mnemonicResolverHandle, - ) - }.getOrNull() - ?.firstOrNull { it.contentEquals(claimedId) } + ?: 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 @@ -198,11 +212,12 @@ fun ClaimInvitationSheet( onClose() } } catch (t: Throwable) { - errorMessage = if (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." - } else { - 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 @@ -328,3 +343,26 @@ 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)) +} + +/** A recovery outcome of the claim, shown to the user as is. */ +private class ClaimRecoveryMessage(override val message: String) : Exception(message) 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 1fe90dd9615..b4281c55ec1 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 @@ -228,6 +228,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..1c0981b63f8 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,23 @@ 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 { + 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/rs-unified-sdk-jni/src/identity.rs b/packages/rs-unified-sdk-jni/src/identity.rs index 5602c73c255..a79b2e48195 100644 --- a/packages/rs-unified-sdk-jni/src/identity.rs +++ b/packages/rs-unified-sdk-jni/src/identity.rs @@ -928,6 +928,39 @@ 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| { + 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/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift index 250762aaf13..9b387a73832 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift @@ -235,14 +235,46 @@ struct ClaimInvitationSheet: View { // of this wallet. Only the identity the error names counts. if let recorded = identities.first(where: { $0.identityIdBase58 == claimedId }) { newIdentityId = recorded.identityId - } else if let loaded = try? await wallet.loadIdentity(atIndex: identityIndex), - loaded.toBase58String() == claimedId { - newIdentityId = loaded } else { - errorMessage = "This invitation already created identity \(claimedId) " - + "in this wallet. If it is not listed, try Re-scan for Identities." + 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) From da374fc09880c2cd10280c7de0f4ef01746dbd91 Mon Sep 17 00:00:00 2001 From: Roman <51091564+jeanpierreroma@users.noreply.github.com> Date: Mon, 26 Oct 2026 12:51:44 +0200 Subject: [PATCH 07/15] fix(sdk): reject a negative index in loadIdentityAtIndex and scope the claim shortcut to its wallet The JNI bridge and the Kotlin wrapper refuse a negative identity index instead of probing the slot the u32 cast lands on. On code 64 both example apps take a recorded identity as the claimed one only when it is recorded under the selected wallet; otherwise they load it from that wallet. Co-Authored-By: Claude Opus 5.5 --- .../ui/dashpay/ClaimInvitationSheet.kt | 6 +++-- .../dashsdk/identity/IdentityRegistration.kt | 1 + .../identity/IdentityLoadAtIndexTest.kt | 23 +++++++++++++++++++ packages/rs-unified-sdk-jni/src/identity.rs | 4 ++++ .../Views/DashPay/ClaimInvitationSheet.swift | 4 +++- 5 files changed, 35 insertions(+), 3 deletions(-) create mode 100644 packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/identity/IdentityLoadAtIndexTest.kt 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 83a472e3525..42d4c882a36 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 @@ -180,8 +180,10 @@ fun ClaimInvitationSheet( // any identity of this wallet. Only the identity the // error names counts. val claimedId = Base58.decodeIdentifier(e.identityId) ?: throw e - walletOwned.firstOrNull { it.identityId.contentEquals(claimedId) } - ?.identityId + 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." 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 1c0981b63f8..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 @@ -474,6 +474,7 @@ class IdentityRegistration internal constructor( 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) } 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-unified-sdk-jni/src/identity.rs b/packages/rs-unified-sdk-jni/src/identity.rs index a79b2e48195..ccc86e2ac8f 100644 --- a/packages/rs-unified-sdk-jni/src/identity.rs +++ b/packages/rs-unified-sdk-jni/src/identity.rs @@ -940,6 +940,10 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_IdentityNative_loadId 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 { diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift index 9b387a73832..53b2d9b98cd 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift @@ -233,7 +233,9 @@ struct ClaimInvitationSheet: View { // 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 }) { + if let recorded = identities.first(where: { + $0.identityIdBase58 == claimedId && $0.wallet?.walletId == walletId + }) { newIdentityId = recorded.identityId } else { let loaded: Identifier? From ef70fa6cb083ea70b1ce31baa70429bbb768d6ca Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 13:58:31 +0200 Subject: [PATCH 08/15] fix(swift-example-app): skip identity slots held by an in-flight registration when claiming an invitation The claim sheet picked one past the highest recorded identity index, so a normal registration still in flight for that slot (no identity row yet) could be given the same index and the same HD keys. The Kotlin sheet already counts the coordinator's slots. Co-Authored-By: Claude Opus 5.5 --- .../Views/DashPay/ClaimInvitationSheet.swift | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift index 3395ac0b0cf..16d811719ac 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift @@ -340,11 +340,17 @@ 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 } } From 7415d5937cd79fd5b13a3d558c65aaa11f6e5ee3 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 17:12:13 +0200 Subject: [PATCH 09/15] fix(swift-example-app): reserve the invitation claim's identity slot before deriving its keys The claim now marks its identity-registration slot used as soon as it picks the index, the same reservation CreateIdentityView reads, so a normal registration started while the claim is in flight skips that slot instead of deriving the same keys. Co-Authored-By: Claude Opus 5.5 --- .../Views/DashPay/ClaimInvitationSheet.swift | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift index 16d811719ac..3aa5bdb128a 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() + reserveIdentitySlot(identityIndex) // Register the invitee's own keys exactly like a normal // registration: master + auth keys, plus a DashPay enc/dec pair @@ -353,4 +356,16 @@ struct ClaimInvitationSheet: View { 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. + private func reserveIdentitySlot(_ identityIndex: UInt32) { + let slot = accounts + .first { $0.wallet.walletId == walletId && $0.accountType == 2 }? + .coreAddresses + .first { $0.addressIndex == identityIndex } + slot?.isUsed = true + } } From f312d9062318ca9aba7e3d8e7302af39e8a23e60 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 19:56:24 +0200 Subject: [PATCH 10/15] fix(swift-example-app): save the invitation claim's slot reservation at once The isUsed marker was left to SwiftData's autosave, so an app exit during the claim could lose it. The claim's own selector still ignores the marker on purpose: a retry after a lost result must return to the same slot to be recognized as this wallet's claim. Co-Authored-By: Claude Opus 5.5 --- .../Views/DashPay/ClaimInvitationSheet.swift | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift index 3aa5bdb128a..42ed5b4ea8f 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift @@ -203,7 +203,7 @@ struct ClaimInvitationSheet: View { } let signer = KeychainSigner(modelContainer: modelContext.container) let identityIndex = nextUnusedIdentityIndex() - reserveIdentitySlot(identityIndex) + try reserveIdentitySlot(identityIndex) // Register the invitee's own keys exactly like a normal // registration: master + auth keys, plus a DashPay enc/dec pair @@ -360,12 +360,19 @@ struct ClaimInvitationSheet: View { /// 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. - private func reserveIdentitySlot(_ identityIndex: UInt32) { + /// 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 } - slot?.isUsed = true + guard let slot, !slot.isUsed else { return } + slot.isUsed = true + try modelContext.save() } } From e5deb4a592460e09e0aadbb8162e759530900397 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 22:39:48 +0200 Subject: [PATCH 11/15] fix(sdk): refuse invitation claim keys that Platform's structural validation refuses Duplicate key data, too many keys, a wrong master-key count or a disallowed security level reached Platform, which refuses them only after charging part of the voucher. The claim now runs the identity-create structural validation from DPP on its keys before anything is signed. Co-Authored-By: Claude Opus 5.5 --- .../rs-sdk/src/platform/dashpay/invitation.rs | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/packages/rs-sdk/src/platform/dashpay/invitation.rs b/packages/rs-sdk/src/platform/dashpay/invitation.rs index 48793741ebf..9453c1449e6 100644 --- a/packages/rs-sdk/src/platform/dashpay/invitation.rs +++ b/packages/rs-sdk/src/platform/dashpay/invitation.rs @@ -86,6 +86,8 @@ use dpp::identity::v0::IdentityV0; 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; use crate::core::FetchedCoreTransaction; use crate::platform::transition::asset_lock_submission::{ @@ -772,6 +774,29 @@ fn preflight_keys_map(keys_map: &BTreeMap) -> Result<(), Ok(()) } +/// 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 @@ -956,6 +981,7 @@ impl Sdk { S: Signer + Send + Sync, { preflight_keys_map(&keys_map)?; + validate_claim_keys_structure(&keys_map, self.version())?; ensure_invitation_network(&invitation, self.network)?; // Reconstruct the funding asset-lock proof by refetching the tx. Consensus @@ -2429,6 +2455,29 @@ mod tests { assert!(preflight_keys_map(&our_keys()).is_ok()); } + /// 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 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] From a489bffaf11a16e5d69e09da5ceaf94ebe5f3b9e Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sun, 15 Nov 2026 18:40:34 +0200 Subject: [PATCH 12/15] fix(sdk): validate invitation claim keys at the network's protocol version The structural key check ran before any Platform request, at the version an SDK starts with (the network minimum), so keys a newer generation refuses could still be broadcast and charged. It now runs after the preflight: its proved lookups raise the SDK's version to the one the network signed, and nothing is signed before the check. Co-Authored-By: Claude Opus 5.5 --- .../rs-sdk/src/platform/dashpay/invitation.rs | 38 +++++++++++++++++-- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/packages/rs-sdk/src/platform/dashpay/invitation.rs b/packages/rs-sdk/src/platform/dashpay/invitation.rs index 9453c1449e6..2856f1a22e9 100644 --- a/packages/rs-sdk/src/platform/dashpay/invitation.rs +++ b/packages/rs-sdk/src/platform/dashpay/invitation.rs @@ -981,7 +981,6 @@ impl Sdk { S: Signer + Send + Sync, { preflight_keys_map(&keys_map)?; - validate_claim_keys_structure(&keys_map, self.version())?; ensure_invitation_network(&invitation, self.network)?; // Reconstruct the funding asset-lock proof by refetching the tx. Consensus @@ -1016,6 +1015,12 @@ impl Sdk { let master_key = &master_key; claim_unless_refused(preflight, || async move { + // Checked here, after the preflight: its lookups are proved, and + // each verified answer raises the SDK's protocol version to the + // network's, so the keys are judged by the rules Platform will + // apply rather than by the version an SDK starts with. + validate_claim_keys_structure(&keys_map, self.version())?; + // 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. @@ -3693,6 +3698,15 @@ mod tests { 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. + async fn claim_with_keys( + 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); @@ -3722,7 +3736,7 @@ mod tests { .expect_fetch(invitation_id, by_id(invitation_id)) .await .expect("expect the lookup by id"); - for hash in claim_key_hashes(&claim_keys()).expect("key hashes") { + for hash in claim_key_hashes(&keys).expect("key hashes") { sdk.mock() .expect_fetch(PublicKeyHash(hash), by_hash(hash, invitation_id)) .await @@ -3730,7 +3744,7 @@ mod tests { } let result = sdk - .claim_invitation(parsed(key, txid, None), claim_keys(), &UnusedSigner, None) + .claim_invitation(parsed(key, txid, None), keys, &UnusedSigner, None) .await; (result, invitation_id) } @@ -3772,6 +3786,24 @@ mod tests { ); } + /// 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(_))), + "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. From 8a78a8732ba81a9b4e3480155aff25fd891712a8 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sun, 15 Nov 2026 23:57:07 +0200 Subject: [PATCH 13/15] fix(sdk): judge invitation claim keys by the network's verified protocol version A pinned SDK keeps its operation version after a verified answer shows a newer network, so the structural check of the claim's keys could run under older rules than Platform applies. The keys are now judged by the newer of the SDK's version and the network's verified one; the claim is refused before signing when no verified answer showed it, or when this build has no rules for it. A keys map larger than any known version allows is refused before the per-key lookups start. Co-Authored-By: Claude Opus 5.5 --- .../rs-sdk/src/platform/dashpay/invitation.rs | 244 +++++++++++++++++- 1 file changed, 231 insertions(+), 13 deletions(-) diff --git a/packages/rs-sdk/src/platform/dashpay/invitation.rs b/packages/rs-sdk/src/platform/dashpay/invitation.rs index 2856f1a22e9..79d6c27e194 100644 --- a/packages/rs-sdk/src/platform/dashpay/invitation.rs +++ b/packages/rs-sdk/src/platform/dashpay/invitation.rs @@ -87,7 +87,7 @@ use dpp::identity::{Identity, IdentityPublicKey, KeyID, KeyType, Purpose, Securi use dpp::prelude::{AssetLockProof, Identifier}; use dpp::secp256k1::{PublicKey, SecretKey}; use dpp::state_transition::public_key_in_creation::IdentityPublicKeyInCreation; -use dpp::version::PlatformVersion; +use dpp::version::{PlatformVersion, PLATFORM_VERSIONS}; use crate::core::FetchedCoreTransaction; use crate::platform::transition::asset_lock_submission::{ @@ -98,7 +98,7 @@ 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 @@ -771,9 +771,53 @@ fn preflight_keys_map(keys_map: &BTreeMap) -> Result<(), 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 @@ -1015,11 +1059,12 @@ impl Sdk { let master_key = &master_key; claim_unless_refused(preflight, || async move { - // Checked here, after the preflight: its lookups are proved, and - // each verified answer raises the SDK's protocol version to the - // network's, so the keys are judged by the rules Platform will - // apply rather than by the version an SDK starts with. - validate_claim_keys_structure(&keys_map, self.version())?; + // 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 @@ -2460,6 +2505,33 @@ mod tests { 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. @@ -2483,6 +2555,62 @@ mod tests { )); } + /// 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] @@ -3614,6 +3742,7 @@ mod tests { 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}; @@ -3624,6 +3753,7 @@ mod tests { 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; @@ -3702,11 +3832,33 @@ mod tests { claim_with_keys(claim_keys(), by_id, by_hash).await } - /// [`claim`] with the given keys. + /// [`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); @@ -3716,10 +3868,21 @@ mod tests { tx.consensus_encode(&mut raw) .expect("encode the funding tx"); - let mut sdk = SdkBuilder::new_mock() - .with_network(Network::Testnet) - .build() - .expect("mock sdk"); + 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() }, @@ -3799,7 +3962,62 @@ mod tests { 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(_))), + 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:?}" ); } From f160a3c5b19f29f0782092140abc8dd4de62cc7d Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sun, 15 Nov 2026 23:57:07 +0200 Subject: [PATCH 14/15] fix(platform-wallet): keep an invitation claim to the wallet generation that started it A claim runs without the wallet manager's lock, so its wallet can be removed and re-created under the same id before it ends. The claim now records the new identity only through the generation-checked `current_wallet_info_mut`, and reads whether an identity is this wallet's (refusal classification, claim status, the claimant's master key) only from the handle's own generation. Co-Authored-By: Claude Opus 5.5 --- .../identity/network/identity_handle.rs | 10 +++ .../src/wallet/identity/network/invitation.rs | 81 ++++++++++++++++--- 2 files changed, 78 insertions(+), 13 deletions(-) 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 d5c5e3a9942..f1ed5715ee6 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/invitation.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/invitation.rs @@ -404,8 +404,8 @@ impl IdentityWallet { } let has_resident_keys = { let wm = self.wallet_manager.read().await; - wm.get_wallet(&self.wallet_id) - .is_some_and(has_resident_keys) + self.current_wallet_and_info(&wm) + .is_some_and(|(wallet, _)| has_resident_keys(wallet)) }; if has_resident_keys { return self @@ -441,11 +441,13 @@ impl IdentityWallet { } } - /// This wallet records `identity_id` as one of its own identities. + /// 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; - wm.get_wallet_info(&self.wallet_id) - .and_then(|info| info.identity_manager.managed_identity(identity_id)) + 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)) } @@ -499,8 +501,9 @@ impl IdentityWallet { // runs after its read guard is released. let network = { let wm = self.wallet_manager.read().await; - wm.get_wallet(&self.wallet_id) + self.current_wallet_and_info(&wm) .ok_or_else(wallet_not_found)? + .0 .network }; derive_ecdsa_identity_auth_keypair_from_master( @@ -515,8 +518,8 @@ impl IdentityWallet { // holds, so this derivation runs under its read guard. InvitationClaimantKey::ResidentWallet => { let wm = self.wallet_manager.read().await; - let wallet = wm - .get_wallet(&self.wallet_id) + let (wallet, _) = self + .current_wallet_and_info(&wm) .ok_or_else(wallet_not_found)?; let (_path, _private, public_key) = derive_identity_auth_keypair( wallet, @@ -586,9 +589,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, @@ -631,11 +636,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" ); } } @@ -735,6 +740,14 @@ mod tests { /// 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( @@ -742,6 +755,14 @@ mod tests { 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, @@ -1023,6 +1044,40 @@ mod tests { 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" and whose claim it was is + /// unknown, 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() + )); + } } // --- create_invitation: the durable-persistence precondition --- From 28852e6ea8cc407961eaba65c5b3a4bf534df418 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Mon, 16 Nov 2026 01:01:30 +0200 Subject: [PATCH 15/15] fix(platform-wallet): fence an own-claim refusal and identity load to the handle's wallet generation The SDK's own "claimed by this wallet" reached the host without a generation check, and the host then loads that identity through the same handle, whose loader wrote the fetched identity and its DPNS names by wallet id alone. A claim refusal now reports this wallet's claim only while the handle's wallet is still current (else WalletNotFound), and the loader's two writes go through the generation-checked `current_wallet_info_mut`. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/identity/network/invitation.rs | 44 +++++++++++++++++-- .../src/wallet/identity/network/loading.rs | 16 +++---- 2 files changed, 46 insertions(+), 14 deletions(-) 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 f1ed5715ee6..3b0b6800cb1 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/invitation.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/invitation.rs @@ -430,17 +430,36 @@ impl IdentityWallet { /// 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 { - match error { + 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. @@ -1047,8 +1066,10 @@ mod tests { /// 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" and whose claim it was is - /// unknown, while the replacement's own handle recognizes it. + /// 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; @@ -1077,6 +1098,23 @@ mod tests { .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() + )); } } 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); }