diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/IdentityRegistrationController.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/IdentityRegistrationController.kt index d5c38601053..184bc463eae 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/IdentityRegistrationController.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/IdentityRegistrationController.kt @@ -65,10 +65,10 @@ class IdentityRegistrationController( data class Failed(val message: String) : Phase /** - * Broadcast-succeeded-but-confirmation-failed terminal state - * (shielded only). The identity at [identityId] MAY already be live; - * the slot must stay held so a re-submission can't burn funds against - * the registered-key-hash check. + * Unconfirmed terminal state (shielded only): the transition may have + * reached a node and its result is not proved. The identity at + * [identityId] MAY already be live; the slot must stay held so a + * re-submission can't burn funds against the registered-key-hash check. */ data class Unconfirmed(val identityId: ByteArray, val message: String) : Phase { override fun equals(other: Any?): Boolean = @@ -90,12 +90,13 @@ class IdentityRegistrationController( /** * Which stage a shielded [Phase.Failed] failed at, so the progress - * screen can attribute the red marker. Only [BroadcastRejected] is - * attributable with confidence; every other failure leaves this null and - * the progress screen falls back to its elapsed-time heuristic. + * screen can attribute the red marker. Only [BroadcastNotSent] (the + * transition was refused before anything was sent) is attributable with + * confidence; every other failure leaves this null and the progress + * screen falls back to its elapsed-time heuristic. * ← Swift `FailureStage`. */ - enum class FailureStage { BroadcastRejected } + enum class FailureStage { BroadcastNotSent } private val _phase = MutableStateFlow(Phase.Idle) val phase: StateFlow = _phase.asStateFlow() @@ -136,7 +137,7 @@ class IdentityRegistrationController( fun submit( body: suspend () -> ByteArray, isUnconfirmed: (Throwable) -> ByteArray? = { null }, - isBroadcastRejected: (Throwable) -> Boolean = { false }, + isBroadcastNotSent: (Throwable) -> Boolean = { false }, ) { when (_phase.value) { is Phase.Idle, is Phase.PreparingKeys, is Phase.Failed -> Unit @@ -157,7 +158,7 @@ class IdentityRegistrationController( terminalAt = now() _phase.value = Phase.Unconfirmed(unconfirmedId, e.message ?: "Confirmation pending") } else { - _failureStage.value = if (isBroadcastRejected(e)) FailureStage.BroadcastRejected else null + _failureStage.value = if (isBroadcastNotSent(e)) FailureStage.BroadcastNotSent else null terminalAt = now() _phase.value = Phase.Failed(e.message ?: "Registration failed") } diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/RegistrationCoordinator.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/RegistrationCoordinator.kt index 553f3b0967a..69c590ef517 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/RegistrationCoordinator.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/RegistrationCoordinator.kt @@ -73,7 +73,7 @@ class RegistrationCoordinator( fundingKind: IdentityRegistrationController.FundingKind = IdentityRegistrationController.FundingKind.AssetLock, body: suspend () -> ByteArray, isUnconfirmed: (Throwable) -> ByteArray? = { null }, - isBroadcastRejected: (Throwable) -> Boolean = { false }, + isBroadcastNotSent: (Throwable) -> Boolean = { false }, ): IdentityRegistrationController { val key = SlotKey(walletId.toHex(), identityIndex) val existing = _controllers.value[key] @@ -89,7 +89,7 @@ class RegistrationCoordinator( -> { // Legitimate restart: a fresh idle controller, or a retry after failure. existing.enterPreparingKeys() - existing.submit(body, isUnconfirmed, isBroadcastRejected) + existing.submit(body, isUnconfirmed, isBroadcastNotSent) scheduleRetentionSweep(key, existing) return existing } @@ -98,7 +98,7 @@ class RegistrationCoordinator( val controller = IdentityRegistrationController(walletId, identityIndex, fundingKind, scope, now) _controllers.update { it + (key to controller) } controller.enterPreparingKeys() - controller.submit(body, isUnconfirmed, isBroadcastRejected) + controller.submit(body, isUnconfirmed, isBroadcastNotSent) scheduleRetentionSweep(key, controller) return controller } diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt index 5656d273640..783128fef29 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt @@ -730,10 +730,11 @@ fun SendTransactionScreen( } } } catch (e: DashSdkError.PlatformWallet.ShieldedSpendUnconfirmed) { - // Broadcast accepted but its execution result couldn't - // be confirmed — the spend may already be on chain and - // the notes stay reserved Rust-side, so this must NOT - // read as a retryable failure (← SendViewModel.swift:790). + // It may have reached a node and its result is not + // proved (a node's refusal or verdict included), so it + // may already be on chain and a retry signs a second + // transition: this must NOT read as a retryable + // failure (← SendViewModel.swift:790). successMessage = "Transaction may have gone through — waiting for " + "the next shielded sync to confirm. Do not retry." } catch (t: Throwable) { diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/services/RegistrationCoordinatorTest.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/services/RegistrationCoordinatorTest.kt index ccb9e56868f..d4d86bacbfd 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/services/RegistrationCoordinatorTest.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/services/RegistrationCoordinatorTest.kt @@ -110,7 +110,7 @@ class RegistrationCoordinatorTest { } @Test - fun `broadcast-rejected classifier sets failure stage`() = runTest { + fun `broadcast-not-sent classifier sets failure stage`() = runTest { val coordinator = coordinator() val gate = CompletableDeferred() @@ -119,14 +119,14 @@ class RegistrationCoordinatorTest { identityIndex = 0, fundingKind = IdentityRegistrationController.FundingKind.ShieldedPool, body = { gate.await() }, - isBroadcastRejected = { true }, + isBroadcastNotSent = { true }, ) - gate.completeExceptionally(RuntimeException("broadcast rejected")) + gate.completeExceptionally(RuntimeException("nothing was sent")) advanceUntilIdle() assertTrue(controller.phase.value is Phase.Failed) assertEquals( - IdentityRegistrationController.FailureStage.BroadcastRejected, + IdentityRegistrationController.FailureStage.BroadcastNotSent, controller.failureStage.value, ) } 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 02cf721a115..e008d027cde 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 @@ -267,31 +267,32 @@ sealed class DashSdkError( /** * `ErrorShieldedSpendUnconfirmed` (native code 18). A shielded spend - * (transfer / unshield / withdraw / shield) was broadcast and - * accepted, but its execution result couldn't be confirmed — it may - * already be on chain. Rust intentionally KEEPS the spent notes' - * reservations, so the caller must NOT retry (a retry would rebuild - * the bundle against other notes and could double-spend); the next - * shielded sync reconciles the outcome. The Android analog of + * (transfer / unshield / withdraw / shield from Platform addresses) + * may have reached a node and its result is not proved (a failed + * result wait, a node's refusal or a consensus verdict, stale address + * nonce included), so it may already be on chain. Do NOT retry: a + * retry signs a second transition. Spends keep their notes reserved + * for the wallet to resolve; a shield stays pending until the + * shielded scan observes its note. The Android analog of * Swift's `PlatformWalletError.shieldedSpendUnconfirmed`, which the * iOS send flow surfaces as a non-retryable "may have gone through" * outcome rather than an error. */ class ShieldedSpendUnconfirmed(message: String, cause: Throwable? = null) : PlatformWallet( - "$message (do NOT retry: the spend may already be on chain; " + - "the wallet keeps the spent notes reserved until the next " + - "shielded sync reconciles the outcome)", + "$message (do NOT retry: it may already be on chain or may " + + "still execute, and a retry signs a second transition)", cause, ) /** * `ErrorMasternodeWithdrawalUnconfirmed` (native code 42). A - * masternode (evonode) identity credit withdrawal was broadcast and - * accepted, but its execution result couldn't be confirmed — it may - * already have executed, and the identity nonce was consumed for it, - * so a blind retry could submit a SECOND withdrawal. Do NOT retry; - * re-read the identity's claimable balance and reconcile first. The + * masternode (evonode) identity credit withdrawal may have reached a + * node and its remaining balance is not proved (a failed result wait, + * a node's refusal or a consensus verdict included). It may have + * executed; a retry signs a second withdrawal with the next identity + * nonce. Do NOT retry; re-read the claimable balance first. Only a + * failure before anything was sent keeps an ordinary code. The * Android analog of Swift's * `PlatformWalletError.masternodeWithdrawalUnconfirmed`. */ @@ -304,10 +305,10 @@ sealed class DashSdkError( /** * `ErrorShieldedBroadcastFailed` (native code 16). A DEFINITIVE - * non-execution outcome — relay/CheckTx rejected the transaction - * before it entered the chain, and any note reservations were - * released. Safe to retry (the opposite of the ambiguous - * [ShieldedSpendUnconfirmed]). + * non-execution outcome: the transition never left the wallet + * (refused before anything was sent), so it can never execute, and + * any note reservations were released. Safe to retry (the opposite + * of the ambiguous [ShieldedSpendUnconfirmed]). */ class ShieldedBroadcastFailed(message: String, cause: Throwable? = null) : PlatformWallet(message, cause) { diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt index 5f074a73d5b..325504110da 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt @@ -2010,10 +2010,11 @@ class PlatformWalletManager( // (cached by [bindShielded]), so no signer or resolver handle crosses // JNI — matching the Swift counterparts, which take no signer either. // Each blocks for the ~30s Halo 2 proof on Dispatchers.IO. On the - // AMBIGUOUS outcome (broadcast accepted, execution unconfirmed) they - // throw [org.dashfoundation.dashsdk.errors.DashSdkError.PlatformWallet.ShieldedSpendUnconfirmed] - // — the caller must NOT retry (the spent notes stay reserved Rust-side; - // the next shielded sync reconciles the outcome). + // AMBIGUOUS outcome (the spend may have reached a node and its result is + // not proved, a node's refusal or verdict included) they + // throw [org.dashfoundation.dashsdk.errors.DashSdkError.PlatformWallet.ShieldedSpendUnconfirmed]: + // the caller must NOT retry (the spent notes stay reserved Rust-side + // until a later shielded sync resolves them). /** * Shielded → shielded transfer (Type 16) — port of Swift's diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt index 9614b42fa2f..2f97310a44c 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt @@ -132,7 +132,7 @@ class DashSdkErrorTest { DashSdkError.fromNative(DashSDKException(offset + 18, "ambiguous spend")) assertTrue(spendUnconfirmed is DashSdkError.PlatformWallet.ShieldedSpendUnconfirmed) assertFalse( - "ShieldedSpendUnconfirmed must NOT be retryable (notes stay reserved)", + "ShieldedSpendUnconfirmed must NOT be retryable (a retry signs a second transition)", spendUnconfirmed.isRetryable, ) // The message must warn against retrying, like the broadcast sibling. diff --git a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md index 1ab4ec40e4d..891fe70df54 100644 --- a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md +++ b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md @@ -87,12 +87,12 @@ These are shipped ABI. Do not renumber. | 13 | `ErrorArithmeticOverflow` | Produced in-tree by `shielded_send.rs` (the shielded-send amount/fee overflow guard). Its rustdoc was corrected by #4360 (`e0b8baa850`), which documents the `PlatformWalletError::InputSumOverflow` mapping — the stale no-producer comment this row used to track is gone | | 14 | `ErrorNoSelectableInputs` | | | 15 | `ErrorWalletAlreadyExists` | | -| 16 | `ErrorShieldedBroadcastFailed` | For a shielded spend that consumes notes, since #5810: only a transition refused before anything was sent (no address to send it to, or the SDK's own refusal), its notes released. An endpoint's verdict (CheckTx or execution, which no proof backs) and every transport failure after a dispatch, which note spends reported here before, now report 18, or 17 for an identity created from the pool. A shield into the pool still reports a verdict here | +| 16 | `ErrorShieldedBroadcastFailed` | Only a transition refused before anything was sent (no address to send it to, or the SDK's own refusal), its notes released. For a shielded spend that consumes notes, since #5810: an endpoint's verdict (CheckTx or execution, which no proof backs) and every transport failure after a dispatch, which note spends reported here before, now report 18, or 17 for an identity created from the pool. A shield from Platform addresses no longer reports an endpoint's refusal or verdict here either: that is 18 | | 17 | `ErrorShieldedBroadcastUnconfirmed` | | -| 18 | `ErrorShieldedSpendUnconfirmed` | Also, since #5810, what note spends (shielded transfers, unshields, withdrawals, identity top-ups and private document creations from the pool) reported as 16 before: an endpoint's verdict and any transport failure after a dispatch, as the transition may have been delivered. Also `ShieldedBroadcastMaybeDelivered`. The notes and the redrive record are kept; a host must not pay again with other notes | +| 18 | `ErrorShieldedSpendUnconfirmed` | Also, since #5810, what note spends (shielded transfers, unshields, withdrawals, identity top-ups and private document creations from the pool) reported as 16 before: an endpoint's verdict and any transport failure after a dispatch, as the transition may have been delivered. Also `ShieldedBroadcastMaybeDelivered`. The notes and the redrive record are kept, the record saved before the broadcast and the reservation restored from it after a restart; a host must not pay again with other notes. Also what a shield from Platform addresses returns once a dispatch may have reached a node and its result is not proved, an endpoint's refusal or consensus verdict included | | 19 | `ErrorShieldedNoRecordedAnchor` | | | 20 | `ErrorTransactionBroadcastUnconfirmed` | | -| 21 | `ErrorAddressNonceMismatch` | | +| 21 | `ErrorAddressNonceMismatch` | No longer returned by a shield from Platform addresses: an endpoint's nonce verdict on a dispatched shield is 18. Transfers and withdrawals from Platform addresses, and identity registrations and top-ups from them, still return it | | 22 | `ErrorCoreInsufficientFunds` | | | 23 | `ErrorAssetLockNotTracked` | | | 24 | `ErrorAssetLockAlreadyConsumed` | | @@ -109,7 +109,7 @@ These are shipped ABI. Do not renumber. | 39 | `ErrorInsufficientIdentityCredits` | Merged 2026-08-09 by **#4348** (`6373e00f0c`) | | 40 | `ErrorContestedNameNotTradable` | Merged 2026-08-09 by **#4348** (`6373e00f0c`) | | 41 | `ErrorShieldedInsufficientBalance` | Merged 2026-08-11 by **#4360** (`e0b8baa850`) | -| 42 | `ErrorMasternodeWithdrawalUnconfirmed` | Merged 2026-08-22 by **#4451** (masternode-credit claiming). **Took the number active #4356 had claimed** for `ErrorAssetLockInputConflict` — see the proposed table's 42 note; #4356 renumbers via the frontier | +| 42 | `ErrorMasternodeWithdrawalUnconfirmed` | Merged 2026-08-22 by **#4451** (masternode-credit claiming). **Took the number active #4356 had claimed** for `ErrorAssetLockInputConflict`; see the proposed table's 42 note. #4356 renumbers via the frontier. Returned once a dispatch may have reached a node and the result is not proved, an endpoint's refusal or consensus verdict included; only a withdrawal that never left the wallet keeps an ordinary, retryable code | | 46 | `ErrorMasternodeListUnavailable` | Merged 2026-08-24 by **#4465** (`8dd964277`). Initially minted as 43 (already held by active #4313's `ErrorShieldedInviteAlreadyClaimed` across all three layers) — collision flagged in review and renumbered to the then-frontier same day, Rust and Swift together | | 98 | `NotFound` | Sentinel — `Option` returned as an error | | 99 | `ErrorUnknown` | Sentinel — unmapped/flattened errors | diff --git a/packages/rs-platform-wallet-ffi/src/error.rs b/packages/rs-platform-wallet-ffi/src/error.rs index 197d4ebbf8c..3e9c2b88d6a 100644 --- a/packages/rs-platform-wallet-ffi/src/error.rs +++ b/packages/rs-platform-wallet-ffi/src/error.rs @@ -135,42 +135,51 @@ pub enum PlatformWalletFFIResultCode { /// result message for logging/detail. ErrorWalletAlreadyExists = 15, /// Maps `PlatformWalletError::ShieldedBroadcastFailed`. The shielded - /// transition (identity-create, unshield, transfer, or withdrawal) was - /// DEFINITIVELY not executed. For a shielded spend that consumes notes, it - /// never left the wallet: it was refused before anything was sent (no - /// address to send it to, or the SDK's own refusal). An endpoint's verdict - /// proves nothing for such a spend, as no proof backs it: that is - /// [`Self::ErrorShieldedSpendUnconfirmed`] ([`Self::ErrorShieldedBroadcastUnconfirmed`] - /// for an identity create), as is any broadcast that may have been - /// delivered. A shield into the pool also reports here a CheckTx - /// or execution verdict. Any note reservations were released and the + /// transition (a shield from Platform addresses, identity-create, + /// identity top-up, unshield, transfer, or withdrawal) was DEFINITIVELY + /// not executed: it never left the wallet, refused before anything was + /// sent (no address to send it to, or the SDK's own refusal). An + /// endpoint's refusal or verdict (CheckTx or execution) proves nothing, + /// as no proof backs it: that is [`Self::ErrorShieldedSpendUnconfirmed`] + /// ([`Self::ErrorShieldedBroadcastUnconfirmed`] for an identity create), + /// as is any broadcast that may have been delivered. Any note + /// reservations were released, with the spend's recovery record, and the /// caller is free to retry. /// For identity-create, the new identity does NOT exist and /// `out_identity_id` is left untouched (still zeroed). ErrorShieldedBroadcastFailed = 16, /// Maps `PlatformWalletError::ShieldedBroadcastUnconfirmed`. The broadcast - /// was ACCEPTED by the relay but the SDK could not confirm its execution - /// result (a transient result-proof fetch/verify failure, not a platform - /// rejection), and a direct fetch of the derived id also came back empty. - /// The identity may already exist on chain, so the caller must NOT treat + /// was accepted by the relay, or may have been delivered, but the SDK + /// could not confirm its execution result (a broadcast attempt that failed + /// in transport, an endpoint's refusal or verdict, a result-proof + /// fetch/verify failure, …), and a direct fetch of the derived id also + /// came back empty. The wallet keeps the notes reserved and the create's + /// recovery record, which it saved before the broadcast. The identity may + /// already exist on chain, so the caller must NOT treat /// it as unregistered or re-submit. UNLIKE every other error code, /// `out_identity_id` IS written (the 32-byte derived id) on this code so /// the caller can hold the slot and surface the pending identity. ErrorShieldedBroadcastUnconfirmed = 17, - /// Maps `PlatformWalletError::ShieldedSpendUnconfirmed` (unshield / - /// shielded transfer / shielded withdrawal / identity top-up / private - /// document create from the pool; an identity created from the pool - /// reports [`Self::ErrorShieldedBroadcastUnconfirmed`] (17) instead), and - /// `PlatformWalletError::ShieldedBroadcastMaybeDelivered`. The spend - /// transition was accepted by the relay, or may have been delivered, but - /// its execution result could not be confirmed (a broadcast attempt that - /// failed in transport, a DAPI wait timeout, a result-proof fetch/verify - /// failure, …). The spend may have executed on chain, so the wallet - /// intentionally KEEPS the notes reserved and its recovery record: the - /// next nullifier sync promotes them to spent if the spend landed, and the - /// redrive and anchor-prune passes release them once it provably never - /// can. The host must NOT auto-retry — a retry would select different - /// unreserved notes and could double-send if the original spend landed. + /// Maps `PlatformWalletError::ShieldedSpendUnconfirmed` (shield from + /// Platform addresses or from an identity / unshield / shielded transfer / + /// shielded withdrawal / identity top-up / private document create from + /// the pool; an identity created from the pool reports + /// [`Self::ErrorShieldedBroadcastUnconfirmed`] (17) instead), and + /// `PlatformWalletError::ShieldedBroadcastMaybeDelivered`. + /// The transition was accepted by the relay, or may have been delivered, + /// but its execution result could not be confirmed (a broadcast attempt + /// that failed in transport, an endpoint's refusal or consensus verdict, + /// a DAPI wait timeout, a result-proof fetch/verify failure, …). It may + /// have executed on chain, or may still execute. For a spend that consumes + /// notes the wallet intentionally KEEPS the notes reserved and its + /// recovery record, saved before the broadcast and restored after a + /// restart: the next nullifier sync promotes them to spent if the spend + /// landed, and the redrive and anchor-prune passes release them once it + /// provably never can. A shield from Platform addresses reserves nothing + /// and keeps no record: its activity row stays pending until the scan + /// sees its note. The host must NOT auto-retry: a retry would select + /// different unreserved notes, or sign a second shield with the inputs' + /// next nonces, and could double-send if the original landed. ErrorShieldedSpendUnconfirmed = 18, /// Maps `PlatformWalletError::ShieldedNoRecordedAnchor`. The wallet could /// not build the spend against any Platform-recorded anchor yet: its local @@ -194,15 +203,16 @@ pub enum PlatformWalletFFIResultCode { /// auto-retry. Shielded sibling: [`Self::ErrorShieldedSpendUnconfirmed`]. ErrorTransactionBroadcastUnconfirmed = 20, /// Maps `PlatformWalletError::AddressNonceMismatch`. Platform rejected an - /// address-funds transition (shield, or identity top-up-from-addresses) + /// address-funds transition (a transfer or withdrawal from Platform + /// addresses, or an identity registration or top-up from them) /// because the submitted address nonce raced Platform's expected next - /// value (a lagging DAPI replica stale read; consensus code 40603). Same - /// definitively-failed / notes-released / safe-to-retry contract as - /// [`Self::ErrorShieldedBroadcastFailed`] — the transition did NOT execute - /// and any note reservations were released (a shield reserves none) — but - /// as its OWN code so hosts can recognize this specific, self-healing + /// value (a lagging DAPI replica stale read; consensus code 40603). Its + /// OWN code so hosts can recognize this specific, self-healing /// failure and retry: the retry re-fetches the address nonce, resolving - /// the mismatch without host intervention. The submitted and Platform- + /// the mismatch without host intervention. A shield from Platform + /// addresses does not report it: an endpoint's nonce verdict on a shield + /// that was dispatched reads as [`Self::ErrorShieldedSpendUnconfirmed`], + /// as no proof backs it. The submitted and Platform- /// expected nonce values travel in the result `message` (the typed /// `Display`); they are not exposed as structured out-fields (that would /// require an ABI-breaking change to `PlatformWalletFFIResult`). @@ -439,13 +449,17 @@ pub enum PlatformWalletFFIResultCode { ErrorShieldedInsufficientBalance = 41, /// Maps `PlatformWalletError::MasternodeWithdrawalUnconfirmed`. A /// masternode (evonode) identity credit withdrawal was broadcast and - /// accepted, but its execution result could not be confirmed — it may - /// already have executed, and the identity nonce was consumed for it, so + /// accepted, or may have been delivered, but its execution result could + /// not be confirmed (a broadcast attempt that failed in transport, an + /// endpoint's refusal or consensus verdict, a wait timeout, …). It may + /// already have executed, or may still execute, and the identity nonce + /// was taken for it, so /// a blind retry could submit a SECOND withdrawal. The host must NOT /// retry; it must re-read the identity's claimable balance (and the - /// payout) and let the user decide from the reconciled state. Definitive - /// rejections (consensus errors, transport verdicts) keep their ordinary - /// codes and stay retryable. Siblings: [`Self::ErrorShieldedSpendUnconfirmed`], + /// payout) and let the user decide from the reconciled state. Only a + /// failure before the broadcast, or a broadcast refused before anything + /// was sent, keeps its ordinary code and stays retryable. Siblings: + /// [`Self::ErrorShieldedSpendUnconfirmed`], /// [`Self::ErrorTransactionBroadcastUnconfirmed`]. ErrorMasternodeWithdrawalUnconfirmed = 42, /// The deterministic masternode list isn't available yet (SPV not diff --git a/packages/rs-platform-wallet-ffi/src/masternode_withdrawal.rs b/packages/rs-platform-wallet-ffi/src/masternode_withdrawal.rs index 4b83446381d..f8e10ecc16f 100644 --- a/packages/rs-platform-wallet-ffi/src/masternode_withdrawal.rs +++ b/packages/rs-platform-wallet-ffi/src/masternode_withdrawal.rs @@ -177,12 +177,13 @@ pub unsafe extern "C" fn platform_wallet_manager_masternode_withdrawal_keys( /// invalid. The resolver is invoked exactly once, at signing time; the /// handle-storage guard is not held across it. /// -/// Outcome codes after the transition leaves the wallet: a definitive -/// rejection returns an ordinary error (retryable); an AMBIGUOUS outcome — -/// broadcast accepted (or its ACK lost) and the result wait failed — returns -/// `ErrorMasternodeWithdrawalUnconfirmed` (42): the claim may have executed -/// and the identity nonce was consumed, so the host must NOT retry until it -/// has re-read the claimable balance. +/// Outcome codes of the broadcast: a transition that never left the wallet +/// (refused before anything was sent) returns an ordinary error (retryable). +/// Once a dispatch may have reached a node, anything short of a proved +/// result, an endpoint's refusal or consensus verdict included, returns +/// `ErrorMasternodeWithdrawalUnconfirmed` (42): the claim may have executed, +/// or may still execute, and the identity nonce was taken for it, so the +/// host must NOT retry until it has re-read the claimable balance. /// /// # Safety /// `wallet_id` / `pro_tx_hash` must point at 32 readable bytes; diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index c67edeafcdc..98aa8046d22 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -602,12 +602,13 @@ pub(crate) fn map_spend_result( ) -> PlatformWalletFFIResult { match result { Ok(()) => PlatformWalletFFIResult::ok(), - // Ambiguous: the broadcast was accepted but its execution result - // couldn't be confirmed — the host must NOT re-submit. For the - // spend-based operations the notes stay reserved wallet-side; a - // shield reserves nothing. Either way the next sync (or an app - // restart) reconciles the outcome; the typed Display already - // carries the operation name and guidance. + // Outcome not known: a dispatch may have reached a node and the + // execution result couldn't be confirmed, so the host must NOT + // re-submit. For the spend-based operations the notes stay reserved + // wallet-side, with the recovery record saved before the broadcast; + // a shield from Platform addresses reserves nothing. Either way the + // next sync reconciles a transition that landed; the typed Display + // already carries the operation name and guidance. // A broadcast that may have been delivered reads the same: it may // still execute, so its notes and recovery record stay, and a host // must not pay again. @@ -654,18 +655,19 @@ pub(crate) fn map_spend_result( PlatformWalletFFIResultCode::ErrorShieldedNoRecordedAnchor, format!("Wallet is still syncing to a confirmed state — try again shortly. ({e})"), ), - // Definitive failure: the transition never left the wallet (for a note - // spend, refused before anything was sent); the notes were released - // and the host may retry. + // Definitive failure: the transition never left the wallet (refused + // before anything was sent); a spend's notes were released and the + // host may retry. Err(e @ PlatformWalletError::ShieldedBroadcastFailed(_)) => PlatformWalletFFIResult::err( PlatformWalletFFIResultCode::ErrorShieldedBroadcastFailed, format!("{operation} failed: {e}"), ), - // Definitively failed on an address-nonce race (a shield spends platform - // address funds; a shield reserves no notes). Its own code carries the - // safe-to-retry contract AND lets the host recognize the self-healing - // nonce mismatch — a plain retry re-fetches the nonce. Without this arm - // it would regress to the generic `ErrorWalletOperation` below. + // An address-nonce race keeps its own code, so the host can recognize + // the self-healing nonce mismatch: a plain retry re-fetches the nonce. + // No operation mapped here reports it today: a shield from Platform + // addresses reads an endpoint's nonce verdict on a dispatched shield + // as unconfirmed, above. The arm keeps the code from regressing to the + // generic `ErrorWalletOperation` below if one does. Err(e @ PlatformWalletError::AddressNonceMismatch { .. }) => PlatformWalletFFIResult::err( PlatformWalletFFIResultCode::ErrorAddressNonceMismatch, format!("{operation} failed: {e}"), @@ -769,7 +771,7 @@ const SPEND_PANIC_GUIDANCE: &str = "The spend may or may not have been broadcast /// a definitive failure code: a panic can strike after the notes were reserved and even after the /// transition was broadcast, so the outcome is genuinely ambiguous. That code's contract is /// exactly the conservative one this needs — the host must not auto-retry, the reservation stays -/// in place, and the next nullifier sync (or an app restart) reconciles whether the spend landed. +/// in place, and the next nullifier sync reconciles whether the spend landed. fn catch_spend_panic( operation: &str, body: impl FnOnce() -> PlatformWalletFFIResult, diff --git a/packages/rs-platform-wallet/Cargo.toml b/packages/rs-platform-wallet/Cargo.toml index 7557d6db3ae..4dbe5e97c00 100644 --- a/packages/rs-platform-wallet/Cargo.toml +++ b/packages/rs-platform-wallet/Cargo.toml @@ -114,8 +114,9 @@ static_assertions = "1.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } # `test-util` brings `tokio::time::pause` / `tokio::test(start_paused = true)` # so time-driven manager, startup and SPV runtime logic can be tested -# deterministically without sleeping wall-clock seconds. -tokio = { version = "1", features = ["sync", "rt", "time", "macros", "test-util"] } +# deterministically without sleeping wall-clock seconds. `net` gives the +# broadcast tests a loopback port they hold bound and unlistened. +tokio = { version = "1", features = ["sync", "rt", "time", "macros", "test-util", "net"] } # Re-enable the SDK with mocks feature for test-only mock builders; # the non-test build keeps the leaner default-feature SDK above. dash-sdk = { path = "../rs-sdk", default-features = false, features = ["dashpay-contract", "dpns-contract", "wallet", "mocks"] } diff --git a/packages/rs-platform-wallet/src/broadcast_outcome.rs b/packages/rs-platform-wallet/src/broadcast_outcome.rs index bcb54c1983e..e06b22214cb 100644 --- a/packages/rs-platform-wallet/src/broadcast_outcome.rs +++ b/packages/rs-platform-wallet/src/broadcast_outcome.rs @@ -1,14 +1,17 @@ //! Classifying the outcome of a state-transition broadcast / result wait. //! -//! Shared by every Platform money-moving path that must keep "definitely -//! rejected, safe to retry" apart from "ambiguous, may have executed, do -//! not retry". Shielded spends that consume notes broadcast through +//! Shared by every Platform money-moving path that must keep "never left the +//! wallet, safe to retry" apart from "may have reached a node, may still +//! execute, do not retry". Shielded spends that consume notes, shields from +//! Platform addresses and masternode credit withdrawals broadcast through //! [`broadcast_tracking_delivery`], which keeps every dispatch's outcome so an //! earlier dispatch that may have been delivered is never hidden by a later -//! refusal; shields into the pool and masternode credit withdrawals classify -//! the SDK's final error with [`broadcast_definitely_failed`]. The shapes are -//! SDK-transport facts, not operation-specific, so they live here rather than -//! behind the `shielded` feature. +//! refusal: only a refusal before anything was sent reads as failed. The +//! shield from an identity keeps the SDK's own broadcast and reads its final +//! error with [`broadcast_was_refused`], which is no proof and only decides +//! whether it waits for a result: it reports unconfirmed either way. The +//! shapes are SDK-transport facts, not operation-specific, so they live here +//! rather than behind the `shielded` feature. /// Whether an SDK error carries Platform's own consensus verdict on the /// transition. Two shapes qualify: @@ -41,34 +44,37 @@ pub(crate) fn carries_consensus_rejection(err: &dash_sdk::Error) -> bool { } } -/// Whether a failed `broadcast()` call DEFINITIVELY left the transition -/// out of every mempool, so any note reservations may be released and the -/// caller may rebuild and retry: +/// Whether the final error of a failed `broadcast()` call reads as a +/// refusal of the transition, rather than as a call that got no answer: /// /// - a consensus verdict ([`carries_consensus_rejection`]): CheckTx /// evaluated the transition and refused it; /// - a gRPC response whose status code is a server-side rejection or a -/// connection-establishment failure. `Unavailable` is the common shape -/// of a connect-refused/offline attempt — classifying it as definitive -/// keeps the no-network failure's notes immediately re-spendable -/// instead of stranding them until the next restart — and rejection -/// codes (`InvalidArgument`, `ResourceExhausted` = mempool full, …) are -/// verdicts that the tx was refused admission; +/// connection-establishment failure: `Unavailable` is the common shape +/// of a connect-refused/offline attempt, and rejection codes +/// (`InvalidArgument`, `ResourceExhausted` = mempool full, …) say the +/// transition was refused admission; /// - no usable DAPI addresses at all (nothing was ever sent). /// -/// `Unavailable` is NOT an absolute never-delivered guarantee: HTTP/2 -/// stream resets after the request bytes left can surface the same code, -/// and the dapi-client's cross-address retry only retains the LAST +/// This is NOT proof that the transition was left out of every mempool, +/// and it never authorizes a retry, or a release of what the transition +/// spends. An endpoint's answer is unauthenticated, and one that kept or +/// forwarded the signed transition can answer with any verdict. HTTP/2 +/// stream resets after the request bytes left can surface `Unavailable` +/// too, and the dapi-client's cross-address retry only retains the LAST /// transport error, so an earlier-attempt delivery can hide behind a -/// later attempt's final error, whatever its code. That is why shielded -/// spends do not use this classification but [`broadcast_tracking_delivery`], -/// which reports such a spend unconfirmed: a spend reported failed while it -/// may still execute could be paid again with other notes. The callers left -/// here are shields into the pool, which move funds to the wallet's own -/// notes, and masternode credit withdrawals. +/// later attempt's final error, whatever its code. A transition reported +/// failed while it may still execute invites a second one, so every path +/// whose retry signs a new transition classifies with +/// [`broadcast_tracking_delivery`] instead: shielded spends, shields from +/// Platform addresses (to the wallet's own notes or to a recipient's) and +/// masternode credit withdrawals. The one caller left here is the shield +/// from an identity, which holds a durable guard on the exact signed +/// transition: a refusal only makes it skip the result wait for a proven +/// read of the identity nonce, and it reports unconfirmed either way. /// -/// Everything else leaves the outcome unknown and the caller must fall -/// through to the result wait instead of failing: `AlreadyExists` proves +/// Everything else reads as no answer, and the caller falls through to the +/// result wait: `AlreadyExists` proves /// the tx IS in the mempool or on chain (a lost-ACK attempt was re-sent /// by the dapi-client retry and hit tenderdash's dedupe), and /// timeout/cancellation/no-response shapes (`TimeoutReached`, @@ -76,7 +82,8 @@ pub(crate) fn carries_consensus_rejection(err: &dash_sdk::Error) -> bool { /// `Internal`/`Unknown`/`Aborted`/`DataLoss`, which DAPI also uses for /// its own tenderdash-side failures that can postdate delivery) allow /// the request to have outlived its lost ACK. -pub(crate) fn broadcast_definitely_failed(e: &dash_sdk::Error) -> bool { +#[cfg(feature = "shielded")] +pub(crate) fn broadcast_was_refused(e: &dash_sdk::Error) -> bool { use dash_sdk::dapi_client::transport::TransportError; use dash_sdk::dapi_client::DapiClientError; use dash_sdk::dapi_grpc::tonic::Code; @@ -104,14 +111,13 @@ pub(crate) fn broadcast_definitely_failed(e: &dash_sdk::Error) -> bool { dash_sdk::Error::DapiClientError(DapiClientError::NoAvailableAddressesToRetry(t)) => { status_is_verdict(t) } - dash_sdk::Error::NoAvailableAddressesToRetry(inner) => broadcast_definitely_failed(inner), + dash_sdk::Error::NoAvailableAddressesToRetry(inner) => broadcast_was_refused(inner), _ => false, } } -/// What the dispatches of one shielded spend's broadcast proved about its +/// What the dispatches of one transition's broadcast proved about its /// delivery ([`broadcast_tracking_delivery`]). -#[cfg(feature = "shielded")] #[derive(Debug)] pub(crate) enum BroadcastDelivery { /// A node admitted the transition, or already held it (`AlreadyExists`). @@ -121,7 +127,8 @@ pub(crate) enum BroadcastDelivery { /// whatever it answered (a consensus verdict included, which no proof /// or quorum signature backs), or failed in a way that allows delivery. /// It may execute, so the caller waits for its result, and an - /// unconfirmed outcome keeps the notes reserved. + /// unconfirmed outcome keeps what the transition spends held (a shielded + /// spend's notes stay reserved). MaybeDelivered(dash_sdk::Error), /// The transition never left the wallet: it was refused before its first /// dispatch was sent, there being no address to send it to or the SDK @@ -133,7 +140,6 @@ pub(crate) enum BroadcastDelivery { /// How many single dispatches [`broadcast_tracking_delivery`] makes at most /// on `sdk`: its configured overall budget, one dispatch and its effective /// retries, so a client configured with no retries dispatches once. -#[cfg(feature = "shielded")] pub(crate) fn spend_broadcast_dispatches(sdk: &dash_sdk::Sdk) -> usize { sdk.query_settings() .request_settings @@ -142,13 +148,14 @@ pub(crate) fn spend_broadcast_dispatches(sdk: &dash_sdk::Sdk) -> usize { .saturating_add(1) } -/// Broadcast a shielded spend `state_transition` in single dispatches (no +/// Broadcast `state_transition` (a shielded spend, a shield from Platform +/// addresses, a masternode credit withdrawal) in single dispatches (no /// SDK retry inside a dispatch), at most the SDK's configured budget /// ([`spend_broadcast_dispatches`]), keeping what every dispatch proved: the /// SDK's own retry loop returns only its last error, which cannot show that /// an earlier attempt was delivered with its response lost. Centralizing that /// evidence in the SDK is dashpay/platform#5556; what it means for a payment's -/// notes, journal and contact stays here. +/// notes, journal and contact stays with its caller. /// /// Any dispatch that reached an endpoint, or failed in a way that allows it /// (every transport error, whatever its gRPC code, a timeout, a cause-less @@ -157,7 +164,17 @@ pub(crate) fn spend_broadcast_dispatches(sdk: &dash_sdk::Sdk) -> usize { /// endpoint's answer is unauthenticated, and one that kept or forwarded the /// signed transition can answer with any verdict. Only a refusal before /// anything was sent is [`BroadcastDelivery::NeverDelivered`]. -#[cfg(feature = "shielded")] +/// +/// A verdict ends the dispatches, with one exception the SDK's own broadcast +/// makes too +/// ([`is_address_nonce_ahead`](dash_sdk::platform::transition::broadcast::is_address_nonce_ahead)): +/// a node that reads an input address's nonce as ahead of its own state is +/// behind the node the nonce was read from, so the same signed bytes go to +/// the next dispatch's node. A single dispatch gets none of the SDK's +/// failover, and it does not step off the answering node as the SDK's loop +/// does, so a later dispatch can reach that node again and spend one of the +/// budget's dispatches on the same answer. The broadcast is maybe delivered +/// either way. pub(crate) async fn broadcast_tracking_delivery( sdk: &dash_sdk::Sdk, state_transition: &dpp::state_transition::StateTransition, @@ -173,22 +190,26 @@ pub(crate) async fn broadcast_tracking_delivery( }, ..PutSettings::default() }; - track_delivery(spend_broadcast_dispatches(sdk), || { + track_delivery(state_transition, spend_broadcast_dispatches(sdk), || { state_transition.broadcast(sdk, Some(single_dispatch)) }) .await } -/// The classification [`broadcast_tracking_delivery`] makes, over the -/// outcomes `dispatch` returns, one call per single dispatch, at most -/// `dispatches` of them. -#[cfg(feature = "shielded")] -async fn track_delivery(dispatches: usize, mut dispatch: F) -> BroadcastDelivery +/// The classification [`broadcast_tracking_delivery`] makes of +/// `state_transition`'s broadcast, over the outcomes `dispatch` returns, one +/// call per single dispatch, at most `dispatches` of them. +async fn track_delivery( + state_transition: &dpp::state_transition::StateTransition, + dispatches: usize, + mut dispatch: F, +) -> BroadcastDelivery where F: FnMut() -> Fut, Fut: std::future::Future>, { use dash_sdk::dapi_client::DapiClientError; + use dash_sdk::platform::transition::broadcast::is_address_nonce_ahead; let mut maybe_delivered: Option = None; for _ in 0..dispatches.max(1) { @@ -216,8 +237,11 @@ where None => BroadcastDelivery::NeverDelivered(error), }; } - // An endpoint's verdict ends the dispatches, and proves nothing. - if carries_consensus_rejection(&error) { + // An endpoint's verdict ends the dispatches, and proves nothing. The + // verdict of a node that is behind does not end them: the same bytes + // go to the next dispatch's node. + if carries_consensus_rejection(&error) && !is_address_nonce_ahead(state_transition, &error) + { return BroadcastDelivery::MaybeDelivered(error); } maybe_delivered = Some(error); @@ -231,12 +255,105 @@ where } } -#[cfg(all(test, feature = "shielded"))] +/// Network SDKs for the tests of the flows that broadcast through +/// [`broadcast_tracking_delivery`]. +#[cfg(test)] +pub(crate) mod test_sdks { + use dash_sdk::dpp::dashcore::Network; + use dash_sdk::dpp::prelude::CoreBlockHeight; + use dash_sdk::error::ContextProviderError; + use dash_sdk::platform::ContextProvider; + use dash_sdk::sdk::AddressList; + use dpp::data_contract::{DataContract, TokenConfiguration}; + use dpp::prelude::Identifier; + use dpp::version::PlatformVersion; + use std::str::FromStr; + use std::sync::Arc; + + /// A context provider that knows no contract and no quorum key: the + /// tests' requests fail before a proof is verified. + struct NoKeys; + + impl ContextProvider for NoKeys { + fn get_data_contract( + &self, + _id: &Identifier, + _platform_version: &PlatformVersion, + ) -> Result>, ContextProviderError> { + Ok(None) + } + + fn get_token_configuration( + &self, + _token_id: &Identifier, + ) -> Result, ContextProviderError> { + Ok(None) + } + + fn get_quorum_public_key( + &self, + _quorum_type: u32, + _quorum_hash: [u8; 32], + _core_chain_locked_height: u32, + ) -> Result<[u8; 48], ContextProviderError> { + Err(ContextProviderError::Generic("no quorum keys".to_string())) + } + + fn get_platform_activation_height(&self) -> Result { + Ok(1) + } + } + + fn sdk(addresses: AddressList) -> dash_sdk::Sdk { + dash_sdk::SdkBuilder::new(addresses) + .with_network(Network::Testnet) + .with_version(PlatformVersion::latest()) + .with_context_provider(NoKeys) + .build() + .expect("a network SDK") + } + + /// A network SDK with no address to send to: every dispatch is refused + /// before anything is sent. + pub(crate) fn sdk_without_addresses() -> dash_sdk::Sdk { + sdk(AddressList::new()) + } + + /// A loopback port that refuses every connection for as long as this is + /// held: bound, so nothing else can take it, and never listened on. + pub(crate) struct RefusingPort { + _bound: tokio::net::TcpSocket, + } + + /// A network SDK whose only node refuses the connection, and the port + /// that does so while it is held: every dispatch fails in transport, the + /// way an offline attempt does. + pub(crate) fn sdk_refusing_connections() -> (dash_sdk::Sdk, RefusingPort) { + let bound = tokio::net::TcpSocket::new_v4().expect("a socket"); + bound + .bind(std::net::SocketAddr::from(([127, 0, 0, 1], 0))) + .expect("a loopback port"); + let address = bound.local_addr().expect("its address"); + ( + sdk(AddressList::from_str(&format!("http://{address}")).expect("an address")), + RefusingPort { _bound: bound }, + ) + } +} + +#[cfg(test)] mod tests { use super::*; use dash_sdk::dapi_client::transport::TransportError; use dash_sdk::dapi_client::DapiClientError; use dash_sdk::dapi_grpc::tonic::{Code, Status}; + use dpp::address_funds::PlatformAddress; + use dpp::consensus::state::address_funds::AddressInvalidNonceError; + use dpp::consensus::state::state_error::StateError; + use dpp::state_transition::address_funds_transfer_transition::v0::AddressFundsTransferTransitionV0; + use dpp::state_transition::identity_credit_withdrawal_transition::v1::IdentityCreditWithdrawalTransitionV1; + use dpp::state_transition::StateTransition; + use std::collections::BTreeMap; use std::sync::Mutex; /// Another error of the same shape as `error`, which is not `Clone`. @@ -289,12 +406,21 @@ mod tests { } /// What [`track_delivery`] makes of dispatches whose outcome `outcome` - /// gives by dispatch number, from 0, and how many dispatches it made. + /// gives by dispatch number, from 0, and how many dispatches it made: + /// of a transition with no address input, which no node can be behind on. async fn tracked( outcome: impl Fn(usize) -> Result<(), dash_sdk::Error>, + ) -> (BroadcastDelivery, usize) { + tracked_for(&withdrawal(), outcome).await + } + + /// [`tracked`], of `transition`. + async fn tracked_for( + transition: &StateTransition, + outcome: impl Fn(usize) -> Result<(), dash_sdk::Error>, ) -> (BroadcastDelivery, usize) { let dispatched = Mutex::new(0usize); - let delivery = track_delivery(BUDGET, || { + let delivery = track_delivery(transition, BUDGET, || { let mut count = dispatched.lock().expect("count"); let result = outcome(*count); *count += 1; @@ -305,6 +431,41 @@ mod tests { (delivery, dispatched) } + /// An identity credit withdrawal, which is broadcast in every build and + /// spends from no Platform address. + fn withdrawal() -> StateTransition { + IdentityCreditWithdrawalTransitionV1 { + amount: 1_000_000, + nonce: 1, + ..Default::default() + } + .into() + } + + /// The Platform address [`address_spend`] spends from, and the nonce it + /// signed. + const SPENT_FROM: PlatformAddress = PlatformAddress::P2pkh([7; 20]); + const SIGNED_NONCE: u32 = 5; + + /// A transition that spends from a Platform address, as a shield does. + fn address_spend() -> StateTransition { + AddressFundsTransferTransitionV0 { + inputs: BTreeMap::from([(SPENT_FROM, (SIGNED_NONCE, 2_000_000))]), + ..Default::default() + } + .into() + } + + /// A node's verdict that `SPENT_FROM` was spent with `SIGNED_NONCE` where + /// the node expects `expected`. + fn nonce_verdict(expected: u32) -> dash_sdk::Error { + dash_sdk::Error::Protocol(dpp::ProtocolError::ConsensusError(Box::new( + dpp::consensus::ConsensusError::StateError(StateError::AddressInvalidNonceError( + AddressInvalidNonceError::new(SPENT_FROM, SIGNED_NONCE, expected), + )), + ))) + } + /// The dispatch budget the tests run with. const BUDGET: usize = 6; @@ -369,10 +530,14 @@ mod tests { assert_eq!(spend_broadcast_dispatches(&three_retries), 4); let dispatched = Mutex::new(0usize); - let delivery = track_delivery(spend_broadcast_dispatches(&no_retries), || { - *dispatched.lock().expect("count") += 1; - std::future::ready(Err(grpc(Code::Unavailable))) - }) + let delivery = track_delivery( + &withdrawal(), + spend_broadcast_dispatches(&no_retries), + || { + *dispatched.lock().expect("count") += 1; + std::future::ready(Err(grpc(Code::Unavailable))) + }, + ) .await; assert!(matches!(delivery, BroadcastDelivery::MaybeDelivered(_))); assert_eq!(*dispatched.lock().expect("count"), 1); @@ -454,6 +619,99 @@ mod tests { } } + /// The broadcast of a signed transition through a network SDK: with no + /// address to send it to it never left, and a node that refuses the + /// connection leaves it maybe delivered, as a transport failure cannot + /// show nothing was sent. Here an identity credit withdrawal, which is + /// broadcast in every build. + #[tokio::test] + async fn should_track_the_delivery_of_a_broadcast_through_a_network_sdk() { + let transition = withdrawal(); + + let delivery = + broadcast_tracking_delivery(&test_sdks::sdk_without_addresses(), &transition).await; + assert!( + matches!(delivery, BroadcastDelivery::NeverDelivered(_)), + "{delivery:?}" + ); + let (refusing, _port) = test_sdks::sdk_refusing_connections(); + let delivery = broadcast_tracking_delivery(&refusing, &transition).await; + assert!( + matches!(delivery, BroadcastDelivery::MaybeDelivered(_)), + "{delivery:?}" + ); + } + + /// A node that reads an input address's nonce as ahead of its own state + /// is behind the node the nonce was read from: the same signed + /// transition goes to the next dispatch's node, as the SDK's own + /// broadcast sends it, and a node that admits it ends the dispatches. + #[tokio::test] + async fn should_send_a_transition_a_node_is_behind_on_to_another_node() { + let behind = SIGNED_NONCE - 1; + let (delivery, dispatched) = tracked_for(&address_spend(), |dispatch| match dispatch { + 0 | 1 => Err(nonce_verdict(behind)), + _ => Ok(()), + }) + .await; + assert!( + matches!(delivery, BroadcastDelivery::Admitted), + "{delivery:?}" + ); + assert_eq!(dispatched, 3); + + // Every node behind: the budget ends the dispatches, and the + // transition stays maybe delivered, as every node that answered holds + // its bytes. + let (delivery, dispatched) = + tracked_for(&address_spend(), |_| Err(nonce_verdict(behind))).await; + assert!( + matches!(delivery, BroadcastDelivery::MaybeDelivered(_)), + "{delivery:?}" + ); + assert_eq!(dispatched, BUDGET); + } + + /// Every other verdict ends the dispatches: a nonce the node has already + /// passed, a nonce of an address the transition does not spend from, and + /// the same verdict on a transition that spends from no address. + #[tokio::test] + async fn should_end_the_dispatches_on_a_verdict_no_other_node_changes() { + let (delivery, dispatched) = + tracked_for(&address_spend(), |_| Err(nonce_verdict(SIGNED_NONCE + 1))).await; + assert!( + matches!(delivery, BroadcastDelivery::MaybeDelivered(_)), + "a nonce the node has passed: {delivery:?}" + ); + assert_eq!(dispatched, 1); + + let another_address = || { + dash_sdk::Error::Protocol(dpp::ProtocolError::ConsensusError(Box::new( + dpp::consensus::ConsensusError::StateError(StateError::AddressInvalidNonceError( + AddressInvalidNonceError::new( + PlatformAddress::P2pkh([8; 20]), + SIGNED_NONCE, + SIGNED_NONCE - 1, + ), + )), + ))) + }; + let (delivery, dispatched) = + tracked_for(&address_spend(), |_| Err(another_address())).await; + assert!( + matches!(delivery, BroadcastDelivery::MaybeDelivered(_)), + "another address: {delivery:?}" + ); + assert_eq!(dispatched, 1); + + let (delivery, dispatched) = tracked(|_| Err(nonce_verdict(SIGNED_NONCE - 1))).await; + assert!( + matches!(delivery, BroadcastDelivery::MaybeDelivered(_)), + "no address input: {delivery:?}" + ); + assert_eq!(dispatched, 1); + } + /// A dispatch a node admitted, or already holds, is admitted, after any /// number of failed ones. #[tokio::test] diff --git a/packages/rs-platform-wallet/src/error.rs b/packages/rs-platform-wallet/src/error.rs index 36625e4eb83..7da9bac682f 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -1052,6 +1052,13 @@ pub enum PlatformWalletError { #[error("Shielded build error: {0}")] ShieldedBuildError(String), + /// A shielded transition (a shield from Platform addresses, or a spend + /// that consumes notes) never left the wallet: its broadcast was refused + /// before anything was sent. It can never execute, so a spend's notes are + /// released, its saved record retired, and the caller may retry. Once a + /// dispatch may have reached a node the outcome is + /// [`Self::ShieldedSpendUnconfirmed`] (or + /// [`Self::ShieldedBroadcastUnconfirmed`]) instead. #[error("Shielded broadcast failed: {0}")] ShieldedBroadcastFailed(String), @@ -1067,11 +1074,13 @@ pub enum PlatformWalletError { #[error("Shielded broadcast failed, but may have been delivered: {0}")] ShieldedBroadcastMaybeDelivered(String), - /// The shielded identity-create transition was **broadcast and accepted by the relay**, but the - /// SDK could not confirm its execution result (the result-proof fetch/verify failed — e.g. a - /// transient DAPI/proof error, not a platform rejection). The identity with `identity_id` may + /// The shielded identity-create transition was broadcast and accepted by the relay, or may + /// have been delivered, but the SDK could not confirm its execution result (a broadcast + /// attempt that failed in transport, an endpoint's refusal or verdict, a result-proof + /// fetch/verify failure). The identity with `identity_id` may /// already exist on chain, so the caller must NOT treat it as unregistered: the slot stays held - /// against re-submission and the spent notes' reservations are left in place (the next nullifier + /// against re-submission and the spent notes' reservations are left in place, with the + /// recovery record saved before the broadcast (the next nullifier /// sync reconciles them). `reason` carries the underlying SDK error for diagnostics. #[error( "Shielded broadcast succeeded but its execution result could not be confirmed; \ @@ -1099,16 +1108,19 @@ pub enum PlatformWalletError { #[error("shielded account {account_index} is required for payment recovery: {reason}; restore its original viewing keys or inspect the unresolved payment before choosing recovery")] ShieldedRecoveryKeysRequired { account_index: u32, reason: String }, - /// A shielded transition (`operation` is `"shield"`, `"unshield"`, `"transfer"` or - /// `"withdraw"`) was **broadcast and accepted by the relay**, but the SDK could not confirm - /// its execution result (the result-proof fetch/verify failed — e.g. a transient DAPI/proof - /// error or timeout, not a platform rejection). The operation may already be executed on - /// chain, so re-submitting risks a double-execution. For the spend-based operations the spent + /// A shielded transition (`operation` names it: `"shield"`, `"unshield"`, `"transfer"`, + /// `"withdraw"`, an identity top-up, a private document create) was broadcast and accepted + /// by the relay, or may have been delivered, but the SDK could not confirm its execution + /// result (a broadcast attempt that failed in transport, an endpoint's refusal or consensus + /// verdict, which no proof backs, a result-proof fetch/verify failure or a timeout). The + /// operation may already be executed on chain, or may still execute, so re-submitting risks + /// a double-execution. For the spend-based operations the spent /// notes' reservations are intentionally left in place rather than released — releasing them - /// would invite re-selecting notes whose nullifiers may already be consumed; a shield spends - /// no notes, so it has nothing reserved. The next sync (or an app restart, since reservations - /// are in-memory only) reconciles the outcome either way. `reason` carries the underlying SDK - /// error for diagnostics. + /// would invite re-selecting notes whose nullifiers may already be consumed. Their recovery + /// record is saved before the broadcast, so a restart restores the reservations from it, and + /// the next sync reconciles the outcome. A shield from Platform addresses spends no notes and + /// keeps no record: its activity row stays pending until the scan sees its note. `reason` + /// carries the underlying SDK error for diagnostics. /// /// The identity-create sibling is [`Self::ShieldedBroadcastUnconfirmed`], which additionally /// carries the derived identity id so the caller can hold the registration slot. @@ -1122,11 +1134,13 @@ pub enum PlatformWalletError { reason: String, }, - /// A masternode (evonode) identity credit withdrawal was **broadcast and - /// accepted**, but its execution result could not be confirmed (the - /// result-proof fetch/verify failed — transient DAPI/proof error or - /// timeout, not a Platform rejection). The claim may already have - /// executed, and the SDK's identity-nonce cache was bumped for it, so + /// A masternode (evonode) identity credit withdrawal was broadcast and + /// accepted, or may have been delivered, but its execution result could + /// not be confirmed (a broadcast attempt that failed in transport, an + /// endpoint's refusal or consensus verdict, which no proof backs, a + /// result-proof fetch/verify failure or a timeout). The claim may already + /// have executed, or may still execute, and the SDK's identity-nonce + /// cache was bumped for it, so /// re-submitting could execute a SECOND withdrawal with the next nonce. /// Callers must NOT retry until they have re-read the identity's /// claimable balance (and the payout) and reconciled the outcome. @@ -1348,7 +1362,7 @@ pub fn is_instant_lock_timeout(error: &PlatformWalletError) -> bool { /// Matches the three `dash_sdk::Error` shapes that can carry a consensus /// verdict — `StateTransitionBroadcastError` (wait-stream), `Protocol( /// ConsensusError)` (CheckTx), and a `NoAvailableAddressesToRetry` envelope it -/// recurses into — staying in lockstep with `broadcast_definitely_failed`. +/// recurses into, staying in lockstep with `carries_consensus_rejection`. pub fn as_address_invalid_nonce(error: &dash_sdk::Error) -> Option<&AddressInvalidNonceError> { use dpp::consensus::state::state_error::StateError; @@ -1858,7 +1872,7 @@ mod address_nonce_tests { fn extracts_nonce_error_wrapped_in_no_available_addresses_to_retry() { // The dapi-client wraps the last rejection in `NoAvailableAddressesToRetry` // when every address is exhausted mid-retry; the extractor must recurse - // into it (lockstep with `broadcast_definitely_failed`). + // into it (lockstep with `carries_consensus_rejection`). let inner = Box::new(protocol_shape(9, 10)); let wrapped = dash_sdk::Error::NoAvailableAddressesToRetry(inner); let got = as_address_invalid_nonce(&wrapped).expect("must unwrap the retry envelope"); diff --git a/packages/rs-platform-wallet/src/wallet/masternode_withdrawal.rs b/packages/rs-platform-wallet/src/wallet/masternode_withdrawal.rs index 32bf9206254..bf96ebddfee 100644 --- a/packages/rs-platform-wallet/src/wallet/masternode_withdrawal.rs +++ b/packages/rs-platform-wallet/src/wallet/masternode_withdrawal.rs @@ -54,9 +54,10 @@ use dpp::state_transition::identity_credit_withdrawal_transition::{ IdentityCreditWithdrawalTransition, MIN_CORE_FEE_PER_BYTE, }; use dpp::state_transition::proof_result::StateTransitionProofResult; +use dpp::state_transition::StateTransition; use dpp::withdrawal::Pooling; -use crate::broadcast_outcome::{broadcast_definitely_failed, carries_consensus_rejection}; +use crate::broadcast_outcome::{broadcast_tracking_delivery, BroadcastDelivery}; use crate::error::{PlatformWalletError, SIGNER_KEY_UNAVAILABLE_PREFIX}; use crate::wallet::core::is_signable_funding_account; use crate::wallet::identity::network::{ @@ -288,14 +289,16 @@ impl PlatformWallet { /// - the identity is missing, or doesn't carry the expected /// `OWNER` / `TRANSFER` key for the wallet's hash160. /// - /// Outcomes after the transition leaves this wallet are kept distinct: - /// a definitive rejection (consensus error, or a transport verdict that - /// rules out delivery) is an ordinary error and may be retried; anything - /// ambiguous — broadcast accepted (or its ACK lost) and the result wait - /// failed — is [`PlatformWalletError::MasternodeWithdrawalUnconfirmed`] - /// and MUST NOT be retried until the claimable balance is re-read: the - /// identity nonce was already consumed for this attempt, so a blind retry - /// would submit a second withdrawal. + /// Outcomes of the broadcast are kept distinct. A transition that never + /// left this wallet (refused before anything was sent) is an ordinary + /// error and may be retried. Once a dispatch may have reached a node, + /// anything short of a proved result, an endpoint's refusal or a + /// consensus verdict included, is + /// [`PlatformWalletError::MasternodeWithdrawalUnconfirmed`] and MUST NOT + /// be retried until the claimable balance is re-read: no proof backs an + /// endpoint's answer, and the identity nonce was already taken for this + /// attempt, so a blind retry would submit a second withdrawal with the + /// next one. pub async fn masternode_withdraw( &self, request: MasternodeWithdrawalRequest, @@ -387,9 +390,11 @@ impl PlatformWallet { /// `expected_hash160`, sign with `signer` at `path` through /// [`DerivedKeyIdentitySigner`] (which re-checks the derived key against /// `expected_hash160` before emitting a signature), broadcast, and wait for -/// the proved balance. Error semantics: definitive rejections stay -/// retryable, ambiguous outcomes are -/// [`PlatformWalletError::MasternodeWithdrawalUnconfirmed`]. +/// the proved balance. Error semantics: a failure before the broadcast, or a +/// broadcast refused before anything was sent, stays retryable; every other +/// outcome short of a proved result is +/// [`PlatformWalletError::MasternodeWithdrawalUnconfirmed`] +/// ([`settle_masternode_withdrawal`]). #[allow(clippy::too_many_arguments)] pub(crate) async fn execute_masternode_withdrawal( sdk: &dash_sdk::Sdk, @@ -481,38 +486,94 @@ pub(crate) async fn execute_masternode_withdrawal .await .map_err(|e| definitive(dash_sdk::Error::Protocol(e)))?; - // Broadcast, then wait — split so an ambiguous outcome stays typed. - let unconfirmed = |reason: String| PlatformWalletError::MasternodeWithdrawalUnconfirmed { - identity_id, - amount_credits, - reason, - }; - match state_transition.broadcast(sdk, None).await { - Ok(()) => {} - Err(e) if broadcast_definitely_failed(&e) => return Err(definitive(e)), - Err(e) => { + broadcast_masternode_withdrawal(sdk, &state_transition, identity_id, amount_credits).await +} + +/// Broadcast the signed masternode withdrawal `state_transition`, keeping +/// what every dispatch proved ([`broadcast_tracking_delivery`]), then wait +/// for its result: split so an outcome that is not known stays typed +/// ([`settle_masternode_withdrawal`]). +async fn broadcast_masternode_withdrawal( + sdk: &dash_sdk::Sdk, + state_transition: &StateTransition, + identity_id: Identifier, + amount_credits: u64, +) -> Result { + let delivery = broadcast_tracking_delivery(sdk, state_transition).await; + settle_masternode_withdrawal(identity_id, amount_credits, delivery, || { + state_transition.wait_for_affected_state::(sdk, None) + }) + .await +} + +/// What a signed masternode withdrawal's broadcast (`delivery`) and result +/// wait (`wait`, run only when a dispatch may have reached a node) came to: +/// the identity's proved remaining balance, or the error the withdrawal +/// reports. +/// +/// Only a transition that never left the wallet +/// ([`BroadcastDelivery::NeverDelivered`]: refused before anything was sent) +/// is an ordinary, retryable error: nothing holds its bytes but the wallet, +/// so it can never execute. Once a dispatch may have reached a node, every +/// outcome short of the proved balance is +/// [`PlatformWalletError::MasternodeWithdrawalUnconfirmed`]: a wait that +/// fails, an endpoint's refusal of the broadcast and a consensus verdict on +/// either call included. The endpoint that sends a verdict is +/// unauthenticated, no proof or quorum signature backs it, and one that kept +/// or forwarded the signed transition can answer with any verdict, while a +/// retry signs a second withdrawal with the next identity nonce. +/// +/// The withdrawal keeps no record of its signed transition: what settles an +/// unconfirmed one is the identity's nonce (once the nonce it signed with +/// reads as used, it executed or can no longer execute) and the claimable +/// balance, which the host re-reads before it submits again. +async fn settle_masternode_withdrawal( + identity_id: Identifier, + amount_credits: u64, + delivery: BroadcastDelivery, + wait: W, +) -> Result +where + W: FnOnce() -> Fut, + Fut: std::future::Future>, +{ + // What the broadcast was answered with, kept for the reason an + // unconfirmed withdrawal reports. + let broadcast_answer = match delivery { + BroadcastDelivery::Admitted => None, + BroadcastDelivery::NeverDelivered(e) => { + return Err(PlatformWalletError::InvalidIdentityData(format!( + "masternode withdrawal failed: {e}" + ))); + } + BroadcastDelivery::MaybeDelivered(e) => { tracing::warn!( identity = %identity_id, error = %e, - "masternode withdrawal broadcast returned no verdict; the transition may \ - have been admitted — falling through to the result wait" + "masternode withdrawal broadcast may have been delivered; falling through \ + to the result wait" ); + Some(e.to_string()) } - } + }; + let unconfirmed = |waited: String| PlatformWalletError::MasternodeWithdrawalUnconfirmed { + identity_id, + amount_credits, + reason: match &broadcast_answer { + Some(answer) => format!("{waited}; its broadcast answered: {answer}"), + None => waited, + }, + }; - match state_transition - .wait_for_affected_state::(sdk, None) - .await - { + match wait().await { Ok(StateTransitionProofResult::VerifiedPartialIdentity(partial)) => partial .balance .ok_or_else(|| unconfirmed("the result proof carried no identity balance".to_string())), - // Proved, but not the shape a withdrawal produces — the transition - // landed; only the balance read-back is missing. + // Verified, but not the identity balance a withdrawal's result + // carries: the remaining balance is not proved. Ok(_) => Err(unconfirmed( "the result proof did not carry the identity's balance".to_string(), )), - Err(e) if carries_consensus_rejection(&e) => Err(definitive(e)), Err(e) => Err(unconfirmed(e.to_string())), } } @@ -724,11 +785,221 @@ where #[cfg(test)] mod tests { use super::*; + use crate::broadcast_outcome::test_sdks::{sdk_refusing_connections, sdk_without_addresses}; + use dash_sdk::dapi_client::transport::TransportError; + use dash_sdk::dapi_client::DapiClientError; + use dash_sdk::dapi_grpc::tonic::{Code, Status}; + use dash_sdk::error::StateTransitionBroadcastError; use dashcore::crypto::ecdsa::{EcdsaPublicKey as PublicKey, EcdsaSecretKey as SecretKey}; + use dpp::consensus::basic::{BasicError, UnsupportedFeatureError}; + use dpp::consensus::ConsensusError; use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; - use dpp::identity::{Purpose, SecurityLevel}; + use dpp::identity::{PartialIdentity, Purpose, SecurityLevel}; + use dpp::state_transition::identity_credit_withdrawal_transition::v1::IdentityCreditWithdrawalTransitionV1; + use std::cell::Cell; use std::str::FromStr; + /// The identity the withdrawal tests withdraw from, and the amount. + const WITHDRAWN_FROM: [u8; 32] = [0x31; 32]; + const WITHDRAWN: u64 = 1_000_000; + + /// A node's refusal of a dispatch, as an offline or overloaded endpoint + /// answers one. + fn unavailable() -> dash_sdk::Error { + dash_sdk::Error::DapiClientError(DapiClientError::Transport(TransportError::Grpc( + Status::new(Code::Unavailable, "test"), + ))) + } + + fn verdict() -> ConsensusError { + ConsensusError::BasicError(BasicError::UnsupportedFeatureError( + UnsupportedFeatureError::new("test".to_string(), 1), + )) + } + + /// A consensus verdict as a broadcast returns one. + fn broadcast_verdict() -> dash_sdk::Error { + dash_sdk::Error::Protocol(ProtocolError::ConsensusError(Box::new(verdict()))) + } + + /// A consensus verdict as the result wait returns one. + fn wait_verdict() -> dash_sdk::Error { + dash_sdk::Error::StateTransitionBroadcastError(StateTransitionBroadcastError { + code: 1, + message: "rejected".to_string(), + cause: Some(verdict()), + }) + } + + fn wait_timeout() -> dash_sdk::Error { + dash_sdk::Error::TimeoutReached(std::time::Duration::from_secs(80), "waiting".to_string()) + } + + fn proved_balance(balance: Option) -> StateTransitionProofResult { + StateTransitionProofResult::VerifiedPartialIdentity(PartialIdentity { + id: Identifier::from(WITHDRAWN_FROM), + loaded_public_keys: Default::default(), + balance, + revision: None, + not_found_public_keys: Default::default(), + }) + } + + fn is_unconfirmed(settled: &Result) -> bool { + matches!( + settled, + Err(PlatformWalletError::MasternodeWithdrawalUnconfirmed { + identity_id, + amount_credits: WITHDRAWN, + .. + }) if *identity_id == Identifier::from(WITHDRAWN_FROM) + ) + } + + /// Once a dispatch may have reached a node, a withdrawal whose result is + /// not proved is unconfirmed, never failed: a node's refusal of the + /// broadcast and a consensus verdict on either call included, as no proof + /// backs an endpoint's answer and a retry signs a second withdrawal. The + /// reason keeps what the wait and the broadcast were answered with. + #[tokio::test] + async fn should_report_a_masternode_withdrawal_unconfirmed_once_a_dispatch_may_have_reached_a_node( + ) { + let cases = [ + ( + "a node refused the broadcast, the wait timed out", + BroadcastDelivery::MaybeDelivered(unavailable()), + wait_timeout(), + ), + ( + "the broadcast was answered with a consensus verdict", + BroadcastDelivery::MaybeDelivered(broadcast_verdict()), + wait_timeout(), + ), + ( + "admitted, the wait was answered with a consensus verdict", + BroadcastDelivery::Admitted, + wait_verdict(), + ), + ( + "admitted, the wait timed out", + BroadcastDelivery::Admitted, + wait_timeout(), + ), + ]; + for (case, delivery, wait_error) in cases { + let broadcast_answer = match &delivery { + BroadcastDelivery::MaybeDelivered(e) => Some(e.to_string()), + _ => None, + }; + let waited = wait_error.to_string(); + let settled = settle_masternode_withdrawal( + Identifier::from(WITHDRAWN_FROM), + WITHDRAWN, + delivery, + || std::future::ready(Err(wait_error)), + ) + .await; + let Err(PlatformWalletError::MasternodeWithdrawalUnconfirmed { reason, .. }) = settled + else { + panic!("{case}: {settled:?}"); + }; + assert!(reason.contains(&waited), "{case}: {reason}"); + if let Some(answer) = broadcast_answer { + assert!(reason.contains(&answer), "{case}: {reason}"); + } + } + } + + /// Only a withdrawal whose transition never left the wallet is an + /// ordinary, retryable failure, and nothing waits for its result. + #[tokio::test] + async fn should_report_a_masternode_withdrawal_failed_only_when_nothing_was_sent() { + let waited = Cell::new(false); + let settled = settle_masternode_withdrawal( + Identifier::from(WITHDRAWN_FROM), + WITHDRAWN, + BroadcastDelivery::NeverDelivered(dash_sdk::Error::DapiClientError( + DapiClientError::NoAvailableAddresses, + )), + || { + waited.set(true); + std::future::ready(Err(wait_timeout())) + }, + ) + .await; + assert!( + matches!(settled, Err(PlatformWalletError::InvalidIdentityData(_))), + "{settled:?}" + ); + assert!(!waited.get(), "nothing was sent, so nothing is waited for"); + } + + /// A proved result returns the identity's remaining balance, whatever the + /// broadcast answered; a proof that carries no balance leaves the + /// withdrawal unconfirmed. + #[tokio::test] + async fn should_return_a_masternode_withdrawal_s_proved_balance() { + for delivery in [ + BroadcastDelivery::Admitted, + BroadcastDelivery::MaybeDelivered(unavailable()), + ] { + let settled = settle_masternode_withdrawal( + Identifier::from(WITHDRAWN_FROM), + WITHDRAWN, + delivery, + || std::future::ready(Ok(proved_balance(Some(7)))), + ) + .await; + assert!(matches!(settled, Ok(7)), "{settled:?}"); + } + let settled = settle_masternode_withdrawal( + Identifier::from(WITHDRAWN_FROM), + WITHDRAWN, + BroadcastDelivery::Admitted, + || std::future::ready(Ok(proved_balance(None))), + ) + .await; + assert!(is_unconfirmed(&settled), "{settled:?}"); + } + + /// The broadcast of a signed withdrawal through a network SDK: a node that + /// refuses the connection leaves it unconfirmed, as a transport failure + /// cannot show that nothing was sent, and an SDK with no address to send + /// to leaves it failed. + #[tokio::test] + async fn should_report_a_masternode_withdrawal_unconfirmed_when_its_node_refuses_the_connection( + ) { + let transition: StateTransition = IdentityCreditWithdrawalTransitionV1 { + identity_id: Identifier::from(WITHDRAWN_FROM), + amount: WITHDRAWN, + nonce: 4, + ..Default::default() + } + .into(); + + let (refusing, _port) = sdk_refusing_connections(); + let refused = broadcast_masternode_withdrawal( + &refusing, + &transition, + Identifier::from(WITHDRAWN_FROM), + WITHDRAWN, + ) + .await; + assert!(is_unconfirmed(&refused), "{refused:?}"); + + let never_sent = broadcast_masternode_withdrawal( + &sdk_without_addresses(), + &transition, + Identifier::from(WITHDRAWN_FROM), + WITHDRAWN, + ) + .await; + assert!( + matches!(never_sent, Err(PlatformWalletError::InvalidIdentityData(_))), + "{never_sent:?}" + ); + } + /// Test signer: one fixed secp256k1 key regardless of path. struct FixedKeySigner { secret: SecretKey, diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index 51b978a3dcf..3c3cdca430b 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -2351,6 +2351,11 @@ impl PlatformWallet { /// at `payment_account` doesn't exist, or /// `PlatformShieldCapacityExceeded` if the selected Platform-address set /// can't cover `amount` plus the fee reserve. + /// + /// Succeeds once the shield's verified result reads every input address + /// at or past the nonce the shield signed. The activity row stays pending + /// until the shielded scan observes the note on-chain: the result proves + /// the input addresses, not this shield or its note. #[cfg(feature = "shielded")] pub async fn shielded_shield_from_account( &self, diff --git a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs index 9105c5dd007..c213918b251 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs @@ -33,7 +33,7 @@ use super::store::{ SubwalletId, }; use crate::broadcast_outcome::{ - broadcast_definitely_failed, broadcast_tracking_delivery, carries_consensus_rejection, + broadcast_tracking_delivery, broadcast_was_refused, carries_consensus_rejection, BroadcastDelivery, }; use crate::changeset::{PlatformWalletChangeSet, ShieldedChangeSet}; @@ -68,7 +68,7 @@ use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV use dpp::identity::signer::Signer; use dpp::identity::{Identity, IdentityPublicKey}; use dpp::platform_value::BinaryData; -use dpp::prelude::{Identifier, IdentityNonce}; +use dpp::prelude::{AddressNonce, Identifier, IdentityNonce}; use dpp::shielded::builder::{ build_identity_create_from_shielded_pool_transition, build_identity_top_up_from_shielded_pool_transition, @@ -703,117 +703,240 @@ pub async fn shield_to, P: Orchar ) .await; - // Wait for proven execution (not just relay-ACK) so the host only - // sees success once Platform has actually included the transition. A - // DAPI-level ACK alone could otherwise mask a later Platform - // rejection. The proven result is discarded; we only need the - // confirmation. Staged like `broadcast_shielded_spend`: only a - // DEFINITIVE verdict (CheckTx rejection / refused admission) marks - // the activity row Failed — an ambiguous wait failure (timeout, - // result-proof fetch error) leaves it Pending, because the shield - // may still land and the scan's cmx-overlap confirmation will flip - // the row when its note appears on-chain. Shield takes no note - // reservation, so the ambiguous arm strands no local spend state; - // its inputs are transparent address claims guarded by on-chain - // nonces, and a host-level retry re-fetches those nonces. - let enrich = |e: &dash_sdk::Error| -> PlatformWalletError { - if let Some(rich) = addresses_not_enough_funds(e) { - let claimed = claimed_inputs - .iter() - .map(|(addr, (nonce, credits))| { - format!( - "{}=(nonce {nonce}, {credits} credits)", - addr.to_bech32m_string(network) - ) - }) - .collect::>() - .join(", "); - PlatformWalletError::ShieldedBroadcastFailed(format!( - "addresses not enough funds: required {} credits; \ - claimed inputs [{}]; platform sees [{}]", - rich.required_balance(), - claimed, - format_addresses_with_info(rich.addresses_with_info(), network), - )) - } else { - crate::error::promote_address_nonce_error(e) - .unwrap_or_else(|| PlatformWalletError::ShieldedBroadcastFailed(e.to_string())) - } + // What an endpoint's answer says, for the reason an unconfirmed shield + // reports. A funds shortfall names the claimed inputs beside what the + // endpoint says Platform sees. + let describe = |e: &dash_sdk::Error| -> String { + let Some(rich) = addresses_not_enough_funds(e) else { + return e.to_string(); + }; + let claimed = claimed_inputs + .iter() + .map(|(addr, (nonce, credits))| { + format!( + "{}=(nonce {nonce}, {credits} credits)", + addr.to_bech32m_string(network) + ) + }) + .collect::>() + .join(", "); + format!( + "addresses not enough funds: required {} credits; \ + claimed inputs [{}]; platform sees [{}]", + rich.required_balance(), + claimed, + format_addresses_with_info(rich.addresses_with_info(), network), + ) }; - match state_transition.broadcast(sdk, None).await { - Ok(()) => {} - Err(e) if broadcast_definitely_failed(&e) => { + // Broadcast keeping what every dispatch proved, then wait for the + // verified snapshot of the input addresses (not just a relay ACK). A + // shield's proof authenticates those addresses as of its block, not this + // exact shield's execution, so the host sees success only once the + // snapshot reads every input at or past the nonce this shield signed, and + // the activity row stays pending until the scan observes the note. + broadcast_shield( + sdk, + store, + persister, + wallet_id, + id, + &pending_entry, + &state_transition, + describe, + ) + .await?; + info!( + account, + credits = amount, + "Shield admitted with its input addresses proved spent; the activity row awaits \ + on-chain confirmation by the shielded scan" + ); + Ok(()) +} + +/// Broadcast the signed shield `state_transition`, keeping what every +/// dispatch proved ([`broadcast_tracking_delivery`]), wait for its result and +/// settle it ([`settle_shield`]). +#[allow(clippy::too_many_arguments)] +async fn broadcast_shield( + sdk: &Arc, + store: &Arc>, + persister: Option<&WalletPersister>, + wallet_id: WalletId, + id: SubwalletId, + pending_entry: &Option, + state_transition: &StateTransition, + describe: D, +) -> Result<(), PlatformWalletError> +where + S: ShieldedStore, + D: Fn(&dash_sdk::Error) -> String, +{ + let delivery = broadcast_tracking_delivery(sdk, state_transition).await; + // A transition that names no input is no shield from addresses: its + // result then shows nothing spent, and it settles as unconfirmed. + let no_inputs = BTreeMap::new(); + settle_shield( + store, + persister, + wallet_id, + id, + pending_entry, + state_transition.inputs().unwrap_or(&no_inputs), + delivery, + describe, + || state_transition.wait_for_affected_state::(sdk, None), + ) + .await +} + +/// What a signed shield's broadcast (`delivery`) and result wait (`wait`, run +/// only when a dispatch may have reached a node) came to, recording it on the +/// shield's activity row (`pending_entry`). `signed_inputs` are the shield's +/// input addresses with the nonces it signed, and `describe` renders an +/// endpoint's answer for the reason an unconfirmed shield reports. +/// +/// Only a transition that never left the wallet +/// ([`BroadcastDelivery::NeverDelivered`]: refused before anything was sent) +/// is a failed shield +/// ([`PlatformWalletError::ShieldedBroadcastFailed`]): nothing holds its bytes +/// but the wallet, so it can never execute, its row reads failed and the host +/// may retry. Once a dispatch may have reached a node, every outcome short +/// of a verified result that reads its inputs spent +/// ([`shield_inputs_read_spent`]) is +/// [`PlatformWalletError::ShieldedSpendUnconfirmed`]: a wait that fails, a +/// result that does not show the inputs spent, an endpoint's refusal of the +/// broadcast and a consensus verdict on either call included. The endpoint +/// that sends a verdict is unauthenticated, no proof or quorum signature +/// backs it, and one that kept or forwarded the signed transition can answer +/// with any verdict, while a retry signs a second shield with the inputs' +/// next nonces, and a shield's note can be a recipient's ([`shield_to`]). +/// +/// The row stays pending on every outcome but the failed one, a successful +/// one included, as a shield from an identity's does: the result proves the +/// input addresses as of its block, which does not bind this transition or +/// its note. The scan confirms the row when the note commitment appears on +/// chain. +/// +/// The shield takes no note reservation and keeps no record of its signed +/// transition. What shows that an unconfirmed one can no longer execute is +/// its inputs' nonces (one of them used by another transition), which +/// nothing reads for it: until then the row stays pending. +#[allow(clippy::too_many_arguments)] +async fn settle_shield( + store: &Arc>, + persister: Option<&WalletPersister>, + wallet_id: WalletId, + id: SubwalletId, + pending_entry: &Option, + signed_inputs: &BTreeMap, + delivery: BroadcastDelivery, + describe: D, + wait: W, +) -> Result<(), PlatformWalletError> +where + S: ShieldedStore, + D: Fn(&dash_sdk::Error) -> String, + W: FnOnce() -> Fut, + Fut: Future>, +{ + let broadcast_answer = match delivery { + BroadcastDelivery::Admitted => None, + BroadcastDelivery::NeverDelivered(e) => { record_activity_status( store, persister, wallet_id, id, - &pending_entry, + pending_entry, ShieldedActivityStatus::Failed, None, ) .await; - return Err(enrich(&e)); + return Err(definite_broadcast_failure(&e)); } - Err(e) => { + BroadcastDelivery::MaybeDelivered(e) => { warn!( - account, + account = id.account_index, error = %e, - "Shield broadcast returned no verdict; the transition may have been \ - admitted — falling through to the result wait" + "Shield broadcast may have been delivered; falling through to the result wait" ); + Some(describe(&e)) } - } + }; - // A shield proof authenticates the input addresses' post-state, not this - // exact shield's execution — accept the affected-state snapshot; a - // consensus rejection still surfaces as an error here. - if let Err(wait_err) = state_transition - .wait_for_affected_state::(sdk, None) - .await - { - if carries_consensus_rejection(&wait_err) { - // A consensus verdict in the result: the shield definitively - // did not execute. - record_activity_status( - store, - persister, - wallet_id, - id, - &pending_entry, - ShieldedActivityStatus::Failed, - None, - ) - .await; - return Err(enrich(&wait_err)); + // Whatever the wait comes to, the activity row stays Pending: the scan's + // confirmation pass flips it when the shielded note lands on-chain. + let unproved = match wait().await { + Ok(snapshot) => match shield_inputs_read_spent(signed_inputs, &snapshot) { + Ok(()) => return Ok(()), + Err(unproved) => { + warn!( + account = id.account_index, + reason = %unproved, + "Shield result does not read its inputs spent; leaving the activity row pending" + ); + unproved + } + }, + Err(wait_err) => { + warn!( + account = id.account_index, + error = %wait_err, + rejected = carries_consensus_rejection(&wait_err), + "Shield broadcast but its result is unconfirmed; leaving the activity row pending" + ); + describe(&wait_err) } - // Ambiguous: admitted but unconfirmed. Leave the activity row - // Pending — the scan's confirmation pass flips it when the - // shielded note lands on-chain. - warn!( - account, - error = %wait_err, - "Shield broadcast accepted but result confirmation failed; \ - leaving the activity row pending" - ); - return Err(PlatformWalletError::ShieldedSpendUnconfirmed { - operation: "shield", - reason: wait_err.to_string(), - }); - } + }; + Err(PlatformWalletError::ShieldedSpendUnconfirmed { + operation: "shield", + reason: match broadcast_answer { + Some(answer) => format!("{unproved}; its broadcast answered: {answer}"), + None => unproved, + }, + }) +} - record_activity_status( - store, - persister, - wallet_id, - id, - &pending_entry, - ShieldedActivityStatus::Confirmed, - None, - ) - .await; - info!(account, credits = amount, "Shield broadcast succeeded"); +/// Whether `snapshot`, the verified result a shield's wait returned, reads +/// every input address of the shield at or past the nonce the shield signed +/// it with (`signed_inputs`), or why it does not. +/// +/// The proof behind a shield's result authenticates its input addresses as +/// of the proof's block, not the shield's execution. An address's nonce +/// advances only when a transition signed with that nonce executes, so +/// inputs at or past their signed nonces show those nonces used. A result +/// that is no address snapshot shows nothing of the shield, and one that +/// leaves an input out, proves no state for it or reads it below its signed +/// nonce shows the shield had not executed at that block, whatever the +/// endpoint that returned it claims. +fn shield_inputs_read_spent( + signed_inputs: &BTreeMap, + snapshot: &StateTransitionProofResult, +) -> Result<(), String> { + let StateTransitionProofResult::VerifiedAddressInfos(proved) = snapshot else { + return Err(format!( + "a proof of its input addresses was expected, received {snapshot}" + )); + }; + if signed_inputs.is_empty() { + return Err("it names no input address".to_string()); + } + for (address, (signed, _)) in signed_inputs { + match proved.get(address) { + Some(Some((proved, _))) if proved >= signed => {} + Some(Some((proved, _))) => { + return Err(format!( + "its result proves an input address at nonce {proved}, below the nonce \ + {signed} it signed" + )); + } + Some(None) | None => { + return Err("its result proves no state for an input address".to_string()); + } + } + } Ok(()) } @@ -1049,7 +1172,7 @@ pub(in crate::wallet) async fn shield_from_identity_to< match state_transition.broadcast(sdk, None).await { Ok(()) => {} - Err(e) if broadcast_definitely_failed(&e) => { + Err(e) if broadcast_was_refused(&e) => { // Unauthenticated verdict: settle it against the proven nonce. return Err(settle_identity_shield_failure( sdk, @@ -1472,21 +1595,8 @@ pub(in crate::wallet) async fn identity_top_up_from_pool_with_metadata< }, ) .await; - if arm_pending_release( - store, - id, - anchor_bytes, - anchor_height, - &pending_entry, - &selected_notes, - ) - .await? - { - // Each reservation carries its anchor: a pruned anchor releases it. - reservation.hand_over(); - } - trace!("IdentityTopUpFromShieldedPool: state transition built, broadcasting..."); + trace!("IdentityTopUpFromShieldedPool: state transition built, saving and broadcasting..."); // Type 22 is classified affected state: its nullifiers are shared with any // competing spend of the same notes and the identity's balance is a // snapshot, so the strict wait would reject every success. The snapshot @@ -1501,6 +1611,7 @@ pub(in crate::wallet) async fn identity_top_up_from_pool_with_metadata< anchor_bytes, anchor_height, &selected_notes, + &mut reservation, &state_transition, "identity top up from shielded pool", SpendResultWait::AffectedState, @@ -1567,28 +1678,17 @@ pub(in crate::wallet) async fn identity_top_up_from_pool_with_metadata< }; Ok((proven_balance, metadata)) } - Err(e @ PlatformWalletError::ShieldedSpendUnconfirmed { .. }) => { - // It may have executed: the reservation stays, released by sync. - reservation.hand_over(); - Err(e) - } - Err(e) => { - // It did not execute: the guard owns the notes until they are - // released, so a drop on the way still releases them. - reservation.reclaim(); - record_activity_status( - store, - persister, - wallet_id, - id, - &pending_entry, - ShieldedActivityStatus::Failed, - None, - ) - .await; - reservation.cancel().await; - Err(e) - } + Err(failure) => Err(settle_failed_spend( + store, + persister, + wallet_id, + id, + &pending_entry, + reservation, + "identity top up from shielded pool", + failure, + ) + .await), } } @@ -2185,10 +2285,9 @@ pub async fn unshield( "Unshield" ); - // From here on every error path must release the reservation taken - // by `reserve_unspent_notes` — except the ambiguous - // `ShieldedSpendUnconfirmed` one, which intentionally leaves it in - // place (see the outer match below). + // From here on an error before the spend's record is saved releases the + // reservation taken by `reserve_unspent_notes`; once it is saved, only a + // transition that never left the wallet does (`settle_failed_spend`). // // `pending_entry` is recorded once the transition is built (so we // have its output cmxs) and flipped to Confirmed / Failed in the @@ -2246,21 +2345,8 @@ pub async fn unshield( }, ) .await; - if arm_pending_release( - store, - id, - anchor_bytes, - anchor_height, - &pending_entry, - &selected_notes, - ) - .await? - { - // Each reservation carries its anchor: a pruned anchor releases it. - reservation.hand_over(); - } - trace!("Unshield: state transition built, broadcasting..."); + trace!("Unshield: state transition built, saving and broadcasting..."); broadcast_shielded_spend_with_redrive( sdk, store, @@ -2269,6 +2355,7 @@ pub async fn unshield( anchor_bytes, anchor_height, &selected_notes, + &mut reservation, &state_transition, "unshield", SpendResultWait::ExecutionProved, @@ -2303,9 +2390,9 @@ pub async fn unshield( // scan runs the note is re-selected and a second spend is // built + proven, then rejected at broadcast with a // nullifier-already-used error — wasted ~30 s proof, never - // fund loss. (`pending_nullifiers` is in-memory only, so it - // does not protect across a process restart in this window; - // the on-chain set does.) + // fund loss. (A restart restores the reservation only while + // the spend's saved record is still there; the on-chain set + // protects either way.) if let Err(e) = finalize_pending(store, persister, wallet_id, id, &selected_notes).await { warn!( @@ -2318,43 +2405,25 @@ pub async fn unshield( info!(account, credits = amount, "Unshield broadcast succeeded"); Ok(()) } - // The broadcast was accepted but its execution result couldn't be - // confirmed: the spend may well have executed, so do NOT release - // the reservation. `pending_nullifiers` is in-memory only — if the - // spend landed, the next nullifier sync's `mark_spent` promotes the - // notes to spent (clearing the reservation); if it never landed, an - // app restart drops the reservation and frees the notes. Releasing - // them now would invite re-selecting notes whose nullifiers may - // already be consumed on chain. - // - // Activity entry: leave it `Pending`. Like the note reservation, - // the outcome is genuinely unknown here — a later scan that finds - // the spend will flip the row to Confirmed (its id matches), and - // until then surfacing it as Pending is honest. - Err(e @ PlatformWalletError::ShieldedSpendUnconfirmed { .. }) => { - // It may have executed: the reservation stays, released by sync. - reservation.hand_over(); - Err(e) - } - Err(e) => { - // It did not execute: the guard owns the notes until they are - // released, so a drop on the way still releases them. - reservation.reclaim(); - // Definitive failure: the spend never executed. Mark the - // activity row Failed (upsert by id) before releasing notes. - record_activity_status( - store, - persister, - wallet_id, - id, - &pending_entry, - ShieldedActivityStatus::Failed, - None, - ) - .await; - reservation.cancel().await; - Err(e) - } + // A spend that may have reached a node keeps its reservation, its + // saved record and its `Pending` activity row: a later scan that + // finds the spend marks the notes spent and flips the row to + // Confirmed (its id matches), and the saved record restores the + // reservation after a restart. Releasing the notes would invite + // re-selecting notes whose nullifiers may already be consumed on + // chain. Only a spend that failed before its record was saved, or + // whose transition never left the wallet, releases them. + Err(failure) => Err(settle_failed_spend( + store, + persister, + wallet_id, + id, + &pending_entry, + reservation, + "unshield", + failure, + ) + .await), } } @@ -2448,21 +2517,8 @@ pub async fn transfer( }, ) .await; - if arm_pending_release( - store, - id, - anchor_bytes, - anchor_height, - &pending_entry, - &selected_notes, - ) - .await? - { - // Each reservation carries its anchor: a pruned anchor releases it. - reservation.hand_over(); - } - trace!("Shielded transfer: state transition built, broadcasting..."); + trace!("Shielded transfer: state transition built, saving and broadcasting..."); broadcast_shielded_spend_with_redrive( sdk, store, @@ -2471,6 +2527,7 @@ pub async fn transfer( anchor_bytes, anchor_height, &selected_notes, + &mut reservation, &state_transition, "transfer", SpendResultWait::ExecutionProved, @@ -2510,31 +2567,18 @@ pub async fn transfer( ); Ok(()) } - // Ambiguous post-broadcast confirmation failure: leave the - // reservation (and the Pending activity row) in place — a later - // scan flips it to Confirmed (see `unshield`'s outer match). - Err(e @ PlatformWalletError::ShieldedSpendUnconfirmed { .. }) => { - // It may have executed: the reservation stays, released by sync. - reservation.hand_over(); - Err(e) - } - Err(e) => { - // It did not execute: the guard owns the notes until they are - // released, so a drop on the way still releases them. - reservation.reclaim(); - record_activity_status( - store, - persister, - wallet_id, - id, - &pending_entry, - ShieldedActivityStatus::Failed, - None, - ) - .await; - reservation.cancel().await; - Err(e) - } + // See `unshield`'s outer match. + Err(failure) => Err(settle_failed_spend( + store, + persister, + wallet_id, + id, + &pending_entry, + reservation, + "transfer", + failure, + ) + .await), } } @@ -2640,21 +2684,8 @@ pub async fn withdraw( }, ) .await; - if arm_pending_release( - store, - id, - anchor_bytes, - anchor_height, - &pending_entry, - &selected_notes, - ) - .await? - { - // Each reservation carries its anchor: a pruned anchor releases it. - reservation.hand_over(); - } - trace!("Shielded withdrawal: state transition built, broadcasting..."); + trace!("Shielded withdrawal: state transition built, saving and broadcasting..."); broadcast_shielded_spend_with_redrive( sdk, store, @@ -2663,6 +2694,7 @@ pub async fn withdraw( anchor_bytes, anchor_height, &selected_notes, + &mut reservation, &state_transition, "withdraw", SpendResultWait::ExecutionProved, @@ -2702,31 +2734,18 @@ pub async fn withdraw( ); Ok(()) } - // Ambiguous post-broadcast confirmation failure: leave the - // reservation (and the Pending activity row) in place — a later - // scan flips it to Confirmed (see `unshield`'s outer match). - Err(e @ PlatformWalletError::ShieldedSpendUnconfirmed { .. }) => { - // It may have executed: the reservation stays, released by sync. - reservation.hand_over(); - Err(e) - } - Err(e) => { - // It did not execute: the guard owns the notes until they are - // released, so a drop on the way still releases them. - reservation.reclaim(); - record_activity_status( - store, - persister, - wallet_id, - id, - &pending_entry, - ShieldedActivityStatus::Failed, - None, - ) - .await; - reservation.cancel().await; - Err(e) - } + // See `unshield`'s outer match. + Err(failure) => Err(settle_failed_spend( + store, + persister, + wallet_id, + id, + &pending_entry, + reservation, + "withdraw", + failure, + ) + .await), } } @@ -2808,14 +2827,16 @@ where .map(|(key, _)| (key.id(), key.clone())) .collect(); - // From here on every error path must release the reservation taken above — except the - // ambiguous `ShieldedBroadcastUnconfirmed` one, which intentionally leaves it in place - // (see the outer match below). + // From here on an error before the create's record is saved releases the reservation taken + // above; once it is saved, only a transition that never left the wallet does + // (`settle_failed_spend`). // // `pending_entry` is recorded once the bundle is built (so we know the // identity id + output cmxs) and flipped to Confirmed / Failed in the - // outer match; it lives here so the flip can see it. + // outer match; it lives here so the flip can see it. So does + // `derived_identity_id`, which an unconfirmed create reports. let mut pending_entry = None; + let mut derived_identity_id = None; let result = async { let (spends, anchor, anchor_height) = extract_spends_and_recorded_anchor(sdk, store, &selected_notes).await?; @@ -2842,6 +2863,7 @@ where .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))?; let identity_id = build.identity_id; + derived_identity_id = Some(identity_id); // Live activity: IdentityCreate carries the created identity id. // The display amount is the denomination LESS the metered fee (the @@ -2869,30 +2891,11 @@ where }, ) .await; - if arm_pending_release( - store, - id, - anchor_bytes, - anchor_height, - &pending_entry, - &selected_notes, - ) - .await? { - // Each reservation carries its anchor: a pruned anchor releases it. - reservation.hand_over(); - } - trace!("IdentityCreateFromShieldedPool: built, broadcasting via SDK..."); - // Stage the broadcast and the result-wait SEPARATELY (instead of one `broadcast_and_wait`) - // so the two failure shapes can be told apart: - // - a broadcast-time rejection (relay/CheckTx refused the tx) means it never executed, so - // releasing the note reservations is correct; - // - a post-broadcast wait failure is AMBIGUOUS — the relay accepted the tx and it may well - // have executed; treating it as "unregistered" + releasing the notes is the - // orphaned-identity + double-spend hazard this split exists to avoid. // The transition is built once from the PoP-signed keys + bundle params (preserving the // per-key signatures); the binding signature already committed `identity_id`, the - // denomination, and the full key set. + // denomination, and the full key set. It is built before its record is saved, which + // keeps these exact bytes. let st = sdk .identity_create_from_shielded_pool_transition( build.public_keys, @@ -2902,147 +2905,21 @@ where ) .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))?; - // Broadcast (relay-ACK only). Only a transition that never left the wallet - // (`BroadcastDelivery::NeverDelivered`: refused before anything was sent) maps to - // `ShieldedBroadcastFailed`, - // which lets the outer match release the reservation. Every other failure may have - // delivered it and falls through to the result wait below, whose ambiguous arm owns the - // fetch-by-derived-id fallback — so the in-flight tx gets confirmed (or held as - // unconfirmed) instead of being reported as failed. - match broadcast_tracking_delivery(sdk, &st).await { - BroadcastDelivery::Admitted => {} - BroadcastDelivery::NeverDelivered(e) => { - return Err(PlatformWalletError::ShieldedBroadcastFailed(e.to_string())); - } - BroadcastDelivery::MaybeDelivered(e) => { - warn!( - derived_id = %identity_id, - error = %e, - "IdentityCreateFromShieldedPool: broadcast may have been delivered — \ - falling through to the result wait" - ); - } - } - - // Wait for proven execution. Every failure is AMBIGUOUS: the broadcast reached an - // endpoint and the transition may have executed even though we couldn't fetch or - // verify its result proof. That includes a `StateTransitionBroadcastError` with a - // consensus `cause`: the endpoint that reports it is unauthenticated, no proof or quorum - // signature backs it, and one that kept or forwarded the transition can answer with any - // verdict. It also includes cause-less ones, as DAPI encodes its own wait-side failures - // (timeouts, internal errors) that way. Fall back to fetching the identity by its - // pre-derived id before deciding it is unconfirmed. - // An identity-create-from-shielded-pool proof authenticates the spent - // nullifiers and resulting identity as a snapshot; it cannot bind the - // complete Orchard request, so accept the affected-state outcome. - let proof_result = match st - .wait_for_affected_state::(sdk, None) - .await - { - Ok(result) => result, - Err(wait_err) => { - warn!( - derived_id = %identity_id, - error = %wait_err, - "IdentityCreateFromShieldedPool: broadcast accepted but result confirmation \ - failed; falling back to fetching the identity by its derived id" - ); - // Fetch the identity directly. The id is committed in the sighash and derived - // deterministically from the spent nullifiers, so if the transition landed the row - // is queryable. A freshly-included identity can take a moment to index on the DAPI - // node we hit, so retry a few times with a short, fixed backoff before concluding - // it's truly absent — long enough to ride out routine indexing/replica lag, short - // enough not to wedge the caller's UI for minutes. - match fetch_identity_with_retries(sdk, identity_id).await { - Some(mut identity) => { - info!( - derived_id = %identity_id, - "IdentityCreateFromShieldedPool: result confirmation failed but the \ - identity was found on chain by its derived id; treating as success" - ); - // Same defensive empty-`public_keys` fill as the proven-result path below, - // so downstream auth-key checks see the committed key set immediately. - if identity.public_keys().is_empty() { - identity.set_public_keys(submitted_public_keys.clone()); - } - return Ok::<(Identifier, Identity), PlatformWalletError>(( - identity.id(), - identity, - )); - } - None => { - // Arm the persisted re-drive before surfacing the - // ambiguity: the sync-time pass re-checks the - // nullifiers, then re-broadcasts this - // byte-identical transition up to - // MAX_REDRIVE_ATTEMPTS times. - arm_redrive_record( - store, - id, - &pending_entry, - anchor_bytes, - anchor_height, - &selected_notes, - &st, - "identity_create", - ) - .await; - return Err(PlatformWalletError::ShieldedBroadcastUnconfirmed { - identity_id, - reason: wait_err.to_string(), - }); - } - } - } - }; - - // Pull the verified `Identity` out of the proof result. The expected variant is - // `VerifiedIdentityWithShieldedNullifiers`; if drive-abci ever returns a different one the - // broadcast still SUCCEEDED, so we don't turn it into an error — we synthesize the identity - // from the derived id + submitted keys (the binding signature committed both) and warn, so - // the local row is still created. - let identity = match proof_result { - StateTransitionProofResult::VerifiedIdentityWithShieldedNullifiers( - mut identity, - _nullifiers, - ) => { - // The proof-verified id is authoritative: it's recomputed from the proven nullifier - // set, while `identity_id` was derived pre-broadcast. They should match (the derived - // id is committed in the sighash), but trust the verified one. - if identity.id() != identity_id { - warn!( - derived_id = %identity_id, - verified_id = %identity.id(), - "IdentityCreateFromShieldedPool: derived id differs from proof-verified id; \ - using the proof-verified id" - ); - } - // Defensive: a proof result can hand back an identity whose `public_keys` map is - // empty. Fill it from the submitted set so downstream auth-key checks see the keys - // immediately without waiting for the next identity-fetch round (the transition - // committed exactly these keys, so id reproducibility is preserved). - if identity.public_keys().is_empty() { - identity.set_public_keys(submitted_public_keys); - } - identity - } - other => { - warn!( - derived_id = %identity_id, - result = %other, - "IdentityCreateFromShieldedPool: unexpected proof-result variant; synthesizing \ - the identity from the derived id + submitted keys so the local row still lands" - ); - Identity::new_with_id_and_keys( - identity_id, - submitted_public_keys, - sdk.version(), - ) - .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))? - } - }; - - Ok::<(Identifier, Identity), PlatformWalletError>((identity.id(), identity)) + trace!("IdentityCreateFromShieldedPool: built, saving and broadcasting via SDK..."); + broadcast_identity_create_with_redrive( + sdk, + store, + id, + &pending_entry, + anchor_bytes, + anchor_height, + &selected_notes, + &mut reservation, + &st, + identity_id, + submitted_public_keys, + ) + .await } .await; @@ -3081,62 +2958,225 @@ where ); Ok((identity_id, identity)) } - // The broadcast was accepted but its result couldn't be confirmed and the identity wasn't - // found by a direct fetch. Do NOT release the notes here: `pending_nullifiers` is in-memory - // only (see `SubwalletState`, "never persisted; the next sync after a crash reconciles"), - // and `mark_spent` during nullifier sync clears matching reservations. So if the transition - // actually executed, the next sync promotes these notes to spent; if it truly never landed, - // an app restart drops the in-memory reservation and frees them. Releasing them now would - // invite double-spend attempts against notes that may already be consumed on chain — the - // very hazard this variant exists to prevent. The activity row likewise stays `Pending` - // (a later scan that finds the identity's change note flips it to Confirmed). - Err(e @ PlatformWalletError::ShieldedBroadcastUnconfirmed { .. }) => { - // It may have executed: the reservation stays, released by sync. - reservation.hand_over(); - Err(e) + // A create that may have reached a node keeps its reservation, its saved record and its + // `Pending` activity row (see `unshield`'s outer match), and reports the derived id: the + // identity may already exist on chain, so the caller holds its registration slot. + Err(failure) => { + let error = settle_failed_spend( + store, + persister, + wallet_id, + id, + &pending_entry, + reservation, + IDENTITY_CREATE_OPERATION, + failure, + ) + .await; + Err(identity_create_failure(error, derived_identity_id)) } - Err(e) => { - if error_releases_note_reservation(&e) { - // It did not execute: the guard owns the notes until they are - // released, so a drop on the way still releases them. - reservation.reclaim(); - // Definitive failure: the identity was never created. Mark - // the activity row Failed (upsert by id) before releasing. - record_activity_status( - store, - persister, - wallet_id, - id, - &pending_entry, - ShieldedActivityStatus::Failed, - None, - ) - .await; - reservation.cancel().await; - } else { - // It may have executed: the reservation stays, released by sync. - reservation.hand_over(); + } +} + +/// The error an identity create reports for `error`, what [`settle_failed_spend`] settled its +/// failure as. A create settled as unconfirmed carries the derived `identity_id` +/// ([`PlatformWalletError::ShieldedBroadcastUnconfirmed`]): the identity may already exist on +/// chain, so the caller must hold its registration slot rather than read a failed create. +fn identity_create_failure( + error: PlatformWalletError, + identity_id: Option, +) -> PlatformWalletError { + match (error, identity_id) { + (PlatformWalletError::ShieldedSpendUnconfirmed { reason, .. }, Some(identity_id)) => { + PlatformWalletError::ShieldedBroadcastUnconfirmed { + identity_id, + reason, } - Err(e) } + (error, _) => error, } } -/// Whether a failed identity-create should release the notes reserved for it. +/// Save the built identity create `st`'s recovery record durably, then +/// broadcast it and wait for its result ([`save_spend_then_broadcast`], +/// [`broadcast_identity_create`]): the identity create's counterpart of +/// [`broadcast_shielded_spend_with_redrive_with_metadata`]. +#[allow(clippy::too_many_arguments)] +async fn broadcast_identity_create_with_redrive( + sdk: &Arc, + store: &Arc>, + id: SubwalletId, + pending_entry: &Option, + anchor: [u8; 32], + anchor_height: u64, + notes: &[ShieldedNote], + reservation: &mut NoteReservation, + st: &StateTransition, + identity_id: Identifier, + submitted_public_keys: BTreeMap, +) -> Result<(Identifier, Identity), SpendFailure> { + save_spend_then_broadcast( + store, + id, + pending_entry, + anchor, + anchor_height, + notes, + reservation, + st, + IDENTITY_CREATE_OPERATION, + || broadcast_identity_create(sdk, st, identity_id, submitted_public_keys), + ) + .await +} + +/// What an identity create is named in the errors its record's save and its +/// settlement report. +const IDENTITY_CREATE_OPERATION: &str = "identity create from shielded pool"; + +/// Broadcast the built identity create `st`, whose record is already saved +/// ([`save_spend_then_broadcast`]), and wait for its result. /// -/// `false` ONLY for [`PlatformWalletError::ShieldedBroadcastUnconfirmed`]: the broadcast was -/// accepted and the transition may have executed, so the reservation must be retained. Releasing it -/// now would invite double-spend attempts against notes that may already be consumed on chain — the -/// very hazard that variant exists to prevent. `pending_nullifiers` is in-memory only (see -/// `SubwalletState`, "never persisted; the next sync after a crash reconciles") and `mark_spent` -/// during nullifier sync clears matching reservations, so if the transition actually executed the -/// next sync promotes these notes to spent; if it truly never landed, an app restart drops the -/// in-memory reservation and frees them. +/// The broadcast and the result wait are staged separately so the two failure shapes can be +/// told apart: +/// - a transition that never left the wallet ([`BroadcastDelivery::NeverDelivered`]: refused +/// before anything was sent) can never execute, so its record is retired and its notes are +/// released ([`SpendFailure::never_delivered`]); +/// - every other failure may have delivered it. It falls through to the result wait, and a +/// wait that fails falls back to fetching the identity by its pre-derived id before the +/// create is reported unconfirmed ([`PlatformWalletError::ShieldedBroadcastUnconfirmed`]), +/// its notes and record kept. That includes a `StateTransitionBroadcastError` with a +/// consensus `cause`: the endpoint that reports it is unauthenticated, no proof or quorum +/// signature backs it, and one that kept or forwarded the transition can answer with any +/// verdict. It also includes cause-less ones, as DAPI encodes its own wait-side failures +/// (timeouts, internal errors) that way. /// -/// Everything else is a definitive pre-execution / build / rejection failure: the spend never -/// happened, so the reservation must be released. -fn error_releases_note_reservation(e: &PlatformWalletError) -> bool { - !matches!(e, PlatformWalletError::ShieldedBroadcastUnconfirmed { .. }) +/// Nothing here reports a failed create once a dispatch may have reached a node: a create +/// reported failed while it may still execute is the orphaned-identity hazard this staging +/// exists to avoid. +async fn broadcast_identity_create( + sdk: &Arc, + st: &StateTransition, + identity_id: Identifier, + submitted_public_keys: BTreeMap, +) -> Result<(Identifier, Identity), SpendFailure> { + let unconfirmed = |reason: String| { + SpendFailure::from(PlatformWalletError::ShieldedBroadcastUnconfirmed { + identity_id, + reason, + }) + }; + + match broadcast_tracking_delivery(sdk, st).await { + BroadcastDelivery::Admitted => {} + BroadcastDelivery::NeverDelivered(e) => { + return Err(SpendFailure { + error: definite_broadcast_failure(&e), + never_delivered: true, + }); + } + BroadcastDelivery::MaybeDelivered(e) => { + warn!( + derived_id = %identity_id, + error = %e, + "IdentityCreateFromShieldedPool: broadcast may have been delivered; falling \ + through to the result wait" + ); + } + } + + // An identity-create-from-shielded-pool proof authenticates the spent + // nullifiers and resulting identity as a snapshot; it cannot bind the + // complete Orchard request, so accept the affected-state outcome. + let proof_result = match st + .wait_for_affected_state::(sdk, None) + .await + { + Ok(result) => result, + Err(wait_err) => { + warn!( + derived_id = %identity_id, + error = %wait_err, + "IdentityCreateFromShieldedPool: broadcast accepted but result confirmation \ + failed; falling back to fetching the identity by its derived id" + ); + // Fetch the identity directly. The id is committed in the sighash and derived + // deterministically from the spent nullifiers, so if the transition landed the row + // is queryable. A freshly-included identity can take a moment to index on the DAPI + // node we hit, so retry a few times with a short, fixed backoff before concluding + // it's truly absent: long enough to ride out routine indexing/replica lag, short + // enough not to wedge the caller's UI for minutes. + return match fetch_identity_with_retries(sdk, identity_id).await { + Some(mut identity) => { + info!( + derived_id = %identity_id, + "IdentityCreateFromShieldedPool: result confirmation failed but the \ + identity was found on chain by its derived id; treating as success" + ); + // Same defensive empty-`public_keys` fill as the proven-result path below, + // so downstream auth-key checks see the committed key set immediately. + if identity.public_keys().is_empty() { + identity.set_public_keys(submitted_public_keys); + } + Ok((identity.id(), identity)) + } + // The saved record resolves it: the sync-time pass re-checks the nullifiers, + // then re-broadcasts this byte-identical transition up to + // MAX_REDRIVE_ATTEMPTS times. + None => Err(unconfirmed(wait_err.to_string())), + }; + } + }; + + // Pull the verified `Identity` out of the proof result. The expected variant is + // `VerifiedIdentityWithShieldedNullifiers`; if drive-abci ever returns a different one the + // broadcast still SUCCEEDED, so we don't turn it into a failed create: we synthesize the + // identity from the derived id + submitted keys (the binding signature committed both) and + // warn, so the local row is still created. + let identity = match proof_result { + StateTransitionProofResult::VerifiedIdentityWithShieldedNullifiers( + mut identity, + _nullifiers, + ) => { + // The proof-verified id is authoritative: it's recomputed from the proven nullifier + // set, while `identity_id` was derived pre-broadcast. They should match (the derived + // id is committed in the sighash), but trust the verified one. + if identity.id() != identity_id { + warn!( + derived_id = %identity_id, + verified_id = %identity.id(), + "IdentityCreateFromShieldedPool: derived id differs from proof-verified id; \ + using the proof-verified id" + ); + } + // Defensive: a proof result can hand back an identity whose `public_keys` map is + // empty. Fill it from the submitted set so downstream auth-key checks see the keys + // immediately without waiting for the next identity-fetch round (the transition + // committed exactly these keys, so id reproducibility is preserved). + if identity.public_keys().is_empty() { + identity.set_public_keys(submitted_public_keys); + } + identity + } + other => { + warn!( + derived_id = %identity_id, + result = %other, + "IdentityCreateFromShieldedPool: unexpected proof-result variant; synthesizing \ + the identity from the derived id + submitted keys so the local row still lands" + ); + // The create executed. An identity that cannot be synthesized leaves it + // unconfirmed, its notes and record kept for the next sync, never failed. + Identity::new_with_id_and_keys(identity_id, submitted_public_keys, sdk.version()) + .map_err(|e| { + unconfirmed(format!( + "its result was proved, but the identity could not be read from it: {e}" + )) + })? + } + }; + + Ok((identity.id(), identity)) } /// Number of times [`identity_create_from_shielded_pool`] re-fetches the new identity by its @@ -3456,12 +3496,12 @@ async fn mark_notes_spent( /// and proceed to build a duplicate proof that's only rejected /// ~30 s later at broadcast time. /// -/// The reservation is in-memory only — see -/// [`ShieldedStore::mark_pending`] for the crash-recovery note. -/// Callers must pair this with [`finalize_pending`] (on -/// broadcast success) or [`NoteReservation::cancel`] (on failure) so the -/// reservation is always released; until they hand it over -/// ([`NoteReservation::hand_over`]), the returned guard releases it when +/// The reservation is held in memory until the spend saves its record +/// ([`save_spend_then_broadcast`]), which restores it after a restart: see +/// [`ShieldedStore::mark_pending`]. Callers must pair this with +/// [`finalize_pending`] (on proven execution) or [`settle_failed_spend`] +/// (on failure); until the notes are handed over +/// ([`NoteReservation::hand_over`]), the returned guard releases them when /// the spend is dropped. async fn reserve_unspent_notes( sdk: &Arc, @@ -3749,19 +3789,14 @@ async fn arm_pending_release( Ok(true) } -/// Maximum sync-time re-broadcast attempts for a -/// broadcast-accepted-but-unconfirmed spend before the re-drive stops -/// and the anchor-prune release backstop owns the reservation. +/// Maximum sync-time re-broadcast attempts for a spend whose outcome is +/// not known before the re-drive stops and the anchor-prune release +/// backstop owns the reservation. pub(super) const MAX_REDRIVE_ATTEMPTS: u32 = 3; -/// Broadcast a built shielded spend and, on the AMBIGUOUS outcome only -/// (`ShieldedSpendUnconfirmed` — accepted broadcast, failed result -/// wait), persist a [`PendingRedrive`] so the sync-time re-drive can -/// resolve the ambiguity actively: the next scan detects a landing via -/// the nullifiers; otherwise the byte-identical transition is -/// re-broadcast up to [`MAX_REDRIVE_ATTEMPTS`] times (fund-safe — -/// identical nullifiers cannot double-spend); only if every attempt -/// stays silent does the anchor-prune release backstop take over. +/// Save a built shielded spend's recovery record, broadcast it and wait for +/// its result ([`broadcast_shielded_spend_with_redrive_with_metadata`]), +/// returning the proven result without its metadata. #[allow(clippy::too_many_arguments)] async fn broadcast_shielded_spend_with_redrive( sdk: &Arc, @@ -3771,10 +3806,11 @@ async fn broadcast_shielded_spend_with_redrive( anchor: [u8; 32], anchor_height: u64, notes: &[ShieldedNote], + reservation: &mut NoteReservation, state_transition: &StateTransition, operation: &'static str, wait: SpendResultWait, -) -> Result { +) -> Result { broadcast_shielded_spend_with_redrive_with_metadata( sdk, store, @@ -3783,6 +3819,7 @@ async fn broadcast_shielded_spend_with_redrive( anchor, anchor_height, notes, + reservation, state_transition, operation, wait, @@ -3791,6 +3828,17 @@ async fn broadcast_shielded_spend_with_redrive( .map(|(result, _)| result) } +/// Save a built shielded spend's recovery record ([`PendingRedrive`]) +/// durably, then broadcast it and wait for its result +/// ([`save_spend_then_broadcast`], [`broadcast_shielded_spend_classified`]). +/// +/// The record is what resolves a spend whose outcome is not known: the next +/// scan detects a landing via the nullifiers; otherwise the byte-identical +/// transition is re-broadcast up to [`MAX_REDRIVE_ATTEMPTS`] times +/// (identical nullifiers cannot be spent twice); only if every attempt stays +/// silent does the anchor-prune release backstop take over. Saved before the +/// first dispatch, it also covers a process that exits during the dispatches +/// or the result wait: a restart restores the notes' reservation from it. #[allow(clippy::too_many_arguments)] async fn broadcast_shielded_spend_with_redrive_with_metadata( sdk: &Arc, @@ -3800,87 +3848,237 @@ async fn broadcast_shielded_spend_with_redrive_with_metadata( anchor: [u8; 32], anchor_height: u64, notes: &[ShieldedNote], + reservation: &mut NoteReservation, state_transition: &StateTransition, operation: &'static str, wait: SpendResultWait, -) -> Result<(StateTransitionProofResult, ResponseMetadata), PlatformWalletError> { - let result = broadcast_shielded_spend(sdk, state_transition, operation, wait).await; - if matches!( - &result, - Err(PlatformWalletError::ShieldedSpendUnconfirmed { .. }) - ) { - arm_redrive_record( - store, - id, - pending_entry, - anchor, - anchor_height, - notes, - state_transition, - operation, - ) - .await; - } - result +) -> Result<(StateTransitionProofResult, ResponseMetadata), SpendFailure> { + save_spend_then_broadcast( + store, + id, + pending_entry, + anchor, + anchor_height, + notes, + reservation, + state_transition, + operation, + || broadcast_shielded_spend_classified(sdk, state_transition, operation, wait), + ) + .await } -/// Save the re-drivable record of a spend durably before it is broadcast, -/// as identity-funded shields arm theirs: an exit after the node admitted -/// the transition, before its result returns, leaves the record. The record -/// is keyed by the spend's `activity_id` and carries its `nullifiers`, and -/// the private contact request the spend pays for when it does. A spend -/// paying for one is a private document create (type 29), and the private -/// payment journal keeps a record of each entry it appends, read from the -/// transition, in the same durable write ([`ShieldedStore::arm_private_contact_payment`]). -/// A spend whose record cannot be saved, or whose entries do not read, is -/// refused before anything is broadcast, as the unknown outcome could then -/// not be recovered. `payment_started`, when given, is marked right after -/// the record is saved, under the same store lock: dropped while it waits -/// for the lock, the spend leaves neither a record nor a mark. -/// `anchor_recorded_at` is the proved height of the recorded-anchor set the -/// spend's anchor was chosen from, kept in the journal record: an expiry -/// proof needs the anchor absent from a set proved at or above it. +/// Save the recovery record of the built note-consuming spend +/// `state_transition` durably, hand its notes over, and only then run +/// `broadcast`, which sends it and waits for its result: the production flows +/// pass their classified broadcast, a test intercepts it. +/// +/// Each of `notes`' reservations first carries the spend's `anchor` +/// ([`arm_pending_release`]), so a pruned anchor releases it; the record is +/// then saved, keyed by `pending_entry` ([`arm_redrive_before_broadcast`]). A +/// spend with no entry to key its record by, or whose record cannot be saved, +/// is refused with nothing broadcast, and `reservation` still owns the notes: +/// the caller releases them ([`settle_failed_spend`]), and so does a spend +/// dropped while a save waits for the store. +/// +/// Once the record is saved the notes are handed over, with nothing awaited +/// in between: from then on they belong to the spend's resolution, whatever +/// happens to this call. An exit or a drop during the dispatches or the +/// result wait leaves the reservation and the record, which a restart +/// restores and the redrive pass resolves. #[allow(clippy::too_many_arguments)] -pub(crate) async fn arm_redrive_before_broadcast( +async fn save_spend_then_broadcast( store: &Arc>, id: SubwalletId, - activity_id: Option<[u8; 32]>, + pending_entry: &Option, anchor: [u8; 32], - nullifiers: Vec<[u8; 32]>, + anchor_height: u64, + notes: &[ShieldedNote], + reservation: &mut NoteReservation, state_transition: &StateTransition, operation: &'static str, - private_contact: Option, - payment_started: Option<&PaymentStarted>, - anchor_recorded_at: u64, -) -> Result<(), PlatformWalletError> { - use dpp::serialization::PlatformSerializable; - - let activity_id = activity_id.ok_or_else(|| { - PlatformWalletError::ShieldedBuildError(format!( - "{operation}: no activity entry keys the record of this spend, so it is not \ - broadcast" - )) - })?; - let st_bytes = state_transition.serialize_to_bytes().map_err(|e| { - PlatformWalletError::ShieldedBuildError(format!( - "{operation}: the transition does not serialize for its record, so it is not \ - broadcast: {e}" - )) - })?; - let journal = match private_contact { - Some(payment) => Some(( - payment, - private_document_entries(state_transition).ok_or_else(|| { - PlatformWalletError::ShieldedBuildError(format!( - "{operation}: the entries this private contact request payment appends do \ - not read, so it is not broadcast" - )) - })?, - )), - None => None, - }; - let redrive = PendingRedrive { - activity_id, + broadcast: B, +) -> Result +where + S: ShieldedStore, + B: FnOnce() -> Fut, + Fut: Future>, +{ + arm_pending_release(store, id, anchor, anchor_height, pending_entry, notes).await?; + arm_redrive_before_broadcast( + store, + id, + pending_entry.as_ref().map(|entry| entry.id), + anchor, + notes.iter().map(|note| note.nullifier).collect(), + state_transition, + operation, + None, + None, + anchor_height, + ) + .await?; + // Saved: the notes are the spend's resolution's from here on. + reservation.hand_over(); + broadcast().await +} + +/// Settle the notes, saved record and activity row of a note-consuming spend +/// (transfer, unshield, withdrawal, identity top-up, identity create) that +/// ended with `failure`, and return the error it reports. +/// +/// - Its transition never left the wallet ([`SpendFailure::never_delivered`]: +/// refused before anything was sent), so nothing can execute it: its record +/// is retired and its notes are released under one store guard +/// ([`NoteReservation::retire_undelivered`]), and the activity row reads +/// failed. When the record cannot be retired (a redrive pass claimed a +/// re-broadcast of it meanwhile, or the write failed), the transition may +/// leave the wallet after all: everything stays and the spend reads as +/// unconfirmed. +/// - Its record was saved (`reservation` is handed over, +/// [`save_spend_then_broadcast`]) and a dispatch may have reached a node: +/// it may execute. The notes stay reserved and the record stays, for the +/// scan and the redrive pass to resolve, and the activity row stays +/// pending. It reads as unconfirmed, whatever error ended it. +/// - It failed before its record was saved: nothing was broadcast. The notes +/// are released and the activity row reads failed. +#[allow(clippy::too_many_arguments)] +async fn settle_failed_spend( + store: &Arc>, + persister: Option<&WalletPersister>, + wallet_id: WalletId, + id: SubwalletId, + pending_entry: &Option, + mut reservation: NoteReservation, + operation: &'static str, + failure: SpendFailure, +) -> PlatformWalletError { + let SpendFailure { + error, + never_delivered, + } = failure; + if never_delivered { + let retired = match pending_entry.as_ref().map(|entry| entry.id) { + Some(activity_id) => reservation.retire_undelivered(&activity_id, &[]).await, + None => { + reservation.hand_over(); + false + } + }; + if !retired { + return PlatformWalletError::ShieldedSpendUnconfirmed { + operation, + reason: format!( + "its broadcast was refused before delivery ({error}), but its saved \ + transition was claimed for a re-broadcast or could not be retired" + ), + }; + } + record_activity_status( + store, + persister, + wallet_id, + id, + pending_entry, + ShieldedActivityStatus::Failed, + None, + ) + .await; + return error; + } + if reservation.handed_over { + return match error { + unconfirmed @ (PlatformWalletError::ShieldedSpendUnconfirmed { .. } + | PlatformWalletError::ShieldedBroadcastUnconfirmed { .. }) => unconfirmed, + other => { + // The reported error keeps the cause's text alone: its type + // goes to the log. + warn!( + account = id.account_index, + operation, + cause = ?other, + "Shielded spend ended with its record saved; reporting it unconfirmed" + ); + PlatformWalletError::ShieldedSpendUnconfirmed { + operation, + reason: other.to_string(), + } + } + }; + } + // The guard owns the notes until they are released, so a drop on the + // way still releases them. + record_activity_status( + store, + persister, + wallet_id, + id, + pending_entry, + ShieldedActivityStatus::Failed, + None, + ) + .await; + reservation.cancel().await; + error +} + +/// Save the re-drivable record of a spend durably before it is broadcast, +/// as identity-funded shields arm theirs: an exit after the node admitted +/// the transition, before its result returns, leaves the record. The record +/// is keyed by the spend's `activity_id` and carries its `nullifiers`, and +/// the private contact request the spend pays for when it does. A spend +/// paying for one is a private document create (type 29), and the private +/// payment journal keeps a record of each entry it appends, read from the +/// transition, in the same durable write ([`ShieldedStore::arm_private_contact_payment`]). +/// A spend whose record cannot be saved, or whose entries do not read, is +/// refused before anything is broadcast, as the unknown outcome could then +/// not be recovered. `payment_started`, when given, is marked right after +/// the record is saved, under the same store lock: dropped while it waits +/// for the lock, the spend leaves neither a record nor a mark. +/// `anchor_recorded_at` is the proved height of the recorded-anchor set the +/// spend's anchor was chosen from, kept in the journal record: an expiry +/// proof needs the anchor absent from a set proved at or above it. +#[allow(clippy::too_many_arguments)] +pub(crate) async fn arm_redrive_before_broadcast( + store: &Arc>, + id: SubwalletId, + activity_id: Option<[u8; 32]>, + anchor: [u8; 32], + nullifiers: Vec<[u8; 32]>, + state_transition: &StateTransition, + operation: &'static str, + private_contact: Option, + payment_started: Option<&PaymentStarted>, + anchor_recorded_at: u64, +) -> Result<(), PlatformWalletError> { + use dpp::serialization::PlatformSerializable; + + let activity_id = activity_id.ok_or_else(|| { + PlatformWalletError::ShieldedBuildError(format!( + "{operation}: no activity entry keys the record of this spend, so it is not \ + broadcast" + )) + })?; + let st_bytes = state_transition.serialize_to_bytes().map_err(|e| { + PlatformWalletError::ShieldedBuildError(format!( + "{operation}: the transition does not serialize for its record, so it is not \ + broadcast: {e}" + )) + })?; + let journal = match private_contact { + Some(payment) => Some(( + payment, + private_document_entries(state_transition).ok_or_else(|| { + PlatformWalletError::ShieldedBuildError(format!( + "{operation}: the entries this private contact request payment appends do \ + not read, so it is not broadcast" + )) + })?, + )), + None => None, + }; + let redrive = PendingRedrive { + activity_id, anchor, nullifiers, st_bytes, @@ -3995,58 +4193,6 @@ pub(crate) fn private_document_commitments( .collect() } -/// Persist the re-drivable record for an ambiguous spend. Best-effort: -/// a failure here only demotes the resolution path to the anchor-prune -/// backstop (plus restart-loss of the reservation), never fails the -/// spend call itself — the ambiguity already happened. -#[allow(clippy::too_many_arguments)] -async fn arm_redrive_record( - store: &Arc>, - id: SubwalletId, - pending_entry: &Option, - anchor: [u8; 32], - anchor_height: u64, - notes: &[ShieldedNote], - state_transition: &StateTransition, - operation: &'static str, -) { - use dpp::serialization::PlatformSerializable; - - let Some(entry) = pending_entry else { - return; - }; - let st_bytes = match state_transition.serialize_to_bytes() { - Ok(b) => b, - Err(e) => { - warn!( - operation, - error = %e, - "failed to serialize the unconfirmed transition; re-drive disabled for this \ - spend (prune backstop still applies)" - ); - return; - } - }; - let redrive = PendingRedrive { - activity_id: entry.id, - anchor, - nullifiers: notes.iter().map(|n| n.nullifier).collect(), - st_bytes, - attempts: 0, - identity_nonce_finalized: false, - identity_user_abandoned: false, - anchor_height: Some(anchor_height), - }; - if let Err(e) = store.write().await.arm_redrive(id, redrive) { - warn!( - operation, - error = %e, - "failed to persist the redrive record; re-drive disabled for this spend (prune \ - backstop still applies)" - ); - } -} - /// Whether an SDK error is Platform's `NullifierAlreadySpentError` — /// on a RE-broadcast of our own byte-identical transition this means /// the ORIGINAL broadcast executed: the nullifiers are consumed by the @@ -4387,36 +4533,8 @@ pub(super) async fn redrive_pending_spends( } } -/// Broadcast a built shielded spend transition (unshield / transfer / -/// withdraw) and wait for proven execution, staging the two SDK calls -/// separately so the caller's reservation rollback only runs when the -/// spend DEFINITIVELY did not happen: -/// -/// - a definitive `broadcast()` failure ([`broadcast_definitely_failed`]: -/// a consensus-verdict CheckTx rejection, or a transport failure that -/// proves nothing was delivered), or a wait-stage consensus rejection -/// (Platform ran the transition and rejected it on its merits — see -/// [`carries_consensus_rejection`]), means the spend never executed → -/// [`PlatformWalletError::ShieldedBroadcastFailed`], and the caller -/// releases the note reservations via [`NoteReservation::cancel`]; -/// - a no-verdict `broadcast()` failure (`AlreadyExists` proves the tx IS -/// in the mempool after a lost-ACK retry; timeouts merely allow it) -/// falls through to the result wait, which either proves execution or -/// classifies the residual ambiguity; -/// - any other wait failure (transport error, timeout, result-proof -/// fetch/verify error, …) is AMBIGUOUS — the relay accepted (or may -/// have accepted) the tx and it may well have executed → -/// [`PlatformWalletError::ShieldedSpendUnconfirmed`], and the caller -/// must leave the reservations in place (each spend flow's outer -/// match has a dedicated arm for this). -/// -/// Mirrors the staging in [`identity_create_from_shielded_pool`], minus -/// its fetch-by-derived-id fallback: a spend leaves no artifact as -/// cheaply queryable as an identity row, so ambiguity is surfaced -/// directly and reconciled by the next nullifier sync. The proven -/// result is discarded; only the confirmation matters. -/// How [`broadcast_shielded_spend`] waits for an already-broadcast spend's -/// result, mirroring the verifier's classification of the family. +/// How [`broadcast_shielded_spend_classified`] waits for an already-broadcast +/// spend's result, mirroring the verifier's classification of the family. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum SpendResultWait { /// The family is classified execution-proving (transfer, unshield, @@ -4429,19 +4547,10 @@ enum SpendResultWait { AffectedState, } -async fn broadcast_shielded_spend( - sdk: &Arc, - state_transition: &StateTransition, - operation: &'static str, - wait: SpendResultWait, -) -> Result<(StateTransitionProofResult, ResponseMetadata), PlatformWalletError> { - broadcast_shielded_spend_classified(sdk, state_transition, operation, wait) - .await - .map_err(|failure| failure.error) -} - -/// A failed [`broadcast_shielded_spend_classified`]: the error it reports, and -/// whether the transition never left the wallet. +/// A failed note-consuming spend: the error it reports, and whether its +/// transition never left the wallet. Every failure before the broadcast, and +/// every one after a dispatch that may have reached a node, is built from its +/// error alone ([`From`]), with `never_delivered` false. struct SpendFailure { error: PlatformWalletError, /// The broadcast proved nothing was delivered @@ -4459,8 +4568,25 @@ impl From for SpendFailure { } } -/// [`broadcast_shielded_spend`], telling a failure whose transition never -/// left the wallet from one that may have reached the network. +/// Broadcast a built shielded spend transition and wait for its proven +/// result, telling a failure whose transition never left the wallet from one +/// that may have reached the network: +/// +/// - refused before anything was sent ([`BroadcastDelivery::NeverDelivered`]): +/// [`PlatformWalletError::ShieldedBroadcastFailed`], with +/// [`SpendFailure::never_delivered`] set, so the caller retires the saved +/// record and releases the notes; +/// - any dispatch that may have reached a node falls through to the result +/// wait, which either proves the outcome or leaves it unknown; +/// - any wait failure, a consensus verdict included +/// ([`classify_spend_wait_failure`]): +/// [`PlatformWalletError::ShieldedSpendUnconfirmed`], and the caller leaves +/// the reservations and the saved record in place. +/// +/// A spend leaves no artifact as cheaply queryable as the identity row +/// [`broadcast_identity_create`] falls back to, so an unknown outcome is +/// surfaced directly and resolved by the next nullifier sync and the redrive +/// pass. async fn broadcast_shielded_spend_classified( sdk: &Arc, state_transition: &StateTransition, @@ -4516,7 +4642,7 @@ fn definite_broadcast_failure(e: &dash_sdk::Error) -> PlatformWalletError { } /// Classify a `wait_for_response` failure for an already-broadcast -/// shielded spend (see [`broadcast_shielded_spend`]): unconfirmed, whatever +/// shielded spend (see [`broadcast_shielded_spend_classified`]): unconfirmed, whatever /// it is, the notes staying reserved. /// /// A consensus verdict on the wait ([`carries_consensus_rejection`]) is no @@ -4695,6 +4821,7 @@ mod shield_recipient_tests { #[cfg(test)] mod redrive_tests { use super::*; + use crate::broadcast_outcome::test_sdks::{sdk_refusing_connections, sdk_without_addresses}; use crate::wallet::identity::network::PaymentStarted; use crate::wallet::shielded::activity::ShieldedActivityEntry; use crate::wallet::shielded::store::InMemoryShieldedStore; @@ -4714,6 +4841,9 @@ mod redrive_tests { use dpp::state_transition::private_document_create_from_shielded_pool_transition::methods::PrivateDocumentCreateFromShieldedPoolTransitionMethodsV0; use dpp::state_transition::private_document_create_from_shielded_pool_transition::PrivateDocumentCreateFromShieldedPoolTransition; use dpp::state_transition::shield_from_identity_transition::v0::ShieldFromIdentityTransitionV0; + use dpp::state_transition::shield_transition::v0::ShieldTransitionV0; + use dpp::state_transition::shielded_transfer_transition::v0::ShieldedTransferTransitionV0; + use dpp::state_transition::state_transitions::shielded::identity_create_from_shielded_pool_transition::v0::IdentityCreateFromShieldedPoolTransitionV0; use dpp::version::PlatformVersion; use futures::{poll, FutureExt}; use grovedb_commitment_tree::ProvingKey; @@ -6232,95 +6362,1199 @@ mod redrive_tests { assert_eq!(left[0].activity_id, [1; 32]); assert_eq!(left[0].attempts, 1, "claimed once, before its broadcast"); } -} -#[cfg(test)] -mod classify_spend_wait_failure_tests { - use super::*; - use dash_sdk::error::StateTransitionBroadcastError; - use dpp::consensus::basic::decode::ProtocolVersionParsingError; - use dpp::consensus::basic::BasicError; - use dpp::consensus::ConsensusError; + // ── Note-consuming spends: saved before the first dispatch ───────── - fn broadcast_err(cause: Option) -> dash_sdk::Error { - dash_sdk::Error::StateTransitionBroadcastError(StateTransitionBroadcastError { - code: 13, - message: "context deadline exceeded".to_string(), - cause, - }) + /// The anchor the tests' spends are built on, and the proved height of + /// the anchor set it was read from. + const SPEND_ANCHOR: [u8; 32] = [0x6E; 32]; + const SPEND_ANCHOR_HEIGHT: u64 = 5; + + /// The identity the tests' identity create derives. + const CREATED_IDENTITY: [u8; 32] = [0x33; 32]; + + fn spend_action() -> SerializedAction { + SerializedAction { + nullifier: [1; 32], + rk: [2; 32], + cmx: [3; 32], + encrypted_note: vec![4; 216], + cv_net: [5; 32], + spend_auth_sig: [6; 64], + } } - /// A broadcast error carrying a consensus cause comes from an - /// unauthenticated endpoint, with no proof behind it: the spend stays - /// unconfirmed and its reservation stays. - #[test] - fn should_read_a_wait_stage_consensus_verdict_as_unconfirmed() { - let cause = ConsensusError::BasicError(BasicError::ProtocolVersionParsingError( - ProtocolVersionParsingError::new("bad version".to_string()), - )); - let err = classify_spend_wait_failure("unshield", &broadcast_err(Some(cause))); - assert!( - matches!(err, PlatformWalletError::ShieldedSpendUnconfirmed { .. }), - "{err:?}" - ); + /// The note the tests' spends consume. + fn spend_note() -> ShieldedNote { + ShieldedNote { + position: 0, + cmx: [1; 32], + nullifier: [0x5C; 32], + block_height: 1, + is_spent: false, + value: 1_000_000_000_000, + note_data: vec![], + } } - #[test] - fn causeless_broadcast_error_is_ambiguous() { - // DAPI maps its own wait failures (e.g. `DapiError::Timeout`) to a - // `StateTransitionBroadcastError` with EMPTY consensus data, which the - // SDK decodes as `cause: None`. The spend may still execute after the - // wait gave up, so this must NOT release the note reservations. - let err = classify_spend_wait_failure("unshield", &broadcast_err(None)); - assert!( - matches!( - err, - PlatformWalletError::ShieldedSpendUnconfirmed { - operation: "unshield", - .. + /// The note-consuming spends, by the code that saves, broadcasts and + /// waits for them. + #[derive(Clone, Copy, Debug)] + enum SpendPath { + /// Transfer, unshield, withdrawal and identity top-up + /// ([`broadcast_shielded_spend_with_redrive_with_metadata`]): here a + /// transfer. + Shared, + /// Identity create ([`broadcast_identity_create_with_redrive`]). + IdentityCreate, + } + + impl SpendPath { + /// A signed transition of the path, as it saves and broadcasts one. + fn transition(self) -> StateTransition { + match self { + Self::Shared => ShieldedTransferTransitionV0 { + actions: vec![spend_action(), spend_action()], + value_balance: 1_000, + anchor: SPEND_ANCHOR, + proof: vec![8; 64], + binding_signature: [9; 64], } - ), - "got {err:?}" - ); - } + .into(), + Self::IdentityCreate => IdentityCreateFromShieldedPoolTransitionV0 { + public_keys: vec![], + denomination: 1_000_000, + actions: vec![spend_action(), spend_action()], + anchor: SPEND_ANCHOR, + proof: vec![8; 64], + binding_signature: [9; 64], + send_to_address_on_creation_failure: PlatformAddress::P2pkh([7; 20]), + identity_id: Identifier::from(CREATED_IDENTITY), + } + .into(), + } + } - #[test] - fn transport_errors_are_ambiguous() { - let err = classify_spend_wait_failure( - "withdraw", - &dash_sdk::Error::TimeoutReached( - std::time::Duration::from_secs(80), - "waiting for response".to_string(), - ), - ); - assert!(matches!( - err, - PlatformWalletError::ShieldedSpendUnconfirmed { - operation: "withdraw", - .. + /// Save, broadcast and wait for the path's transition on `sdk`, as + /// its production flow does once the transition is built. + async fn broadcast( + self, + sdk: &Arc, + spend: &mut ReservedSpend, + id: SubwalletId, + ) -> Result<(), SpendFailure> { + let transition = self.transition(); + match self { + Self::Shared => broadcast_shielded_spend_with_redrive_with_metadata( + sdk, + &spend.store, + id, + &spend.entry, + SPEND_ANCHOR, + SPEND_ANCHOR_HEIGHT, + &spend.notes, + &mut spend.reservation, + &transition, + "transfer", + SpendResultWait::ExecutionProved, + ) + .await + .map(|_| ()), + Self::IdentityCreate => broadcast_identity_create_with_redrive( + sdk, + &spend.store, + id, + &spend.entry, + SPEND_ANCHOR, + SPEND_ANCHOR_HEIGHT, + &spend.notes, + &mut spend.reservation, + &transition, + Identifier::from(CREATED_IDENTITY), + BTreeMap::new(), + ) + .await + .map(|_| ()), } - )); - } + } - /// The shape a CheckTx rejection takes when it reaches the SDK from - /// `broadcast()`: DAPI re-attaches the serialized consensus error as - /// gRPC metadata and the dapi-client decodes it into - /// `Error::Protocol(ConsensusError)`. - fn consensus_metadata_rejection() -> dash_sdk::Error { + /// Settle the path's failed spend, as its production flow does, and + /// return the error it reports. + async fn settle( + self, + spend: ReservedSpend, + wallet_id: WalletId, + id: SubwalletId, + failure: SpendFailure, + ) -> PlatformWalletError { + let ReservedSpend { + store, + reservation, + entry, + .. + } = spend; + match self { + Self::Shared => { + settle_failed_spend( + &store, + None, + wallet_id, + id, + &entry, + reservation, + "transfer", + failure, + ) + .await + } + Self::IdentityCreate => identity_create_failure( + settle_failed_spend( + &store, + None, + wallet_id, + id, + &entry, + reservation, + IDENTITY_CREATE_OPERATION, + failure, + ) + .await, + Some(Identifier::from(CREATED_IDENTITY)), + ), + } + } + + /// Whether `error` is the path's report of a spend whose outcome is + /// not known. + fn reads_unconfirmed(self, error: &PlatformWalletError) -> bool { + match self { + Self::Shared => matches!( + error, + PlatformWalletError::ShieldedSpendUnconfirmed { + operation: "transfer", + .. + } + ), + Self::IdentityCreate => matches!( + error, + PlatformWalletError::ShieldedBroadcastUnconfirmed { identity_id, .. } + if *identity_id == Identifier::from(CREATED_IDENTITY) + ), + } + } + } + + /// A spend right before it saves its record: its note reserved in a + /// file-backed store, and its pending activity entry recorded. + struct ReservedSpend { + store: Arc>, + notes: Vec, + reservation: NoteReservation, + entry: Option, + } + + impl ReservedSpend { + async fn at(path: &std::path::Path, id: SubwalletId, activity_id: [u8; 32]) -> Self { + let sdk = Arc::new(dash_sdk::Sdk::new_mock()); + let store = Arc::new(RwLock::new( + FileBackedShieldedStore::open_path(path, 100).expect("the store"), + )); + store + .write() + .await + .save_note(id, &spend_note()) + .expect("a note"); + let (notes, _, _, reservation) = + reserve_notes_covering(&sdk, &store, id, 1, 2, ShieldedFeeKind::Base) + .await + .expect("reserved"); + let entry = pending_entry(activity_id); + store + .write() + .await + .save_activity(id, &entry) + .expect("the pending row"); + Self { + store, + notes, + reservation, + entry: Some(entry), + } + } + } + + /// Make the store at `path` refuse to save a spend's record. + fn refuse_record_saves(path: &std::path::Path) { + rusqlite::Connection::open(path) + .expect("the store's file") + .execute_batch( + "CREATE TRIGGER reject_redrive_insert BEFORE INSERT ON \ + shielded_pending_spends BEGIN SELECT RAISE(FAIL, 'injected'); END;", + ) + .expect("the trigger"); + } + + /// The store at `path` as a restart opens it, the wallet's note loaded + /// into it again. + fn restarted_store(path: &std::path::Path, id: SubwalletId) -> FileBackedShieldedStore { + let mut store = FileBackedShieldedStore::open_path(path, 100).expect("reopened"); + store + .save_note(id, &spend_note()) + .expect("the note, loaded again"); + store + } + + /// How many notes of `id` a spend can select, and the status of the + /// activity row `activity_id`. + async fn spendable_and_status( + store: &Arc>, + id: SubwalletId, + activity_id: &[u8; 32], + ) -> (usize, ShieldedActivityStatus) { + let store = store.read().await; + ( + store.get_unspent_notes(id).expect("notes").len(), + store + .get_activity_by_entry_id(id, activity_id) + .expect("the row reads") + .expect("the row") + .status, + ) + } + + /// A note-consuming spend saves its record durably before its first + /// dispatch, and hands its notes over only then. So a process that exits + /// between the broadcast and the result (here the spend is dropped while + /// its result wait is pending, and nothing settles it) leaves the record: + /// the store a restart opens holds the notes' reservation and the exact + /// signed transition, the redrive pass re-broadcasts it, and the scan + /// that sees its nullifier spent resolves it. + #[tokio::test] + async fn should_restore_a_spend_that_exited_between_its_broadcast_and_its_result() { + use dash_sdk::platform::transition::broadcast_request::BroadcastRequestForStateTransition; + use std::task::{Context, Waker}; + + let mut sdk = dash_sdk::SdkBuilder::new_mock().build().expect("mock sdk"); + let sdk_handle = Arc::new(sdk.clone()); + let id = SubwalletId::new([0x71; 32], 0); + let activity_id = [0x7A; 32]; + let dir = tempfile::tempdir().expect("a directory"); + let path = dir.path().join("tree.sqlite"); + let ReservedSpend { + store, + notes, + mut reservation, + entry, + } = ReservedSpend::at(&path, id, activity_id).await; + let transition = SpendPath::Shared.transition(); + let signed = transition.serialize_to_bytes().expect("serializes"); + + let mut cx = Context::from_waker(Waker::noop()); + let mut spend = Box::pin(save_spend_then_broadcast( + &store, + id, + &entry, + SPEND_ANCHOR, + SPEND_ANCHOR_HEIGHT, + ¬es, + &mut reservation, + &transition, + "transfer", + || { + // Nothing is dispatched before the record is on the file. + let durable = + FileBackedShieldedStore::open_path(&path, 100).expect("a second handle"); + let saved = durable.pending_redrives(id).expect("the records"); + assert_eq!(saved.len(), 1, "saved before the first dispatch"); + assert_eq!(saved[0].st_bytes, signed); + // Dispatched; its result never comes. + std::future::pending::>() + }, + )); + assert!( + spend.as_mut().poll(&mut cx).is_pending(), + "broadcast, waiting for its result" + ); + // The process exits here: the spend never returns, nothing settles it. + drop(spend); + drop(reservation); + assert!( + store + .read() + .await + .get_unspent_notes(id) + .expect("notes") + .is_empty(), + "the dropped spend's notes stay reserved" + ); + drop(store); + + let restarted = Arc::new(RwLock::new(restarted_store(&path, id))); + { + let store = restarted.read().await; + assert!( + store.get_unspent_notes(id).expect("notes").is_empty(), + "the reservation is restored from the record" + ); + let saved = store.pending_redrives(id).expect("the records"); + assert_eq!(saved.len(), 1); + assert_eq!(saved[0].st_bytes, signed, "the exact signed transition"); + assert_eq!(saved[0].nullifiers, vec![spend_note().nullifier]); + assert_eq!(saved[0].anchor, SPEND_ANCHOR); + assert_eq!(saved[0].anchor_height, Some(SPEND_ANCHOR_HEIGHT)); + assert_eq!(saved[0].attempts, 0); + } + + let recorded = [SPEND_ANCHOR].into_iter().collect(); + redrive_pending_spends( + &sdk_handle, + &restarted, + id, + &recorded, + &CancellationToken::new(), + ) + .await; + let request = transition + .broadcast_request_for_state_transition() + .expect("serializes"); + assert!( + sdk.mock().request_count(&request).await > 0, + "the redrive pass re-broadcasts the saved transition" + ); + assert_eq!( + restarted + .read() + .await + .pending_redrives(id) + .expect("records")[0] + .attempts, + 1 + ); + + // The next scan sees the spend's nullifier on chain. + assert!(restarted + .write() + .await + .mark_spent(id, &spend_note().nullifier) + .expect("marked")); + drop(restarted); + assert!( + FileBackedShieldedStore::open_path(&path, 100) + .expect("reopened") + .pending_redrives(id) + .expect("records") + .is_empty(), + "resolved for good" + ); + } + + /// A failed spend is settled by what is known about its transition. One + /// that never left the wallet has its record retired and its notes + /// released together, unless a redrive pass claimed a re-broadcast of the + /// record meanwhile: it may then leave the wallet after all, and is kept + /// as unconfirmed. One whose record was saved and that may have reached a + /// node keeps its notes and its record whatever error ended it, and reads + /// as unconfirmed. One whose record could not be saved was never + /// dispatched, and releases its notes. + #[tokio::test] + async fn should_release_a_failed_spend_s_notes_only_when_its_transition_cannot_execute() { + use std::sync::atomic::{AtomicBool, Ordering}; + + let wallet_id = [0x72; 32]; + let id = SubwalletId::new(wallet_id, 0); + let activity_id = [0x7B; 32]; + let transition = SpendPath::Shared.transition(); + let never_delivered = || SpendFailure { + error: PlatformWalletError::ShieldedBroadcastFailed("no address".to_string()), + never_delivered: true, + }; + for outcome in [ + "never delivered", + "never delivered, re-broadcast claimed", + "unconfirmed", + "failed after its record was saved", + "its record could not be saved", + ] { + let dir = tempfile::tempdir().expect("a directory"); + let path = dir.path().join("tree.sqlite"); + let mut spend = ReservedSpend::at(&path, id, activity_id).await; + if outcome == "its record could not be saved" { + refuse_record_saves(&path); + } + let dispatched = AtomicBool::new(false); + let store = Arc::clone(&spend.store); + let result: Result<(), SpendFailure> = save_spend_then_broadcast( + &spend.store, + id, + &spend.entry, + SPEND_ANCHOR, + SPEND_ANCHOR_HEIGHT, + &spend.notes, + &mut spend.reservation, + &transition, + "transfer", + || async { + dispatched.store(true, Ordering::SeqCst); + Err(match outcome { + "never delivered" => never_delivered(), + "never delivered, re-broadcast claimed" => { + // A redrive pass re-broadcast the saved record + // while the spend's own broadcast ran. + store + .write() + .await + .bump_redrive_attempts(id, &activity_id) + .expect("claimed"); + never_delivered() + } + "unconfirmed" => PlatformWalletError::ShieldedSpendUnconfirmed { + operation: "transfer", + reason: "the result wait timed out".to_string(), + } + .into(), + _ => PlatformWalletError::ShieldedBuildError( + "its proved result did not read".to_string(), + ) + .into(), + }) + }, + ) + .await; + let failure = result.expect_err("the spend failed"); + let store = Arc::clone(&spend.store); + let settled = SpendPath::Shared + .settle(spend, wallet_id, id, failure) + .await; + let (spendable, status) = spendable_and_status(&store, id, &activity_id).await; + drop(store); + let saved = FileBackedShieldedStore::open_path(&path, 100) + .expect("reopened") + .pending_redrives(id) + .expect("records"); + match outcome { + "never delivered" => { + assert!( + matches!(settled, PlatformWalletError::ShieldedBroadcastFailed(_)), + "{outcome}: {settled:?}" + ); + assert_eq!(spendable, 1, "{outcome}: the notes are released"); + assert!(saved.is_empty(), "{outcome}: the record is retired"); + assert_eq!(status, ShieldedActivityStatus::Failed, "{outcome}"); + } + "its record could not be saved" => { + assert!( + matches!(settled, PlatformWalletError::ShieldedStoreError(_)), + "{outcome}: {settled:?}" + ); + assert!(!dispatched.load(Ordering::SeqCst), "never dispatched"); + assert_eq!(spendable, 1, "{outcome}: the notes are released"); + assert!(saved.is_empty(), "{outcome}"); + assert_eq!(status, ShieldedActivityStatus::Failed, "{outcome}"); + } + _ => { + assert!( + SpendPath::Shared.reads_unconfirmed(&settled), + "{outcome}: {settled:?}" + ); + assert_eq!(spendable, 0, "{outcome}: the notes stay reserved"); + assert_eq!(saved.len(), 1, "{outcome}: the record stays"); + assert_eq!(status, ShieldedActivityStatus::Pending, "{outcome}"); + } + } + } + } + + /// Each note-consuming spend path, on an SDK whose node answers every + /// request with an error: a dispatch may have reached the node, so the + /// spend is unconfirmed, never failed. Its notes stay reserved and its + /// record stays, across a restart too, where the redrive pass + /// re-broadcasts the exact signed transition and the scan that sees its + /// nullifier spent resolves it. + #[tokio::test(start_paused = true)] + async fn should_keep_a_spend_that_may_have_reached_a_node_until_it_resolves() { + use dash_sdk::platform::transition::broadcast_request::BroadcastRequestForStateTransition; + + let wallet_id = [0x73; 32]; + let id = SubwalletId::new(wallet_id, 0); + let activity_id = [0x7C; 32]; + for spend_path in [SpendPath::Shared, SpendPath::IdentityCreate] { + let mut sdk = dash_sdk::SdkBuilder::new_mock().build().expect("mock sdk"); + let sdk_handle = Arc::new(sdk.clone()); + let dir = tempfile::tempdir().expect("a directory"); + let path = dir.path().join("tree.sqlite"); + let mut spend = ReservedSpend::at(&path, id, activity_id).await; + let transition = spend_path.transition(); + let request = transition + .broadcast_request_for_state_transition() + .expect("serializes"); + + let failure = spend_path + .broadcast(&sdk_handle, &mut spend, id) + .await + .expect_err("its result is not proved"); + assert!(!failure.never_delivered, "{spend_path:?}"); + let dispatches = sdk.mock().request_count(&request).await; + assert!(dispatches > 0, "{spend_path:?}: it was dispatched"); + let store = Arc::clone(&spend.store); + let settled = spend_path.settle(spend, wallet_id, id, failure).await; + assert!( + spend_path.reads_unconfirmed(&settled), + "{spend_path:?}: {settled:?}" + ); + assert_eq!( + spendable_and_status(&store, id, &activity_id).await, + (0, ShieldedActivityStatus::Pending), + "{spend_path:?}: the notes stay reserved, the row pending" + ); + drop(store); + + let restarted = Arc::new(RwLock::new(restarted_store(&path, id))); + { + let store = restarted.read().await; + assert!( + store.get_unspent_notes(id).expect("notes").is_empty(), + "{spend_path:?}: the reservation is restored from the record" + ); + let saved = store.pending_redrives(id).expect("the records"); + assert_eq!(saved.len(), 1, "{spend_path:?}"); + assert_eq!( + saved[0].st_bytes, + transition.serialize_to_bytes().expect("serializes"), + "{spend_path:?}: the exact signed transition" + ); + } + let recorded = [SPEND_ANCHOR].into_iter().collect(); + redrive_pending_spends( + &sdk_handle, + &restarted, + id, + &recorded, + &CancellationToken::new(), + ) + .await; + assert!( + sdk.mock().request_count(&request).await > dispatches, + "{spend_path:?}: the redrive pass re-broadcasts it" + ); + assert!(restarted + .write() + .await + .mark_spent(id, &spend_note().nullifier) + .expect("marked")); + assert!( + restarted + .read() + .await + .pending_redrives(id) + .expect("records") + .is_empty(), + "{spend_path:?}: resolved once its nullifier is seen spent" + ); + } + } + + /// Each note-consuming spend path, on an SDK with no address to send to: + /// the transition never left the wallet. Its record was saved before the + /// dispatch that was refused; the settlement retires it and frees the + /// notes, and the spend reads as failed. + #[tokio::test] + async fn should_retire_the_record_of_a_spend_that_never_left_the_wallet() { + let wallet_id = [0x74; 32]; + let id = SubwalletId::new(wallet_id, 0); + let activity_id = [0x7D; 32]; + for spend_path in [SpendPath::Shared, SpendPath::IdentityCreate] { + let sdk = Arc::new(sdk_without_addresses()); + let dir = tempfile::tempdir().expect("a directory"); + let path = dir.path().join("tree.sqlite"); + let mut spend = ReservedSpend::at(&path, id, activity_id).await; + + let failure = spend_path + .broadcast(&sdk, &mut spend, id) + .await + .expect_err("nothing to send it to"); + assert!( + failure.never_delivered, + "{spend_path:?}: {:?}", + failure.error + ); + let store = Arc::clone(&spend.store); + assert_eq!( + store + .read() + .await + .pending_redrives(id) + .expect("records") + .len(), + 1, + "{spend_path:?}: its record was saved before its dispatch" + ); + let settled = spend_path.settle(spend, wallet_id, id, failure).await; + assert!( + matches!(settled, PlatformWalletError::ShieldedBroadcastFailed(_)), + "{spend_path:?}: {settled:?}" + ); + assert_eq!( + spendable_and_status(&store, id, &activity_id).await, + (1, ShieldedActivityStatus::Failed), + "{spend_path:?}: the notes are free, the row failed" + ); + drop(store); + assert!( + FileBackedShieldedStore::open_path(&path, 100) + .expect("reopened") + .pending_redrives(id) + .expect("records") + .is_empty(), + "{spend_path:?}: no record is left" + ); + } + } + + /// Each note-consuming spend path whose record cannot be saved dispatches + /// nothing: the spend is refused, and its notes are released. + #[tokio::test] + async fn should_not_dispatch_a_spend_whose_record_cannot_be_saved() { + use dash_sdk::platform::transition::broadcast_request::BroadcastRequestForStateTransition; + + let wallet_id = [0x75; 32]; + let id = SubwalletId::new(wallet_id, 0); + let activity_id = [0x7E; 32]; + for spend_path in [SpendPath::Shared, SpendPath::IdentityCreate] { + let mut sdk = dash_sdk::SdkBuilder::new_mock().build().expect("mock sdk"); + let sdk_handle = Arc::new(sdk.clone()); + let dir = tempfile::tempdir().expect("a directory"); + let path = dir.path().join("tree.sqlite"); + let mut spend = ReservedSpend::at(&path, id, activity_id).await; + refuse_record_saves(&path); + + let failure = spend_path + .broadcast(&sdk_handle, &mut spend, id) + .await + .expect_err("its record is not saved"); + assert!( + matches!(failure.error, PlatformWalletError::ShieldedStoreError(_)), + "{spend_path:?}: {:?}", + failure.error + ); + let request = spend_path + .transition() + .broadcast_request_for_state_transition() + .expect("serializes"); + assert_eq!( + sdk.mock().request_count(&request).await, + 0, + "{spend_path:?}: nothing was dispatched" + ); + let store = Arc::clone(&spend.store); + let settled = spend_path.settle(spend, wallet_id, id, failure).await; + assert!( + matches!(settled, PlatformWalletError::ShieldedStoreError(_)), + "{spend_path:?}: {settled:?}" + ); + assert_eq!( + spendable_and_status(&store, id, &activity_id).await, + (1, ShieldedActivityStatus::Failed), + "{spend_path:?}: the notes are free, the row failed" + ); + } + } + + // ── Shields from Platform addresses ──────────────────────────────── + + /// A signed shield from a Platform address (type 15). + fn shield_transition() -> StateTransition { + ShieldTransitionV0 { + inputs: BTreeMap::from([(SHIELD_INPUT, (SHIELD_NONCE, 2_000_000))]), + actions: vec![spend_action(), spend_action()], + amount: 1_000_000, + anchor: SPEND_ANCHOR, + proof: vec![8; 64], + binding_signature: [9; 64], + fee_strategy: vec![AddressFundsFeeStrategyStep::DeductFromInput(0)], + user_fee_increase: 0, + input_witnesses: vec![], + } + .into() + } + + /// A node's refusal of a dispatch, as an offline or overloaded endpoint + /// answers one. + fn unavailable() -> dash_sdk::Error { + use dash_sdk::dapi_client::transport::TransportError; + use dash_sdk::dapi_client::DapiClientError; + use dash_sdk::dapi_grpc::tonic::{Code, Status}; + + dash_sdk::Error::DapiClientError(DapiClientError::Transport(TransportError::Grpc( + Status::new(Code::Unavailable, "test"), + ))) + } + + /// A stale-nonce verdict on the shield's input, as a broadcast or as the + /// result wait returns one. + fn nonce_verdict(on_the_wait: bool) -> dash_sdk::Error { + use dpp::consensus::state::address_funds::AddressInvalidNonceError; + + let verdict = ConsensusError::StateError(StateError::AddressInvalidNonceError( + AddressInvalidNonceError::new(PlatformAddress::P2pkh([7; 20]), 1, 2), + )); + if on_the_wait { + dash_sdk::Error::StateTransitionBroadcastError(StateTransitionBroadcastError { + code: 1, + message: "rejected".to_string(), + cause: Some(verdict), + }) + } else { + dash_sdk::Error::Protocol(dpp::ProtocolError::ConsensusError(Box::new(verdict))) + } + } + + fn wait_timeout() -> dash_sdk::Error { + dash_sdk::Error::TimeoutReached(std::time::Duration::from_secs(80), "waiting".to_string()) + } + + /// The input address of [`shield_transition`] and the nonce it signed. + const SHIELD_INPUT: PlatformAddress = PlatformAddress::P2pkh([7; 20]); + const SHIELD_NONCE: AddressNonce = 1; + + /// What [`shield_transition`] signed: its input addresses and nonces. + fn shield_inputs() -> BTreeMap { + shield_transition() + .inputs() + .expect("a shield spends from addresses") + .clone() + } + + /// A verified result reading the shield's input address at `nonce`, or + /// with no state when `None`. + fn input_snapshot(nonce: Option) -> StateTransitionProofResult { + StateTransitionProofResult::VerifiedAddressInfos(BTreeMap::from([( + SHIELD_INPUT, + nonce.map(|nonce| (nonce, 1_000_000)), + )])) + } + + /// An in-memory store holding the pending activity row `activity_id` of a + /// shield of `id`, and the row's entry. + async fn recorded_shield( + id: SubwalletId, + activity_id: [u8; 32], + ) -> ( + Arc>, + Option, + ) { + let store = Arc::new(RwLock::new(InMemoryShieldedStore::new())); + let entry = pending_entry(activity_id); + store + .write() + .await + .save_activity(id, &entry) + .expect("the pending row"); + (store, Some(entry)) + } + + async fn shield_status( + store: &Arc>, + id: SubwalletId, + activity_id: &[u8; 32], + ) -> ShieldedActivityStatus { + store + .read() + .await + .get_activity_by_entry_id(id, activity_id) + .expect("the row reads") + .expect("the row") + .status + } + + /// Once a dispatch may have reached a node, a shield whose result is not + /// proved is unconfirmed and its row stays pending, never failed: a node's + /// refusal of the broadcast and a consensus verdict on either call + /// included (here a stale nonce, which used to read as a retryable nonce + /// mismatch), as no proof backs an endpoint's answer and a retry signs a + /// second shield. The reason keeps what the broadcast was answered with. + #[tokio::test] + async fn should_report_a_shield_unconfirmed_once_a_dispatch_may_have_reached_a_node() { + let wallet_id = [0x76; 32]; + let id = SubwalletId::new(wallet_id, 0); + let activity_id = [0x7F; 32]; + let cases = [ + ( + "a node refused the broadcast, the wait timed out", + BroadcastDelivery::MaybeDelivered(unavailable()), + wait_timeout(), + ), + ( + "the broadcast was answered with a consensus verdict", + BroadcastDelivery::MaybeDelivered(nonce_verdict(false)), + wait_timeout(), + ), + ( + "admitted, the wait was answered with a consensus verdict", + BroadcastDelivery::Admitted, + nonce_verdict(true), + ), + ( + "admitted, the wait timed out", + BroadcastDelivery::Admitted, + wait_timeout(), + ), + ]; + for (case, delivery, wait_error) in cases { + let (store, entry) = recorded_shield(id, activity_id).await; + let broadcast_answer = match &delivery { + BroadcastDelivery::MaybeDelivered(e) => Some(e.to_string()), + _ => None, + }; + let settled = settle_shield( + &store, + None, + wallet_id, + id, + &entry, + &shield_inputs(), + delivery, + |e: &dash_sdk::Error| e.to_string(), + || std::future::ready(Err(wait_error)), + ) + .await; + let Err(PlatformWalletError::ShieldedSpendUnconfirmed { + operation: "shield", + reason, + }) = settled + else { + panic!("{case}: {settled:?}"); + }; + if let Some(answer) = broadcast_answer { + assert!(reason.contains(&answer), "{case}: {reason}"); + } + assert_eq!( + shield_status(&store, id, &activity_id).await, + ShieldedActivityStatus::Pending, + "{case}" + ); + } + } + + /// Only a shield whose transition never left the wallet is failed, its + /// row with it, and nothing waits for its result. + #[tokio::test] + async fn should_report_a_shield_failed_only_when_nothing_was_sent() { + use dash_sdk::dapi_client::DapiClientError; + use std::cell::Cell; + + let wallet_id = [0x77; 32]; + let id = SubwalletId::new(wallet_id, 0); + let activity_id = [0x80; 32]; + let (store, entry) = recorded_shield(id, activity_id).await; + let waited = Cell::new(false); + let settled = settle_shield( + &store, + None, + wallet_id, + id, + &entry, + &shield_inputs(), + BroadcastDelivery::NeverDelivered(dash_sdk::Error::DapiClientError( + DapiClientError::NoAvailableAddresses, + )), + |e: &dash_sdk::Error| e.to_string(), + || { + waited.set(true); + std::future::ready(Err(wait_timeout())) + }, + ) + .await; + assert!( + matches!( + settled, + Err(PlatformWalletError::ShieldedBroadcastFailed(_)) + ), + "{settled:?}" + ); + assert!(!waited.get(), "nothing was sent, so nothing is waited for"); + assert_eq!( + shield_status(&store, id, &activity_id).await, + ShieldedActivityStatus::Failed + ); + } + + /// A shield succeeds once its verified result reads every input address + /// at or past the nonce it signed, whatever its broadcast was answered + /// with. Its row stays pending: the result proves the input addresses, + /// not this shield or its note, which the scan confirms. + #[tokio::test] + async fn should_accept_a_shield_whose_inputs_read_spent_and_leave_its_row_to_the_scan() { + let wallet_id = [0x78; 32]; + let id = SubwalletId::new(wallet_id, 0); + let activity_id = [0x81; 32]; + for (delivery, proved_nonce) in [ + (BroadcastDelivery::Admitted, SHIELD_NONCE), + (BroadcastDelivery::Admitted, SHIELD_NONCE + 1), + ( + BroadcastDelivery::MaybeDelivered(unavailable()), + SHIELD_NONCE, + ), + ( + BroadcastDelivery::MaybeDelivered(nonce_verdict(false)), + SHIELD_NONCE, + ), + ] { + let (store, entry) = recorded_shield(id, activity_id).await; + settle_shield( + &store, + None, + wallet_id, + id, + &entry, + &shield_inputs(), + delivery, + |e: &dash_sdk::Error| e.to_string(), + || std::future::ready(Ok(input_snapshot(Some(proved_nonce)))), + ) + .await + .expect("its inputs read spent"); + assert_eq!( + shield_status(&store, id, &activity_id).await, + ShieldedActivityStatus::Pending, + "nonce {proved_nonce}" + ); + } + } + + /// A verified result that does not read the shield's inputs spent shows + /// the shield had not executed at its block, whatever the endpoint that + /// returned it claims: a result of another kind, one that leaves an input + /// out or proves no state for it, and an input still below the nonce the + /// shield signed leave it unconfirmed, its row pending. + #[tokio::test] + async fn should_report_a_shield_unconfirmed_when_its_result_does_not_read_its_inputs_spent() { + let wallet_id = [0x7A; 32]; + let id = SubwalletId::new(wallet_id, 0); + let activity_id = [0x83; 32]; + let cases = [ + ( + "a result of another kind", + StateTransitionProofResult::VerifiedTokenBalanceAbsence(Identifier::from([1; 32])), + ), + ( + "an input left out", + StateTransitionProofResult::VerifiedAddressInfos(BTreeMap::from([( + PlatformAddress::P2pkh([8; 20]), + Some((SHIELD_NONCE, 1_000_000)), + )])), + ), + ("an input with no state", input_snapshot(None)), + ( + "an input below its signed nonce", + input_snapshot(Some(SHIELD_NONCE - 1)), + ), + ]; + for (case, snapshot) in cases { + let (store, entry) = recorded_shield(id, activity_id).await; + let settled = settle_shield( + &store, + None, + wallet_id, + id, + &entry, + &shield_inputs(), + BroadcastDelivery::Admitted, + |e: &dash_sdk::Error| e.to_string(), + || std::future::ready(Ok(snapshot)), + ) + .await; + assert!( + matches!( + settled, + Err(PlatformWalletError::ShieldedSpendUnconfirmed { + operation: "shield", + .. + }) + ), + "{case}: {settled:?}" + ); + assert_eq!( + shield_status(&store, id, &activity_id).await, + ShieldedActivityStatus::Pending, + "{case}" + ); + } + + // A transition that names no input shows nothing spent. + let (store, entry) = recorded_shield(id, activity_id).await; + let settled = settle_shield( + &store, + None, + wallet_id, + id, + &entry, + &BTreeMap::new(), + BroadcastDelivery::Admitted, + |e: &dash_sdk::Error| e.to_string(), + || std::future::ready(Ok(input_snapshot(Some(SHIELD_NONCE)))), + ) + .await; + assert!( + matches!( + settled, + Err(PlatformWalletError::ShieldedSpendUnconfirmed { .. }) + ), + "no input: {settled:?}" + ); + } + + /// The broadcast of a signed shield through a network SDK: a node that + /// refuses the connection leaves it unconfirmed and its row pending, as a + /// transport failure cannot show that nothing was sent, and an SDK with + /// no address to send to leaves it failed. + #[tokio::test] + async fn should_report_a_shield_unconfirmed_when_its_node_refuses_the_connection() { + let wallet_id = [0x79; 32]; + let id = SubwalletId::new(wallet_id, 0); + let activity_id = [0x82; 32]; + let transition = shield_transition(); + + let (store, entry) = recorded_shield(id, activity_id).await; + let (refusing, _port) = sdk_refusing_connections(); + let refused = broadcast_shield( + &Arc::new(refusing), + &store, + None, + wallet_id, + id, + &entry, + &transition, + |e: &dash_sdk::Error| e.to_string(), + ) + .await; + assert!( + matches!( + refused, + Err(PlatformWalletError::ShieldedSpendUnconfirmed { + operation: "shield", + .. + }) + ), + "{refused:?}" + ); + assert_eq!( + shield_status(&store, id, &activity_id).await, + ShieldedActivityStatus::Pending + ); + + let (store, entry) = recorded_shield(id, activity_id).await; + let never_sent = broadcast_shield( + &Arc::new(sdk_without_addresses()), + &store, + None, + wallet_id, + id, + &entry, + &transition, + |e: &dash_sdk::Error| e.to_string(), + ) + .await; + assert!( + matches!( + never_sent, + Err(PlatformWalletError::ShieldedBroadcastFailed(_)) + ), + "{never_sent:?}" + ); + assert_eq!( + shield_status(&store, id, &activity_id).await, + ShieldedActivityStatus::Failed + ); + } +} + +#[cfg(test)] +mod classify_spend_wait_failure_tests { + use super::*; + use dash_sdk::error::StateTransitionBroadcastError; + use dpp::consensus::basic::decode::ProtocolVersionParsingError; + use dpp::consensus::basic::BasicError; + use dpp::consensus::ConsensusError; + + fn broadcast_err(cause: Option) -> dash_sdk::Error { + dash_sdk::Error::StateTransitionBroadcastError(StateTransitionBroadcastError { + code: 13, + message: "context deadline exceeded".to_string(), + cause, + }) + } + + /// A broadcast error carrying a consensus cause comes from an + /// unauthenticated endpoint, with no proof behind it: the spend stays + /// unconfirmed and its reservation stays. + #[test] + fn should_read_a_wait_stage_consensus_verdict_as_unconfirmed() { + let cause = ConsensusError::BasicError(BasicError::ProtocolVersionParsingError( + ProtocolVersionParsingError::new("bad version".to_string()), + )); + let err = classify_spend_wait_failure("unshield", &broadcast_err(Some(cause))); + assert!( + matches!(err, PlatformWalletError::ShieldedSpendUnconfirmed { .. }), + "{err:?}" + ); + } + + #[test] + fn causeless_broadcast_error_is_ambiguous() { + // DAPI maps its own wait failures (e.g. `DapiError::Timeout`) to a + // `StateTransitionBroadcastError` with EMPTY consensus data, which the + // SDK decodes as `cause: None`. The spend may still execute after the + // wait gave up, so this must NOT release the note reservations. + let err = classify_spend_wait_failure("unshield", &broadcast_err(None)); + assert!( + matches!( + err, + PlatformWalletError::ShieldedSpendUnconfirmed { + operation: "unshield", + .. + } + ), + "got {err:?}" + ); + } + + #[test] + fn transport_errors_are_ambiguous() { + let err = classify_spend_wait_failure( + "withdraw", + &dash_sdk::Error::TimeoutReached( + std::time::Duration::from_secs(80), + "waiting for response".to_string(), + ), + ); + assert!(matches!( + err, + PlatformWalletError::ShieldedSpendUnconfirmed { + operation: "withdraw", + .. + } + )); + } + + /// The shape a CheckTx rejection takes when it reaches the SDK from + /// `broadcast()`: DAPI re-attaches the serialized consensus error as + /// gRPC metadata and the dapi-client decodes it into + /// `Error::Protocol(ConsensusError)`. + fn consensus_metadata_rejection() -> dash_sdk::Error { let cause = ConsensusError::BasicError(BasicError::ProtocolVersionParsingError( ProtocolVersionParsingError::new("bad version".to_string()), )); dash_sdk::Error::Protocol(dpp::ProtocolError::ConsensusError(Box::new(cause))) } - /// A consensus rejection surfacing from `broadcast()` stays definitive - /// for the shields into the pool that classify with - /// `broadcast_definitely_failed`, which move funds to the wallet's own - /// notes. On a note spend's wait the same verdict reads as unconfirmed: + /// A consensus rejection surfacing from `broadcast()` reads as a refusal + /// (`broadcast_was_refused`), which proves nothing: the one flow that + /// reads it, the shield from an identity, reports unconfirmed either + /// way. On a note spend's wait the same verdict reads as unconfirmed: /// no proof backs it. #[test] - fn should_read_a_consensus_rejection_as_definitive_only_for_shields_into_the_pool() { - assert!(broadcast_definitely_failed(&consensus_metadata_rejection())); + fn should_read_a_consensus_rejection_as_a_refusal_and_never_as_a_failed_spend() { + assert!(broadcast_was_refused(&consensus_metadata_rejection())); let err = classify_spend_wait_failure("transfer", &consensus_metadata_rejection()); assert!( matches!(err, PlatformWalletError::ShieldedSpendUnconfirmed { .. }), @@ -6337,49 +7571,38 @@ mod classify_spend_wait_failure_tests { } /// Connection-establishment failures and non-consensus server - /// rejections of `broadcast()` ARE definitive: nothing was admitted to - /// a mempool. The offline case (connect refused → `Unavailable`) in - /// particular must release the notes immediately rather than strand - /// them until restart. + /// rejections of `broadcast()` read as refusals: the shield from an + /// identity then skips its result wait for a proven nonce read. None of + /// them proves the transition was left out of every mempool. #[test] - fn broadcast_connection_failures_and_rejections_are_definitive() { + fn should_read_connection_failures_and_rejections_of_a_broadcast_as_refusals() { use dash_sdk::dapi_grpc::tonic::Code; - assert!(broadcast_definitely_failed(&grpc_err(Code::Unavailable))); + assert!(broadcast_was_refused(&grpc_err(Code::Unavailable))); // Mempool full / malformed request: server verdicts refusing admission. - assert!(broadcast_definitely_failed(&grpc_err( - Code::ResourceExhausted - ))); - assert!(broadcast_definitely_failed(&grpc_err( - Code::InvalidArgument - ))); + assert!(broadcast_was_refused(&grpc_err(Code::ResourceExhausted))); + assert!(broadcast_was_refused(&grpc_err(Code::InvalidArgument))); } - /// No-response shapes of the `broadcast()` call itself are NOT - /// definitive: the dapi-client retries across addresses, so the request + /// No-response shapes of the `broadcast()` call itself are not + /// refusals: the dapi-client retries across addresses, so the request /// may have been delivered to a node whose ACK was lost. The caller - /// falls through to the result wait instead of releasing the - /// reservations (which would let a retry select other unreserved notes - /// and double-send if the original broadcast landed). + /// falls through to the result wait. #[test] fn broadcast_no_response_shapes_are_inconclusive() { use dash_sdk::dapi_grpc::tonic::Code; - assert!(!broadcast_definitely_failed(&grpc_err( - Code::DeadlineExceeded - ))); + assert!(!broadcast_was_refused(&grpc_err(Code::DeadlineExceeded))); // DAPI maps its own tenderdash-side failures (which can postdate // delivery) to Internal. - assert!(!broadcast_definitely_failed(&grpc_err(Code::Internal))); - assert!(!broadcast_definitely_failed( - &dash_sdk::Error::TimeoutReached( - std::time::Duration::from_secs(30), - "broadcast".to_string(), - ) - )); - assert!(!broadcast_definitely_failed(&dash_sdk::Error::Generic( + assert!(!broadcast_was_refused(&grpc_err(Code::Internal))); + assert!(!broadcast_was_refused(&dash_sdk::Error::TimeoutReached( + std::time::Duration::from_secs(30), + "broadcast".to_string(), + ))); + assert!(!broadcast_was_refused(&dash_sdk::Error::Generic( "transport error: connection reset".to_string() ))); // …including as the terminal error of an exhausted retry loop. - assert!(!broadcast_definitely_failed( + assert!(!broadcast_was_refused( &dash_sdk::Error::NoAvailableAddressesToRetry(Box::new(grpc_err( Code::DeadlineExceeded ))) @@ -6392,9 +7615,9 @@ mod classify_spend_wait_failure_tests { /// — the spend is in flight and the result wait will confirm it. #[test] fn broadcast_already_exists_is_in_flight() { - assert!(!broadcast_definitely_failed( - &dash_sdk::Error::AlreadyExists("state transition already in mempool".to_string()) - )); + assert!(!broadcast_was_refused(&dash_sdk::Error::AlreadyExists( + "state transition already in mempool".to_string() + ))); } /// A consensus verdict wrapped in the dapi-client's `NoAvailableAddressesToRetry` @@ -6545,44 +7768,6 @@ mod reserve_shield_fee_tests { } } -#[cfg(test)] -mod note_reservation_release_tests { - use super::*; - - /// `ShieldedBroadcastUnconfirmed` is the one failure that must NOT release the reservation: the - /// broadcast was accepted and the transition may have executed, so freeing the notes invites a - /// double-spend against notes that may already be consumed on chain. The next nullifier sync - /// reconciles them. - #[test] - fn unconfirmed_broadcast_retains_reservation() { - let e = PlatformWalletError::ShieldedBroadcastUnconfirmed { - identity_id: Identifier::from([7u8; 32]), - reason: "result proof unavailable".to_string(), - }; - assert!( - !error_releases_note_reservation(&e), - "ShieldedBroadcastUnconfirmed must retain the note reservation" - ); - } - - /// Every other failure is a definitive pre-execution / build / rejection failure — the spend - /// never happened, so the reservation must be released. - #[test] - fn definitive_failures_release_reservation() { - let releasing: Vec = vec![ - PlatformWalletError::ShieldedBroadcastFailed("rejected on merits".to_string()), - PlatformWalletError::ShieldedBuildError("note selection failed".to_string()), - PlatformWalletError::ShieldedStoreError("store write failed".to_string()), - ]; - for e in &releasing { - assert!( - error_releases_note_reservation(e), - "{e:?} must release the note reservation" - ); - } - } -} - #[cfg(test)] mod record_activity_status_tests { use super::*; diff --git a/packages/rs-platform-wallet/src/wallet/shielded/store.rs b/packages/rs-platform-wallet/src/wallet/shielded/store.rs index 78c87b307ad..b2672e56d00 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/store.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/store.rs @@ -143,12 +143,15 @@ pub type StalePendingSpend = ([u8; 32], [u8; 32], Option<[u8; 32]>, Option) /// /// Identity-funded shields arm this record before broadcast and have no input /// nullifiers. Their guard survives even after rebroadcasting stops. Note spends -/// arm it only on the ambiguous outcome (`ShieldedSpendUnconfirmed`): -/// the broadcast was accepted but the result wait failed, so the spend -/// may or may not have executed. Re-broadcasting the byte-identical -/// transition is fund-safe — identical nullifiers cannot double-spend — -/// and converts silence into either a confirmation (next scan sees the -/// nullifiers spent) or a definitive consensus verdict. +/// arm it before their first dispatch too, and keep it unless the transition +/// never left the wallet ([`ShieldedStore::retire_undelivered_spend`]): a +/// spend that may have reached a node may or may not have executed, and a +/// process that exits during its broadcast or its result wait leaves the +/// record to restore its notes' reservation from. Re-broadcasting the +/// byte-identical transition is fund-safe (identical nullifiers cannot be +/// spent twice) and converts silence into a confirmation (next scan sees the +/// nullifiers spent); a spend that never lands keeps its notes held until its +/// anchor is proven pruned. #[derive(Debug, Clone, PartialEq, Eq)] pub struct PendingRedrive { /// Activity-entry id of the spend (sha256 of visible output cmxs); @@ -507,12 +510,13 @@ pub trait ShieldedStore: Send + Sync + 'static { /// Returns `true` if the nullifier was newly added to the /// pending set, `false` if it was already pending. /// - /// Pending state is **in-memory only** — it does not survive - /// a process restart. The crash-during-broadcast case is - /// reconciled by the next note-scan pass after the transition - /// lands (scan-based spend detection marks the spent note via - /// its nullifier), or, on rejection, leaves the notes - /// observable as unspent again on the next launch. + /// The reservation itself is held in memory. A spend saves a redrive + /// record before its first dispatch ([`Self::arm_redrive`]), which + /// carries its nullifiers: a store that persists records restores the + /// reservation from it on reopen, so a process that exits during a + /// broadcast keeps the notes reserved. A reservation with no saved + /// record (its spend exited before saving one, so before anything was + /// dispatched) does not survive a restart. /// /// `unspent_notes` skips notes whose nullifier is in the /// pending set, so a successful `mark_pending` immediately @@ -605,8 +609,8 @@ pub trait ShieldedStore: Send + Sync + 'static { // ── Re-drivable unconfirmed spends (per-subwallet) ───────────────── - /// Persist a re-drivable record for a broadcast-accepted spend whose - /// result wait failed ambiguously. Keyed by `redrive.activity_id`; + /// Persist the re-drivable record of a spend, saved before its first + /// dispatch. Keyed by `redrive.activity_id`; /// re-arming the same id overwrites. Unlike the bare `mark_pending` /// reservations, redrive records survive a restart where the backend /// persists them (the file store does): on reopen both the record @@ -941,8 +945,8 @@ pub trait ShieldedStore: Send + Sync + 'static { /// stranded (broadcast-accepted-but-never-landed) spend: once that anchor /// is pruned from Platform's recorded set the spend can never execute, and /// with the nullifier still unspent the reservation is provably dead and -/// its note can be freed. All in-memory only — a restart drops every -/// reservation regardless. +/// its note can be freed. Held in memory: a restart keeps the reservations +/// a saved [`PendingRedrive`] restores, and drops the others. #[derive(Debug, Clone, Default)] pub(super) struct PendingSpend { /// The recorded anchor the spend was built against, once known. @@ -981,11 +985,12 @@ pub(super) struct SubwalletState { /// transition, mapped to the [`PendingSpend`] bookkeeping the /// sync reconcile needs. Excluded from `unspent_notes()` so /// concurrent callers can't double-select. Held in memory; a - /// pre-broadcast reservation dies with the process, but a - /// reservation belonging to an armed [`PendingRedrive`] is - /// rehydrated on file-store open (the redrive row carries its - /// nullifiers), so an unconfirmed broadcast keeps its notes - /// reserved across restarts. + /// reservation whose spend has saved no record yet dies with the + /// process, but a reservation belonging to an armed + /// [`PendingRedrive`], which a spend saves before its first + /// dispatch, is rehydrated on file-store open (the redrive row + /// carries its nullifiers), so a spend that may have been broadcast + /// keeps its notes reserved across restarts. pub pending_nullifiers: BTreeMap<[u8; 32], PendingSpend>, /// Armed re-drivable unconfirmed spends, keyed by activity id. /// See [`PendingRedrive`]. Kept consistent with diff --git a/packages/rs-sdk/src/platform/transition/broadcast.rs b/packages/rs-sdk/src/platform/transition/broadcast.rs index 3949a7476d5..c1edd3ffae5 100644 --- a/packages/rs-sdk/src/platform/transition/broadcast.rs +++ b/packages/rs-sdk/src/platform/transition/broadcast.rs @@ -400,7 +400,13 @@ where .await } -fn is_address_nonce_ahead(transition: &StateTransition, error: &Error) -> bool { +/// Whether `error` is a node refusing `transition` because one of its input +/// addresses' nonces is ahead of what that node has: the answer of a node +/// that is behind the one the nonce was read from. A broadcast answers it by +/// sending the same signed bytes to another node, within its retry budget. +/// A caller that broadcasts in single dispatches (`retries: Some(0)`) gets +/// no such failover from the SDK and reads this to keep dispatching. +pub fn is_address_nonce_ahead(transition: &StateTransition, error: &Error) -> bool { let Error::Protocol(ProtocolError::ConsensusError(consensus)) = error else { return false; }; diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerMasternodes.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerMasternodes.swift index e0a072611b5..fc148865ad5 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerMasternodes.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerMasternodes.swift @@ -286,11 +286,12 @@ extension PlatformWalletManager { /// `ownerKeyIndexHint`: as on `masternodeWithdrawalKeys` — verified, not /// trusted. /// - /// Outcomes: a definitive rejection throws an ordinary error and may be - /// retried. An AMBIGUOUS outcome — broadcast accepted (or its ACK lost) - /// and the result wait failed — throws + /// Outcomes: only a failure before anything was sent throws an ordinary + /// error and may be retried. Once the withdrawal may have reached a node, + /// any outcome short of the proved balance (a failed result wait, a + /// node's refusal or a consensus verdict) throws /// `PlatformWalletError.masternodeWithdrawalUnconfirmed`: the claim may - /// have executed and the identity nonce was consumed, so callers must + /// have executed and a retry signs a second withdrawal, so callers must /// NOT retry until they have re-read the claimable balance. /// /// Pure bridge — the whole orchestration (masternode lookup, identity diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift index 617c00d1160..a6feb022840 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift @@ -2,13 +2,14 @@ import Foundation import DashSDKFFI /// Thrown by `shieldedIdentityCreateFromPool` when the Type-20 -/// transition was broadcast and ACCEPTED by the relay, but the SDK -/// could not confirm its execution result and a direct fetch of the -/// derived id also came back empty (the Rust side already retried). +/// transition may have reached a node (a broadcast a node accepted, a +/// send attempt that may have delivered it, a node's refusal or verdict), +/// its result is not proved, and a direct fetch of the derived id also +/// came back empty (the Rust side already retried). /// /// This is NOT a registration failure: the identity may already exist -/// on chain (the broadcast landed; only the result-proof confirmation -/// failed — e.g. a transient DAPI/proof error). The caller MUST hold +/// on chain or may still be created (its result is not proved, e.g. after +/// a transient DAPI/proof error or a node's refusal). The caller MUST hold /// the slot against re-submission and surface the pending identity /// rather than treating it as unregistered — re-registering the same /// keys while the identity is live would fail the registered-key-hash @@ -676,11 +677,12 @@ extension PlatformWalletManager { /// stays resident between spends (the launch-time bind is /// viewing-grade only). /// - /// Throws `PlatformWalletError.shieldedSpendUnconfirmed` when the - /// broadcast was accepted but its execution result couldn't be - /// confirmed — the spend may already be on chain, so the caller - /// must NOT retry (the spent notes stay reserved Rust-side; the - /// next shielded sync reconciles them). + /// Throws `PlatformWalletError.shieldedSpendUnconfirmed` once the + /// spend may have reached a node and its result is not proved (a + /// failed result wait, a node's refusal or consensus verdict + /// included): it may already be on chain or may still execute, so the + /// caller must NOT retry (the spent notes stay reserved Rust-side + /// until a later shielded sync resolves them). public func shieldedTransfer( walletId: Data, resolver: MnemonicResolver, @@ -848,12 +850,12 @@ extension PlatformWalletManager { /// Heavy CPU work (Halo 2 proof + per-input signing) runs on a /// detached task so the caller's actor isn't blocked. /// - /// Throws `PlatformWalletError.shieldedSpendUnconfirmed` when the - /// broadcast was accepted but its execution result couldn't be - /// confirmed — the shield may already be on chain, so the caller - /// must NOT retry (a retry would rebuild the bundle and could - /// double-shield; the next sync reconciles the outcome). A shield - /// spends no notes, so nothing is reserved wallet-side. + /// Throws `PlatformWalletError.shieldedSpendUnconfirmed` once the + /// shield may have reached a node and its result is not proved (a + /// node's refusal or consensus verdict, stale nonce included): it may + /// already be on chain, so the caller must NOT retry (a retry signs a + /// second transition). Its activity row stays pending until the + /// shielded scan sees its note; nothing is reserved wallet-side. public func shieldedShield( walletId: Data, shieldedAccount: UInt32 = 0, @@ -918,10 +920,11 @@ extension PlatformWalletManager { /// Heavy CPU work (Halo 2 proof + the identity signature) runs on a /// detached task so the caller's actor isn't blocked. /// - /// Throws `PlatformWalletError.shieldedSpendUnconfirmed` when the - /// broadcast was accepted but its execution result couldn't be - /// confirmed: the shield may already be on chain, so the caller must - /// NOT retry (a retry would rebuild the bundle and could double-shield; + /// Throws `PlatformWalletError.shieldedSpendUnconfirmed` once the + /// shield may have reached a node and its result is not proved (a + /// node's refusal or consensus verdict included): it may already be on + /// chain or may still execute, so the caller must + /// NOT retry (a retry signs a second transition; /// the next sync reconciles the outcome). Like every shield it spends /// no notes. An unresolved debit blocks a fresh shield from that identity /// with `.shieldedIdentityDebitPending`. Inspect durable records with @@ -1006,12 +1009,12 @@ extension PlatformWalletManager { /// or Rust rejects it. The 36-byte on-chain encoding is done on the /// Rust side. /// - /// Throws `PlatformWalletError.shieldedSpendUnconfirmed` when the - /// broadcast was accepted but its execution result couldn't be - /// confirmed — the shield may already be on chain, so the caller - /// must NOT retry (a retry would rebuild the bundle and could - /// double-pay; the next sync reconciles the outcome). A shield - /// spends no notes, so nothing is reserved wallet-side. + /// Throws `PlatformWalletError.shieldedSpendUnconfirmed` once the + /// shield may have reached a node and its result is not proved (a + /// node's refusal or consensus verdict, stale nonce included): it may + /// already be on chain, so the caller must NOT retry (a retry signs a + /// second transition). Its activity row stays pending until the + /// shielded scan sees its note; nothing is reserved wallet-side. public func shieldedShieldToRecipient( walletId: Data, shieldedAccount: UInt32 = 0, @@ -1086,11 +1089,12 @@ extension PlatformWalletManager { /// `resolver` supplies the per-operation Orchard spend authority /// (see [`shieldedTransfer`]). /// - /// Throws `PlatformWalletError.shieldedSpendUnconfirmed` when the - /// broadcast was accepted but its execution result couldn't be - /// confirmed — the spend may already be on chain, so the caller - /// must NOT retry (the spent notes stay reserved Rust-side; the - /// next shielded sync reconciles them). + /// Throws `PlatformWalletError.shieldedSpendUnconfirmed` once the + /// spend may have reached a node and its result is not proved (a + /// failed result wait, a node's refusal or consensus verdict + /// included): it may already be on chain or may still execute, so the + /// caller must NOT retry (the spent notes stay reserved Rust-side + /// until a later shielded sync resolves them). public func shieldedUnshield( walletId: Data, resolver: MnemonicResolver, @@ -1152,11 +1156,12 @@ extension PlatformWalletManager { /// supplies per operation (see [`shieldedTransfer`]), exactly as for /// [`shieldedUnshield`]. /// - /// Throws `PlatformWalletError.shieldedSpendUnconfirmed` when the - /// broadcast was accepted but its execution result couldn't be - /// confirmed: the spend may already be on chain, so the caller must - /// NOT retry (the spent notes stay reserved Rust-side; the next - /// shielded sync reconciles them). + /// Throws `PlatformWalletError.shieldedSpendUnconfirmed` once the + /// spend may have reached a node and its result is not proved (a + /// failed result wait, a node's refusal or consensus verdict + /// included): it may already be on chain or may still execute, so the + /// caller must NOT retry (the spent notes stay reserved Rust-side + /// until a later shielded sync resolves them). public func shieldedIdentityTopUpFromPool( walletId: Data, resolver: MnemonicResolver, @@ -1220,11 +1225,12 @@ extension PlatformWalletManager { /// `resolver` supplies the per-operation Orchard spend authority /// (see [`shieldedTransfer`]). /// - /// Throws `PlatformWalletError.shieldedSpendUnconfirmed` when the - /// broadcast was accepted but its execution result couldn't be - /// confirmed — the spend may already be on chain, so the caller - /// must NOT retry (the spent notes stay reserved Rust-side; the - /// next shielded sync reconciles them). + /// Throws `PlatformWalletError.shieldedSpendUnconfirmed` once the + /// spend may have reached a node and its result is not proved (a + /// failed result wait, a node's refusal or consensus verdict + /// included): it may already be on chain or may still execute, so the + /// caller must NOT retry (the spent notes stay reserved Rust-side + /// until a later shielded sync resolves them). public func shieldedWithdraw( walletId: Data, resolver: MnemonicResolver, @@ -1412,9 +1418,9 @@ extension PlatformWalletManager { // would construct a second wrapper over the same struct and // double-free). Inspect the typed code directly: // - success: return the derived id. - // - unconfirmed: the broadcast landed but its result couldn't be - // confirmed; Rust filled `outIdentityId` with the derived id on - // THIS code (and only this code). Throw the typed + // - unconfirmed: the transition may have reached a node and its + // result is not proved; Rust filled `outIdentityId` with the + // derived id on THIS code (and only this code). Throw the typed // `ShieldedIdentityCreateUnconfirmedError` so the caller holds // the slot instead of treating it as failed. // - any other non-success: throw the regular typed error. diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift index 15f618e0bee..ec846fb11ba 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift @@ -21,23 +21,27 @@ public enum PlatformWalletResultCode: Int32, Sendable { case errorArithmeticOverflow = 13 case errorNoSelectableInputs = 14 case errorWalletAlreadyExists = 15 - /// Definitive shielded-broadcast failure: the shielded transition - /// (identity-create, unshield, transfer, or withdrawal) was not executed - /// (relay/CheckTx rejection or a platform-reported execution error), the - /// spent notes were released, and the caller may retry. + /// Definitive shielded-broadcast failure: the shielded transition never + /// left the wallet (refused before anything was sent: no node address, or + /// the SDK's own refusal), so it can never execute. Any reserved notes + /// were released and the caller may retry. A node's refusal or consensus + /// verdict is unconfirmed instead (18, or 17 for identity-create). case errorShieldedBroadcastFailed = 16 - /// Shielded broadcast accepted but its execution result could not be - /// confirmed; the identity may already exist on chain. The FFI also fills - /// the derived id into `outIdentityId` on this code, so the caller can - /// hold the slot rather than treat the registration as failed. + /// An identity create from the pool may have reached a node (accepted, a + /// send attempt that may have delivered it, a node's refusal or verdict), + /// its result is not proved and a direct fetch of the derived id came + /// back empty. The wallet keeps the notes reserved and the saved + /// transition. The identity may already exist on chain: do not treat it + /// as unregistered or re-submit. The FFI fills the derived id into + /// `outIdentityId` on this code, so the caller can hold the slot. case errorShieldedBroadcastUnconfirmed = 17 - /// A shielded operation (shield / unshield / transfer / withdrawal) was - /// accepted by the relay but its execution result could not be - /// confirmed. It may have executed on chain; for the spend-based - /// operations the wallet keeps the notes reserved (a shield reserves - /// nothing) until the next sync (or app restart) reconciles the - /// outcome. Do NOT auto-retry — a retry would rebuild the bundle and - /// could double-execute if the original landed. + /// A shielded operation (shield from Platform addresses, unshield / + /// transfer / withdrawal) may have reached a node and its result is not + /// proved: a failed result wait, a node's refusal or a consensus verdict + /// (a stale address nonce included). It may have executed. Spends keep + /// their notes reserved and the saved transition for the wallet to + /// resolve; a shield's activity row stays pending until the scan sees its + /// note. Do NOT auto-retry: a retry signs a second transition. case errorShieldedSpendUnconfirmed = 18 /// A shielded spend could not be built against a Platform-recorded anchor: /// the wallet's commitment tree isn't synced to a checkpoint Platform has @@ -53,12 +57,12 @@ public enum PlatformWalletResultCode: Int32, Sendable { /// of double-spending; the reservation TTL or a sync reconciles the /// outcome. Do NOT auto-retry. case errorTransactionBroadcastUnconfirmed = 20 - /// A masternode (evonode) identity credit withdrawal was broadcast and - /// accepted, but its execution result could not be confirmed — it may - /// already have executed, and the identity nonce was consumed for it, so - /// a blind retry could submit a SECOND withdrawal. Do NOT retry; re-read - /// the claimable balance and reconcile first. Definitive rejections keep - /// their ordinary codes and stay retryable. + /// A masternode (evonode) identity credit withdrawal may have reached a + /// node and its remaining balance is not proved (a failed result wait, a + /// node's refusal or a consensus verdict included). It may have executed; + /// a retry signs a second withdrawal with the next identity nonce. Do NOT + /// retry; re-read the claimable balance first. Only a withdrawal that + /// failed before anything was sent keeps an ordinary, retryable code. case errorMasternodeWithdrawalUnconfirmed = 42 /// The deterministic masternode list isn't available yet (SPV not /// running or masternode sync incomplete), so a list-backed query such @@ -66,13 +70,13 @@ public enum PlatformWalletResultCode: Int32, Sendable { /// `spvProgress.masternodes` reports the list synced. /// (46 — 43/44/45 are held by the shielded-invite error trio, #4313.) case errorMasternodeListUnavailable = 46 - /// Definitively-failed address-nonce race: Platform rejected an - /// address-funds transition (shield, or identity top-up-from-addresses) - /// because the submitted address nonce raced Platform's expected value - /// (a lagging DAPI replica read). The transition did NOT execute and any - /// notes were released (a shield reserves none) — safe to retry; the retry - /// re-fetches the nonce and self-heals. The submitted/expected nonce values - /// travel in the message string, not as structured fields. + /// Address-nonce race: Platform rejected an address-funds transition (a + /// transfer or withdrawal from Platform addresses, or an identity + /// registration or top-up from them) because the submitted address nonce + /// raced Platform's expected value (a lagging DAPI replica read). Safe to + /// retry; the retry re-fetches the nonce and self-heals. A shield does not + /// return it (see `errorShieldedSpendUnconfirmed`). The submitted/expected + /// nonce values travel in the message string, not as structured fields. case errorAddressNonceMismatch = 21 /// Atomic Core selection found no or insufficient unreserved UTXOs. case errorCoreInsufficientFunds = 22 @@ -601,22 +605,25 @@ public enum PlatformWalletError: LocalizedError { /// recipient was recorded carry none and accept the caller's. case assetLockRecipientMismatch(String) case walletAlreadyExists(String) - /// Definitive shielded-broadcast failure: the shielded transition - /// (identity-create or a spend — unshield / transfer / withdrawal) was - /// not executed and the spent notes were released; safe to retry. + /// Definitive shielded-broadcast failure: the shielded transition never + /// left the wallet (refused before anything was sent), so it cannot + /// execute; any reserved notes were released and a retry is safe. case shieldedBroadcastFailed(String) - /// Shielded broadcast accepted but its execution result could not be - /// confirmed; the identity may already exist on chain. Callers that need - /// the derived id should special-case the + /// An identity create from the pool may have reached a node (a node's + /// refusal or verdict included), its result is not proved and a direct + /// fetch of the derived id came back empty. The wallet keeps the notes + /// reserved and the saved transition; the identity may already exist on + /// chain, so do not treat it as unregistered or re-submit. Callers that + /// need the derived id should special-case the /// `.errorShieldedBroadcastUnconfirmed` result code (which carries - /// `outIdentityId`) before falling back to this error — see + /// `outIdentityId`) before falling back to this error: see /// `ShieldedIdentityCreateUnconfirmedError`. case shieldedBroadcastUnconfirmed(String) - /// A shielded operation (shield / unshield / transfer / withdrawal) - /// was accepted by the relay but its execution result could not be - /// confirmed. It may have executed; spend-based operations keep their - /// notes reserved wallet-side (a shield reserves nothing) until the - /// next sync reconciles the outcome. Do NOT auto-retry. + /// A shielded operation (shield from Platform addresses, unshield / + /// transfer / withdrawal) may have reached a node and its result is not + /// proved (a node's refusal or consensus verdict included). It may have + /// executed; spends keep their notes reserved, a shield stays pending + /// until the scan sees its note. Do NOT auto-retry. case shieldedSpendUnconfirmed(String) /// A shielded spend could not be built against a Platform-recorded anchor — /// the wallet's commitment tree isn't synced to a checkpoint Platform has @@ -636,10 +643,10 @@ public enum PlatformWalletError: LocalizedError { /// reservation TTL or a later sync reconciles the outcome. Do NOT /// auto-retry. Core sibling of `shieldedSpendUnconfirmed`. case transactionBroadcastUnconfirmed(String) - /// A masternode (evonode) credit withdrawal was broadcast and accepted - /// but its result could not be confirmed. It may already have executed - /// and the identity nonce was consumed — do NOT retry; re-read the - /// claimable balance first (`.errorMasternodeWithdrawalUnconfirmed`). + /// A masternode (evonode) credit withdrawal may have reached a node and + /// its result is not proved (a node's refusal or verdict included). It may + /// have executed and a retry signs a second withdrawal: do NOT retry; + /// re-read the claimable balance first (`.errorMasternodeWithdrawalUnconfirmed`). case masternodeWithdrawalUnconfirmed(String) /// The masternode list hasn't synced yet, so there is nothing to look a /// masternode up in (`.errorMasternodeListUnavailable`). Retry after @@ -648,12 +655,12 @@ public enum PlatformWalletError: LocalizedError { /// Core definitively rejected the transaction and its input reservation /// was released. Unlike `transactionBroadcastUnconfirmed`, retry is safe. case transactionBroadcastRejected(String) - /// Definitively-failed address-nonce race (shield, or identity - /// top-up-from-addresses): Platform rejected the transition because the - /// submitted address nonce raced its expected value. The transition did - /// NOT execute and any notes were released (a shield reserves none) — safe - /// to retry, and the retry re-fetches the address nonce so the mismatch - /// self-heals. The submitted/expected nonce values are in the message. + /// Address-nonce race (transfer or withdrawal from Platform addresses, or + /// identity registration / top-up from them): Platform rejected the + /// transition because the submitted address nonce raced its expected + /// value. Safe to retry: the retry re-fetches the address nonce so the + /// mismatch self-heals. A shield does not return it. The submitted and + /// expected nonce values are in the message. case addressNonceMismatch(String) /// A quiesce/drain barrier (Clear / reset / sync-stop) timed out with a /// sync pass still in flight. The operation failed closed — retry once diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/ViewModels/SendViewModel.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/ViewModels/SendViewModel.swift index d86c0f13e05..8304a48e2d1 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/ViewModels/SendViewModel.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/ViewModels/SendViewModel.swift @@ -831,11 +831,11 @@ class SendViewModel: ObservableObject { } catch PlatformWalletError.shieldedSpendUnconfirmed { // The shielded operation (shield / unshield / transfer / withdraw) - // was broadcast and accepted, but its execution result couldn't be - // confirmed — it may already be on chain. Rust intentionally KEEPS - // any spent notes' reservations, so this must NOT be presented as a - // retryable failure: retrying would rebuild the bundle and could - // double-execute if the original landed. Surface it through the + // may have reached a node and its result is not proved (a node's + // refusal or verdict included), so it may already be on chain. Rust + // intentionally KEEPS any spent notes' reservations, so this must + // NOT be presented as a retryable failure: a retry signs a second + // transition. Surface it through the // non-error (success) path so the UI doesn't invite a retry; the // next shielded sync reconciles the outcome. successMessage = "Transaction may have gone through — waiting for " diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/MasternodeDetailView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/MasternodeDetailView.swift index e1cf8cdbf17..7cfc03cc01c 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/MasternodeDetailView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/MasternodeDetailView.swift @@ -433,13 +433,13 @@ struct MasternodeDetailView: View { // Reflect the new (reduced) balance. await fetchClaimableBalance() } catch PlatformWalletError.masternodeWithdrawalUnconfirmed(let detail) { - // Ambiguous: the claim may have executed and the nonce was - // consumed — never re-submit blindly. Confirm stays disabled + // Ambiguous: the claim may have executed and its nonce may have + // been taken, so never re-submit blindly. Confirm stays disabled // until the balance is refreshed. claiming = false claimOutcomeUnconfirmed = true - claimError = "The withdrawal was submitted but its result couldn't be confirmed — " - + "it may have gone through. Refresh the balance before trying again. (\(detail))" + claimError = "The withdrawal may have reached the network, but its result couldn't be " + + "confirmed: it may have gone through. Refresh the balance before trying again. (\(detail))" } catch { claiming = false claimError = error.localizedDescription diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Services/IdentityRegistrationController.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Services/IdentityRegistrationController.swift index 86ee5b1898a..414be98a59d 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Services/IdentityRegistrationController.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Services/IdentityRegistrationController.swift @@ -53,11 +53,11 @@ final class IdentityRegistrationController: ObservableObject { /// the coordinator's map until the user dismisses it /// manually. case failed(String) - /// Broadcast-succeeded-but-confirmation-failed terminal state - /// (shielded Type-20 only). The transition was relayed and - /// accepted, but its execution-result proof couldn't be - /// confirmed and a direct fetch of the derived id also came - /// back empty (Rust already retried). The identity at + /// Unconfirmed terminal state (shielded Type-20 only). The + /// transition may have reached a node (a node's refusal or + /// verdict included), its result is not proved, and a direct + /// fetch of the derived id also came back empty (Rust already + /// retried). The identity at /// `identityId` MAY already be live on chain. /// /// This is NOT a red failure: treating it as unregistered is @@ -85,7 +85,7 @@ final class IdentityRegistrationController: ObservableObject { /// which the identity-slot anti-join already covers. /// `.failed` is NOT active either: the user is expected /// to retry, so the lock should resurface for selection. - /// `.unconfirmed` IS active: the identity is probably live on + /// `.unconfirmed` IS active: the identity may be live on /// chain, so the slot must stay held to block a re-submission /// that would burn funds against the registered-key-hash check. var isActive: Bool { @@ -102,10 +102,11 @@ final class IdentityRegistrationController: ObservableObject { /// `RegistrationProgressView` can attribute the red marker to the /// right step. Only meaningful for `fundingKind == .shieldedPool`. /// - /// Deliberately only ONE case: `.broadcastRejected` is the single + /// Deliberately only ONE case: `.broadcastNotSent` is the single /// failure shape we can attribute with confidence (a typed - /// `PlatformWalletError.shieldedBroadcastFailed`). We cannot honestly - /// claim a "before broadcast" stage by elimination — Rust build/proof + /// `PlatformWalletError.shieldedBroadcastFailed`: the transition was + /// refused before anything was sent). We cannot honestly claim a + /// "before broadcast" stage by elimination: Rust build/proof /// errors arrive as a generic `.walletOperation`, indistinguishable at /// this layer from an invalid handle, a marshalling failure, or any other /// non-broadcast error. So `failureStage` is left `nil` for everything @@ -113,10 +114,10 @@ final class IdentityRegistrationController: ObservableObject { /// Extensible: add a case here only when a new typed error actually lets /// us attribute the stage with certainty. enum FailureStage { - /// Platform definitively rejected the broadcast transition (a - /// `PlatformWalletError.shieldedBroadcastFailed`). Attributed to - /// the "Broadcasting transition" step. - case broadcastRejected + /// The transition was refused before anything was sent (a + /// `PlatformWalletError.shieldedBroadcastFailed`), so it never left + /// the wallet. Attributed to the "Broadcasting transition" step. + case broadcastNotSent } /// Current phase. Updates flow: @@ -126,7 +127,7 @@ final class IdentityRegistrationController: ObservableObject { /// Stage attribution for a shielded `.failed` phase. `nil` means /// "unattributed" — either the phase isn't a shielded failure, or the - /// failure wasn't a confidently-attributable broadcast rejection. On a + /// failure wasn't a confidently-attributable refusal before sending. On a /// `nil` shielded failure the progress view falls back to its /// elapsed-time heuristic (note-selection vs Halo 2 proof). Reset at the /// start of every `submit` so a retry doesn't inherit the previous @@ -192,7 +193,7 @@ final class IdentityRegistrationController: ObservableObject { /// - `.completed`: re-submitting after success would flip the /// UI from "Done" back to a spinner before failing on the /// consumed lock. - /// - `.unconfirmed`: the identity is probably already live on + /// - `.unconfirmed`: the identity may already be live on /// chain; re-submitting the same keys would fail the /// registered-key-hash stateful check and burn the funds. /// `.idle`, `.preparingKeys`, and `.failed` are allowed — the @@ -204,10 +205,11 @@ final class IdentityRegistrationController: ObservableObject { /// background priority and reports the identity id on success /// or rethrows on failure. The controller flips `phase` to /// `.completed` / `.unconfirmed` / `.failed` accordingly. On a shielded - /// `.failed` it records `failureStage = .broadcastRejected` ONLY for a - /// `PlatformWalletError.shieldedBroadcastFailed`; every other error leaves - /// `failureStage` nil (unattributed — the progress view uses its - /// elapsed-time heuristic) rather than guessing a stage by elimination. + /// `.failed` it records `failureStage = .broadcastNotSent` ONLY for a + /// `PlatformWalletError.shieldedBroadcastFailed` (refused before anything + /// was sent); every other error leaves `failureStage` nil (unattributed: + /// the progress view uses its elapsed-time heuristic) rather than + /// guessing a stage by elimination. func submit(body: @escaping () async throws -> Data) { switch phase { case .idle, .preparingKeys, .failed: @@ -229,9 +231,9 @@ final class IdentityRegistrationController: ObservableObject { self?.phase = .completed(identityId: identityId) } } catch let unconfirmed as ShieldedIdentityCreateUnconfirmedError { - // Broadcast landed but its result couldn't be confirmed and - // Rust's direct fetch came back empty. Hold the slot; the - // identity probably exists and will surface on the next sync. + // The transition may have reached a node; its result is not + // proved and Rust's direct fetch came back empty. Hold the slot; + // the identity may exist and would surface on a later sync. await MainActor.run { self?.terminalAt = Date() self?.phase = .unconfirmed( @@ -240,15 +242,15 @@ final class IdentityRegistrationController: ObservableObject { ) } } catch { - // Only a `shieldedBroadcastFailed` is a confidently-attributable - // broadcast rejection → mark the broadcast step. Everything else - // (Rust build / Halo 2 proof errors, which surface as a generic + // Only a `shieldedBroadcastFailed` (refused before anything was + // sent) is confidently attributable: mark the broadcast step. + // Everything else (Rust build / Halo 2 proof errors, which surface as a generic // `.walletOperation`, plus invalid-handle / marshalling failures) // is indistinguishable at this layer, so leave `failureStage` nil // and let the progress view's elapsed-time heuristic place it. let stage: FailureStage? if case PlatformWalletError.shieldedBroadcastFailed = error { - stage = .broadcastRejected + stage = .broadcastNotSent } else { stage = nil } diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift index d47274cd161..5c5d8974477 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift @@ -480,7 +480,7 @@ struct CreateIdentityView: View { Section { VStack(alignment: .leading, spacing: 8) { Label( - "Broadcast succeeded — confirmation pending", + "Result not confirmed", systemImage: "exclamationmark.triangle.fill" ) .foregroundColor(.orange) @@ -494,10 +494,10 @@ struct CreateIdentityView: View { .foregroundColor(.primary) .textSelection(.enabled) Text( - "The transition was broadcast and accepted, but its " - + "execution-result proof couldn't be confirmed. The " - + "identity will appear in the Identities tab after the " - + "next sync. Do NOT re-register these keys — the slot " + "The transition may have reached the network, but its " + + "result couldn't be confirmed. If it went through, the " + + "identity will appear in the Identities tab after a " + + "later sync. Do NOT re-register these keys: the slot " + "is held to prevent burning funds." ) .font(.caption) @@ -1541,8 +1541,8 @@ struct CreateIdentityView: View { // the inline failure state. return case .unconfirmed: - // Broadcast landed but its result couldn't be confirmed; - // the identity is probably already live on chain. Mark the + // The transition may have reached a node; its result is not + // proved, and the identity may already be live on chain. Mark the // slot used (same as `.completed`) — `usedIdentityIndices` // unions the persisted `isUsed` reservation with the // `PersistentIdentity` rows, so this is the reservation @@ -2134,8 +2134,8 @@ struct CreateIdentityView: View { /// identity-registration account. /// /// The union matters for `.unconfirmed` Type-20 registrations: the - /// broadcast landed but no `PersistentIdentity` row exists until the - /// next sync confirms the identity, so `markIdentitySlotUsed`'s + /// transition may have reached a node, yet no `PersistentIdentity` row + /// exists until the next sync confirms it, so `markIdentitySlotUsed`'s /// persisted `isUsed` flag is the ONLY artifact holding the slot once /// the in-memory controller is gone. Without it the same index would /// be offered again and a duplicate submission would burn funds diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/RegistrationProgressView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/RegistrationProgressView.swift index ca36b281edb..6a9d6e05e6c 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/RegistrationProgressView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/RegistrationProgressView.swift @@ -39,7 +39,7 @@ import SwiftDashSDK /// Step 4 ("Waiting for platform confirmation") exists so a /// post-broadcast confirmation failure is attributed there — NOT to the /// Halo 2 proof step — and so the `.unconfirmed` terminal state (the -/// broadcast landed but its result couldn't be confirmed) has a step to +/// transition may have reached a node but its result is not proved) has a step to /// render an orange warning on while steps 1–3 stay done and step 5 /// stays pending. /// @@ -253,7 +253,7 @@ struct RegistrationProgressSection: View { /// On `.completed` return 6 (one past the last step) so all rows /// render `.done`. On `.unconfirmed` return 4 ("Waiting for platform /// confirmation") so that step carries the warning. On `.failed` - /// attribute the step: a `.broadcastRejected` failure marks step 3 + /// attribute the step: a `.broadcastNotSent` failure marks step 3 /// ("Broadcasting transition"); an UNATTRIBUTED failure /// (`failureStage == nil` — build / Halo 2 proof errors, or any other /// error we can't confidently place) keeps the note-selection vs Halo 2 @@ -269,21 +269,21 @@ struct RegistrationProgressSection: View { case .completed: return 6 case .unconfirmed: - // Broadcast landed; only the result confirmation failed. + // The transition may have reached a node; its result is not proved. // Attribute to the "Waiting for platform confirmation" step. return 4 case .inFlight: return shieldedStep(elapsedTo: now) case .failed: - // A definitive broadcast rejection (`failureStage == - // .broadcastRejected`) is attributed to the broadcast step (3). + // A refusal before anything was sent (`failureStage == + // .broadcastNotSent`) is attributed to the broadcast step (3). // For an unattributed failure (`failureStage == nil` — build / // Halo 2 proof errors, or any other error we can't confidently // place), keep the elapsed-time heuristic (note-selection vs // proof) — frozen at the failure instant; fall back to `now` only // if the terminal timestamp is missing (pre-submit failure shapes // never set it). - if controller.failureStage == .broadcastRejected { + if controller.failureStage == .broadcastNotSent { return 3 } return shieldedStep(elapsedTo: controller.terminalAt ?? now) @@ -386,10 +386,10 @@ struct RegistrationProgressSection: View { /// fallback — visually distinguishable so users don't think /// the step "didn't happen yet" once we've moved past it. /// `.warning` (orange triangle) marks the "Waiting for platform - /// confirmation" step when the broadcast landed but its result - /// couldn't be confirmed (the shielded `.unconfirmed` terminal + /// confirmation" step when the transition may have reached a node but + /// its result is not proved (the shielded `.unconfirmed` terminal /// state) — distinct from `.failed` because nothing is actually - /// wrong; the identity is probably live on chain. + /// wrong; the identity may be live on chain. enum StepState { case done, active, pending, skipped, failed, warning } private func stepState( @@ -483,7 +483,7 @@ struct RegistrationProgressSection: View { .foregroundColor(.red) .font(.title3) case .warning: - // Broadcast landed but its result couldn't be confirmed — + // The transition may have reached a node; its result is not proved: // not an error, so an orange triangle, not the red octagon. Image(systemName: "exclamationmark.triangle.fill") .foregroundColor(.orange) @@ -607,14 +607,14 @@ struct RegistrationProgressView: View { Section { VStack(alignment: .leading, spacing: 8) { Label( - "Broadcast succeeded — confirmation pending", + "Result not confirmed", systemImage: "exclamationmark.triangle.fill" ) .foregroundColor(.orange) .font(.headline) // Same base58 styling as the completed case — the id is // the derived identity id Rust handed back; the identity - // is probably already live on chain. + // may already be live on chain. Text(identityId.toBase58String()) .font(.system(.caption, design: .monospaced)) .foregroundColor(.secondary) @@ -624,12 +624,11 @@ struct RegistrationProgressView: View { .foregroundColor(.primary) .textSelection(.enabled) Text( - "The transition was broadcast and accepted, but its " - + "execution-result proof couldn't be confirmed. The " - + "identity above will appear in the Identities tab " - + "after the next sync. Do NOT re-submit — the slot is " - + "held to prevent burning funds against a duplicate " - + "registration." + "The transition may have reached the network, but its " + + "result couldn't be confirmed. If it went through, the " + + "identity above will appear in the Identities tab after " + + "a later sync. Do NOT re-submit: the slot is held to " + + "prevent burning funds against a duplicate registration." ) .font(.caption) .foregroundColor(.secondary) diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/CreateIdentityResumableTests.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/CreateIdentityResumableTests.swift index 5514b577eb6..3dc6674d50a 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/CreateIdentityResumableTests.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/CreateIdentityResumableTests.swift @@ -419,7 +419,7 @@ final class CreateIdentityResumableTests: XCTestCase { identityIndex: 1, fundingKind: .shieldedPool ) { - throw PlatformWalletError.shieldedBroadcastFailed("rejected on merits") + throw PlatformWalletError.shieldedBroadcastFailed("no node address to send to") } for _ in 0..<200 { if case .failed = failing.phase { break }