Repository navigation
Description
Expected Behavior
A note the wallet shows as spendable can be witnessed at spend time. If it cannot, the refusal, which happens before any proof is built or anything is broadcast, reaches the host as a typed, retryable code, so the app can say "not sent, try again" instead of treating the payment as possibly sent.
Current Behavior
-
The note is past the latest checkpoint of the local commitment tree. A shielded spend (seen on a shielded withdrawal to a Core address; the transfer, unshield and pool top-up paths share the code) fails with:
shielded withdraw failed: Shielded Merkle witness unavailable: witness(<position>, depth 0): invalid frontier data: witness failed: Tree does not contain a root at address Address { level: Level(0), index: <position> }shardtree raises
NotContainedat depth 0 when the position is greater than the latest checkpoint's position, so the note's leaf is in the tree but no checkpoint covers it. Nothing is broadcast and the shielded balance does not move. The failure keeps repeating until a new commitment arrives on the network and the next sync checkpoints past it. -
The refusal crosses the FFI as code 6.
map_spend_resulthas no arm forShieldedMerkleWitnessUnavailable, so it falls through to the catch-allErrorWalletOperationwith the operation prefix. The identity-create-from-pool mapper does the same. On iOS this becomesPlatformWalletError.walletOperation(String). A host cannot tell it from a failure that may have been sent, so Dash Wallet iOS shows "Send in progress — it will finish on its own" and offers no Retry, for a payment that never left the wallet.
Possible Solution
Root cause (1): the sync pass checkpoints only when it appended something. Each append_commitment is persisted on its own (a SQLite savepoint per append in ClientPersistentCommitmentTree), and the checkpoint comes once, after the stream:
- appends inside the batch loop:
platform/packages/rs-platform-wallet/src/wallet/shielded/sync.rs
Lines 541 to 562 in 39ac391
for (i, raw_note) in batch.notes.iter().enumerate() { // A malformed nullifier length means the proven note item is corrupt; // fail fast (consistent with the cmx check below) rather than silently // dropping it — a dropped nullifier would leave a spent note marked // unspent. let nf_bytes = <[u8; 32]>::try_from(raw_note.nullifier.as_slice()).map_err(|_| { PlatformWalletError::ShieldedSyncFailed("Invalid nullifier length".into()) })?; scanned_nullifiers.push(nf_bytes); let global_pos = batch.start_index + i as u64; if global_pos < tree_size { continue; } let cmx_bytes: [u8; 32] = raw_note.cmx.as_slice().try_into().map_err(|_| { PlatformWalletError::ShieldedSyncFailed("Invalid cmx length".into()) })?; store .append_commitment(&cmx_bytes, true) .map_err(|e| PlatformWalletError::ShieldedTreeUpdateFailed(e.to_string()))?; appended += 1; leaves_committed += 1; - the checkpoint, gated on
appended > 0:platform/packages/rs-platform-wallet/src/wallet/shielded/sync.rs
Lines 665 to 693 in 39ac391
if appended > 0 { // Checkpoint at the tree's true post-append leaf count. The // tree only ever grows, so this id is strictly monotonic // and collision-free across consecutive syncs — unlike // `result.next_start_index` (rewinds to the last partial // chunk's start) or `aligned_start + total_notes_scanned` // (can repeat when a lagging subwallet rewinds the fetch). // shardtree's `checkpoint(id)` silently dedups duplicate // ids; a non-monotonic id pins depth-0 at the first // checkpoint while later appends extend the tree past it, // so the depth-0 witness then reflects a state Platform // never recorded. let new_tree_size = store .tree_size() .map_err(|e| PlatformWalletError::ShieldedStoreError(e.to_string()))?; // Hard-fail rather than saturate at u32::MAX: a saturated id // would reintroduce shardtree's silent-dedup (every checkpoint // past the ceiling pins to the same id) — the exact corruption // this monotonic-id scheme exists to avoid. Unreachable today // (>4.29B notes scanned) but fail loudly before proving. let checkpoint_id: u32 = new_tree_size.try_into().map_err(|_| { PlatformWalletError::ShieldedTreeUpdateFailed(format!( "commitment tree size {new_tree_size} exceeds u32 checkpoint-id range" )) })?; store .checkpoint_tree(checkpoint_id) .map_err(|e| PlatformWalletError::ShieldedTreeUpdateFailed(e.to_string()))?; }
A pass that appends leaves and then stops before the checkpoint (a batch error returned by ? at L512, an append error, or the process killed or suspended mid-pass) leaves those leaves past the latest checkpoint. The next pass gate-skips them (global_pos < tree_size), so appended == 0 and it never checkpoints them, while it does save the notes it decrypts at those positions. Spending such a note hits the strict depth-0 branch:
platform/packages/rs-platform-wallet/src/wallet/shielded/operations.rs
Lines 3385 to 3398 in 39ac391
for (position, note, cmx) in &prepared { let merkle_path = match store.witness_at_depth(*position, depth) { Ok(Some(path)) => path, Ok(None) if strict => { return Err(PlatformWalletError::ShieldedMerkleWitnessUnavailable(format!( "no witness available for note at position {position} (not marked, or pruned past this position)" ))); } Err(e) if strict => { return Err(PlatformWalletError::ShieldedMerkleWitnessUnavailable( e.to_string(), )); } // depth > 0: the note isn't witnessable at this older checkpoint
Root cause (2): no FFI code for the variant.
map_spend_resultcatch-all:platform/packages/rs-platform-wallet-ffi/src/shielded_send.rs
Lines 716 to 720 in 39ac391
), Err(e) => PlatformWalletFFIResult::err( PlatformWalletFFIResultCode::ErrorWalletOperation, format!("{operation} failed: {e}"), ), - identity create from the pool:
platform/packages/rs-platform-wallet-ffi/src/shielded_send.rs
Lines 1079 to 1083 in 39ac391
), Err(e) => PlatformWalletFFIResult::err( PlatformWalletFFIResultCode::ErrorWalletOperation, format!("shielded identity-create-from-pool failed: {e}"), ),
Fix direction (branch fix/shielded-witness-unavailable-typed):
- Sync: checkpoint at the tree size on every pass when the tree is non-empty, not only on a pass that appended.
checkpoint(id)is a no-op for an id not above the current maximum, and the id is the leaf count, so a pass over an already-checkpointed tree changes nothing and a pass after an interrupted one covers the leftover leaves. - FFI: new code
ErrorShieldedMerkleWitnessUnavailable = 85, mapped by the blanket conversion, bymap_spend_result(every note spend, with or without a plan, including private contact requests) and by the identity-create-from-pool mapper. 81–84 are held by open branches (feat: report a shielded identity create proven to have its inputs spent without its identity #5853, feat(platform-wallet): plan a shielded spend with its exact fee and spend against the plan #5865, feat(platform-wallet): top up someone else's identity from the Core balance #5931, feat(platform-wallet)!: give identity slots one wallet-owned lease #6014, feat: expose the Rust identity key layout to FFI, Swift and Kotlin hosts #5647), so it takes 85. Mirrors: Swift (PlatformWalletResultCode.errorShieldedMerkleWitnessUnavailable,PlatformWalletError.shieldedMerkleWitnessUnavailable) and Kotlin (DashSdkError.PlatformWallet.ShieldedMerkleWitnessUnavailable, retryable). - feat(platform-wallet): report whether a failed payment may have left the wallet #5928 (payment delivery classes) already classes the variant
NotSent, but itsis_retryablereturnsfalsefor it. With the sync fix, a retry after the next sync succeeds, so it should betruethere, likeShieldedNoRecordedAnchor.
Left as they are, on purpose:
ShieldedTreeUpdateFailedis raised only by sync, never on a spend path.ShieldedStoreErrorandShieldedBuildErrorare raised both before and after the broadcast (for examplemark_notes_spentafter an accepted broadcast), so a single "not sent" code would be wrong for them. feat(platform-wallet): report whether a failed payment may have left the wallet #5928 classes bothMaybeSent.- A failed fetch of the recorded anchor set is an
Sdkerror, which keeps its own classification; feat(platform-wallet): plan a shielded spend with its exact fee and spend against the plan #5865 reworks that fetch.
Steps to Reproduce (for bugs)
Natural reproduction needs a sync pass to stop between its appends and its checkpoint, and then no new commitments on the network before the spend.
- Receive a note in a shielded account (for example the change of a shielded transfer).
- Interrupt the sync pass that appends that note's commitment after the append and before the checkpoint (kill or suspend the app mid-sync, or have a later chunk fetch fail).
- Relaunch and let a full sync pass complete with no new commitments on the network. The note is saved and shows in the balance.
- Spend from the account so that the note is selected: the spend fails as above, and the host receives code 6.
The branch adds unit tests for this shape: should_checkpoint_leaves_a_failed_pass_appended_on_the_next_pass (a pass that appends and then fails on a batch error, store reopened, a pass that appends nothing: before the fix the depth-0 witness fails with NotContained), plus mapping tests for code 85 on every spend operation.
Context
On testnet this happened about once in six shielded-source sends in a day, right after an app relaunch, a few minutes after a shielded-to-shielded send whose change note was then selected. The user sees a send stuck "in progress" with no retry, while the shielded balance never moved. Related: #4144 (same error and message, Tree does not contain a root at address … level 0, reported on a large tree; possibly the same mechanism), #5865 (shielded spend plans, which also go through map_spend_result), #5928 (payment delivery classes).
Your Environment
- Version used:
v5.2-devat39ac391ea1; observed with an SDK build from feat(platform-wallet): plan a shielded spend with its exact fee and spend against the plan #5865 plus feat(swift-sdk): top up someone else's identity from the Core balance #6139 - Environment name and version: SwiftDashSDK in Dash Wallet iOS, testnet
- Operating System and version: iOS
- Link to your project: https://github.com/dashpay/dashwallet-ios
Activity