Skip to content

Shielded spend fails with ShieldedMerkleWitnessUnavailable after an interrupted sync pass, and hosts get it as the generic ErrorWalletOperation (6) #6256

Backlog

Description

@romchornyi

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

  1. 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 NotContained at 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.

  2. The refusal crosses the FFI as code 6. map_spend_result has no arm for ShieldedMerkleWitnessUnavailable, so it falls through to the catch-all ErrorWalletOperation with the operation prefix. The identity-create-from-pool mapper does the same. On iOS this becomes PlatformWalletError.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:
    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:
    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:

  • 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.

Fix direction (branch fix/shielded-witness-unavailable-typed):

Left as they are, on purpose:

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.

  1. Receive a note in a shielded account (for example the change of a shielded transfer).
  2. 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).
  3. Relaunch and let a full sync pass complete with no new commitments on the network. The note is saved and shows in the balance.
  4. 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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions