Skip to content

fix(platform-wallet): checkpoint the shielded tree on every sync pass and report an uncovered note as retryable code 88 - #6276

Merged
romchornyi merged 10 commits into
v5.2-devfrom
fix/shielded-witness-unavailable-typed
Nov 25, 2026
Merged

romchornyi merged 10 commits into
v5.2-devfrom
fix/shielded-witness-unavailable-typed

Conversation

@romchornyi

@romchornyi romchornyi commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Issue being fixed or feature implemented

Closes #6256.

A shielded spend could fail with ShieldedMerkleWitnessUnavailable ("Tree does not contain a root at address … level 0") and reach the host as the generic ErrorWalletOperation (6). Nothing had been proved or broadcast and the notes were released, but a host has to read code 6 as possibly sent. Dash Wallet iOS therefore showed the payment as in progress, with no retry.

There were two defects:

  • The sync pass checkpointed the tree only when it appended leaves itself. Each append is persisted on its own. A pass that appended and then stopped before its checkpoint (a batch error, an append error, or the app killed or suspended mid-sync) left leaves past the latest checkpoint. The next pass appended nothing, so it never checkpointed them, and it still saved the notes it found at those positions. Spending such a note failed at the depth-0 witness until a new commitment arrived on the network.
  • The FFI had no code for the variant, so it fell to the catch-all.

What was done?

Deferred to #5928. Other errors a note spend raises before anything is sent, such as a failed fetch of the recorded anchors (Sdk) or ShieldedBuildError, still cross the FFI as 6. That is because the FFI derives "not sent" per error variant, while the wallet core already decides it from state: settle_failed_spend knows whether a recovery record was saved before the broadcast. #5928 (payment delivery classes) moves that decision into the core and hands it to hosts as data, with the retry verdict next to it. This PR fixes only the variant with a specific cause and a specific user action ("wait for the next sync"). It adds no further per-variant lists.

How Has This Been Tested?

  • Sync tests (sync/cancel_tests.rs):
    • A pass appends leaves, then fails on a batch error before its checkpoint. The store is reopened, as after a relaunch, and the next pass appends nothing but still checkpoints, so the leaves can be witnessed. This test failed before the fix and passes after it.
    • An idle pass keeps the existing checkpoints on the file-backed store.
    • An idle pass adds no checkpoint on the in-memory store.
  • Spend-selection tests (operations.rs):
    • A note past the latest checkpoint gives ShieldedMerkleWitnessUnavailable.
    • A store failure at depth 0 (the shard table is gone) gives ShieldedStoreError.
    • A note whose position the tree does not hold gives ShieldedStoreError, not the retryable variant.
  • FFI tests:
    • 88, with code 19's wording, for every operation map_spend_result maps, the identity create from the pool included.
    • A store failure stays 6.
    • The blanket conversion is pinned to 88 and its wording.
    • The identity create from the pool, through its export's result handling (map_identity_create_from_pool_result): a witness refusal returns 88 and leaves the host's id buffer untouched; code 17 still writes the derived id.
  • Swift: ErrorHandlingTests (mac xcframework slice, swift test --filter ErrorHandlingTests).
  • Kotlin: DashSdkErrorTest (./gradlew :sdk:testDebugUnitTest).
  • Commands: cargo test -p platform-wallet --features shielded --lib; cargo test -p platform-wallet-ffi --lib, with and without shielded; cargo clippy with -D warnings and shielded; cargo fmt --all --check; scripts/check_sdk_parity_manifest.py.
  • Not tested: no device run. Killing the app between the append and the checkpoint is covered by the test's batch error plus store reopen, which leaves the same on-disk state.

Breaking Changes

No change to the native result layout or to any signature: one new result code and its mirrors. Source changes for SDK users:

  • Swift: PlatformWalletResultCode gains .errorShieldedMerkleWitnessUnavailable and PlatformWalletError gains .shieldedMerkleWitnessUnavailable. A switch over either without default no longer compiles until it handles the new case. Treat it like code 19: nothing was sent; show the message and offer a retry after the next shielded sync, e.g. case .shieldedMerkleWitnessUnavailable: showRetryAfterSync().
  • Kotlin: DashSdkError.PlatformWallet (sealed) gains the subtype ShieldedMerkleWitnessUnavailable (retryable). An exhaustive when used as an expression no longer compiles until it adds is DashSdkError.PlatformWallet.ShieldedMerkleWitnessUnavailable -> retryAfterSync() or an else branch.
  • Rust ShieldedStore implementors: witness_at_depth (and witness) may return Ok(None) only for a position the tree holds that no checkpoint at that depth covers yet. The old contract also allowed Ok(None) for an unmarked or pruned position; such a store must now return Err there, or the spend path tells the user to wait for a sync that will not help.

Behaviour visible to hosts:

  • A note spend refused because no checkpoint covers a selected note returns 88, where it returned 6.
  • A store failure while witnessing at depth 0 is now ShieldedStoreError. It still returns 6, with a different message.
  • The identity create from the pool returns the spend contract's other typed codes (for example 18, 20, 31, 41, 88) where it returned 6; 16, 19 and the catch-all keep their codes and messages.

Checklist:

  • I have performed a self-review of my own code
  • My Rust, FFI, WASM, Swift or Kotlin changes follow the coding conventions
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have added "!" to the title and described breaking changes in the corresponding section if my code contains any
  • I have made corresponding changes to the documentation if needed
  • If I added or changed GroveDB structure, I described it in the area's structure.rs, regenerated grovedb-structure.json, and checked the structure viewer link posted on this pull request
  • If I added or changed a system contract's document schemas, I checked the contract viewer link posted on this pull request

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Generated with Claude Code

PR Hygiene · 15652d3

  • Bots — thepastaclaw ✓
  • Self-review — posted; again after any push
  • Build green
  • Approvals
    • kotlin-sdk (packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt, packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt, packages/rs-unified-sdk-jni/src/funding.rs) — approved by HashEngineering
    • rs-platform-wallet-ffi (packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md, packages/rs-platform-wallet-ffi/src/error.rs, packages/rs-platform-wallet-ffi/src/shielded_send.rs) — approved by HashEngineering
    • rs-platform-wallet (packages/rs-platform-wallet/src/error.rs, packages/rs-platform-wallet/src/wallet/shielded/file_store.rs, packages/rs-platform-wallet/src/wallet/shielded/operations.rs and 3 more) — approved by HashEngineering
    • swift-sdk — you own it

When every merge requirement is met, the PR Hygiene check passes. Reviewer limits do not block merging; other required GitHub checks and protections still apply.

romchornyi and others added 4 commits November 25, 2026 00:29
…d sync pass

The sync pass checkpointed the tree only when it appended leaves itself.
Each append is persisted on its own, so a pass that appended and then
stopped before its checkpoint (a batch error, an append error, the process
killed or suspended mid-pass) left leaves past the latest checkpoint. The
next pass gate-skips those positions, appends nothing and so never
checkpointed them, while it saved the notes it decrypted there. Spending
such a note failed at the depth-0 witness with
ShieldedMerkleWitnessUnavailable ("Tree does not contain a root at address
... level 0") until a new commitment arrived on the network.

Checkpoint at the tree size on every pass when the tree is non-empty. The
id is the leaf count and shardtree ignores an id not above the current
maximum, so a pass over an already-checkpointed tree changes nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s own retryable code

A shielded spend whose selected note the local commitment tree cannot
witness is refused while the spend is assembled, before any proof is built
or anything broadcast, with the notes released. It crossed the FFI as the
generic ErrorWalletOperation (6), which a host must read as possibly sent,
so a wallet showed the payment as in progress with no retry.

Add ErrorShieldedMerkleWitnessUnavailable = 85 (81-84 are held by open
branches #5853, #5865, #5931, #6014 and #5647) and map
PlatformWalletError::ShieldedMerkleWitnessUnavailable to it in the blanket
conversion, in map_spend_result (transfer, unshield, withdraw, identity
top-up from the pool, private contact requests) and in the
identity-create-from-pool mapper, now a function so it can be tested.
Mirror it in Swift (PlatformWalletResultCode, init(ffi:),
PlatformWalletError.shieldedMerkleWitnessUnavailable) and Kotlin
(DashSdkError.PlatformWallet.ShieldedMerkleWitnessUnavailable, retryable),
and record it in the registry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ShieldedMerkleWitnessUnavailable, and so the retryable FFI code 85, also
covered every store failure of the depth-0 witness (an unreadable store, a
poisoned mutex, a covered position the tree cannot witness), which no sync
repairs. A host told to retry after the next sync would retry forever.

ShieldedStore::witness_at_depth now returns Ok(None) exactly when no
checkpoint at that depth covers the position. The file-backed store reads
the checkpoint's position before witnessing, as shardtree's NotContained
reaches it only as a flattened string. At depth 0, select_recorded_spends
maps Ok(None) to ShieldedMerkleWitnessUnavailable and Err to
ShieldedStoreError, which keeps the generic code; the unreachable empty
strict result is a ShieldedBuildError.

Code 85 now reads as code 19 ("Wallet is still syncing to a confirmed state
- try again shortly.", then the diagnostic) in map_spend_result and the
blanket conversion. The identity create from the pool delegates every error
but its unconfirmed broadcast (17) to map_spend_result instead of keeping a
third copy, so it gets the spend contract's typed codes; 16, 19 and the
catch-all keep their codes and messages. The variant, FFI, registry, Swift
and Kotlin docs state the narrowed meaning, the registry row drops the plan
clause (#5865's plan mapper must map 85), and the JNI comment lists 85.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…it in memory

Sync now calls checkpoint_tree on every pass, including passes that
appended nothing, and relies on an identifier not above the current maximum
being a no-op. Only shardtree behind the file-backed store guaranteed that,
and the trait did not say it. State it on ShieldedStore::checkpoint_tree and
make InMemoryShieldedStore skip a repeated identifier instead of recording
a duplicate checkpoint, with a test of an idle pass over the in-memory
store.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@github-actions github-actions Bot added this to the v5.2.0 milestone Nov 25, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added the waiting-bots Waiting for the review bots to report on this head label Nov 25, 2026
@thepastaclaw

thepastaclaw commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Final review complete — no blockers (commit 15652d3) · triage: normal

Resolved:
- packages/rs-platform-wallet/src/wallet/shielded/operations.rs: both
  sides appended tests at the end of select_recorded_spends_tests; kept
  this branch's witness-unavailable / store-error tests and v5.2-dev's
  recorded-anchor cache tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

Copy link
Copy Markdown
Contributor

Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Final validation — Phase 1 + Phase 2

Changes requested: 1 blocker

  • Result code 85 already means a pending shielded tip in the published v5.1 SDK — packages/rs-platform-wallet-ffi/src/error.rs:800 (new)
    Impact: Hosts that share numeric error handling across SDK versions can mistake a pending tip for a spend they can retry after sync, and the two Rust variants cannot coexist when the branches merge.

The PR checkpoints the nonempty local shielded tree even when a sync pass appends nothing, and adds a retryable witness error to the wallet FFI, Swift, and Kotlin SDKs. On the reviewed head, Rust workspace tests, Kotlin SDK build and tests, and the Swift frozen-schema check passed; Swift SDK build and tests and PR Hygiene were pending.

🔴 1 blocking | 🟡 5 suggestion(s)

Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 3: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.2-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 6: gpt-6.2-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 7: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); reviewer 8: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 9: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 10: gpt-6.2-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 11: gpt-6.2-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 12: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: normal by gpt-6.2-sol (effort low) — The change spans checkpoint recovery, witness error classification, and mobile bindings, but it does not change how notes are selected, proved, or broadcast, and it requires no storage migration.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (lane failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Second Phase-2 pass: on this first full review every Phase-2 reviewer also ran a second, independent time, and the verifier weighed both sets
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — rust-quality (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `packages/rs-platform-wallet-ffi/src/error.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/error.rs:800: Result code 85 already means a pending shielded tip in the published v5.1 SDK
  Impact: Hosts that share numeric error handling across SDK versions can mistake a pending tip for a spend they can retry after sync, and the two Rust variants cannot coexist when the branches merge.
  A host handling a pending tip must reconcile the earlier payment before resending; the end of the hold does not mean the earlier payment failed. The published `v5.1.0-dev.4` prerelease contains #6191 (`537bc3e387e`), which assigns 85 to `ErrorShieldedTipPending` and mirrors it in Swift and Kotlin. This PR's v5.2 base does not contain that commit, so local CI does not see the duplicate discriminant. Keep the published assignment and allocate a code free on both release lines (the v5.1 registry lists 88 as its next candidate), updating the registry, both mirrors, and the test pins together.

In `packages/rs-platform-wallet/src/wallet/shielded/file_store.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/shielded/file_store.rs:1577-1582: A note missing from the local tree gets retry advice that sync may never clear
  Impact: Users who restore notes against an older or empty commitment tree can keep getting told to sync and retry even when ordinary sync cannot recover the selected note's missing commitment.
  The retry message says the next sync can checkpoint a leaf that is already present, but this branch checks only checkpoint coverage. `restore_locked` restores notes and scan watermarks independently of the tree, and `sync_notes_from_stream` starts at the chunk containing the minimum watermark rather than clamping that start to the local tree tip. When that chunk starts beyond the tip, the scan skips the missing prefix. The failed Clear tracked in #6184 can leave the same state: the tree reset succeeds, but the purge fails and leaves notes and watermarks intact. The cache-invalidation test already selects position 50 from a four-leaf tree and expects the retryable variant. On a depth-zero coverage miss, check the live tree under the same store guard and return a store error for a missing position or failed tree read. Keep separate tests for an absent leaf and an appended leaf awaiting its checkpoint.
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/shielded/file_store.rs:1561-1575: Shielded spends now depend on GroveDB's internal checkpoint table layout
  Impact: A GroveDB checkpoint schema or depth-ordering change can break wallet spends at the SQL precheck even when GroveDB's witness API still works.
  Every witness probe queries `commitment_tree_checkpoints` through the wallet's recovery connection before GroveDB does its own lookup. The query matches the current layout, but copies a table name, column name, and ordering owned by GroveDB. Both the pinned and default GroveDB revisions flatten shardtree witness errors into `InvalidData(String)`, which explains the workaround. Track a typed witness outcome in `dashpay/grovedb` that uses the existing checkpoint lookup and distinguishes lack of coverage from storage or path failure, then remove the wallet-side SQL. GroveDB #653 tracks storage abstraction, not this witness outcome.

In `packages/rs-platform-wallet/src/wallet/shielded/store.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/shielded/store.rs:830-840: Existing custom shielded stores can report pruned notes as waiting for sync
  Impact: Rust SDK users whose custom store follows the previous witness contract can rebuild unchanged but receive retry advice for a pruned note that a new checkpoint cannot repair.
  The old public `witness_at_depth` contract explicitly allowed `Ok(None)` for unmarked or pruned positions. The signature is unchanged, but the depth-zero selector now treats any `Ok(None)` as confirmation that a checkpoint is all the note needs. The `witness` convenience method still documents the old meaning. Preserve the legacy meaning and use a defaulted typed lookup or coverage hook that requires stores to affirm the retryable case. If the stricter contract is intentional, document it as an implementor migration and update both methods' docs.

In `packages/rs-platform-wallet-ffi/src/shielded_send.rs`:
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/shielded_send.rs:3182-3205: The identity-create mapping test passes even if the export returns generic code 6
  Impact: An identity-create regression can drop the typed witness error or change the output-ID contract without failing the new test.
  The test passes an operation-name string to `map_spend_result`, but the witness arm does not use that string. It never exercises the identity-create export's delegation or the separate code-17 branch whose derived ID Swift and JNI read. Keep a test for the shared mapper and test the result handler used by the export with a sentinel ID buffer: the witness refusal must leave it untouched, while code 17 must write the derived ID. Neither case needs to build a proof or broadcast.

In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift:799-804: Exhaustive mobile wallet-error handlers need a new branch to rebuild
  Impact: Swift and Kotlin hosts with exhaustive wallet-error handlers must update their source before rebuilding against the new SDK, even if they never receive the new result.
  The PR notes the effect on Swift `PlatformWalletError` switches but describes the API as non-breaking. `PlatformWalletResultCode` also gains a public Swift case, and Kotlin adds a direct subtype to the public sealed `DashSdkError.PlatformWallet` hierarchy. Document the source compatibility change for both languages and show how to handle the new retryable outcome. The native result layout is unchanged, and the book reserves `!` for consensus breaks.
Out-of-scope follow-up suggestions (2)

These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.

  • A shielded worker panic can abort the host process — The unchanged block_on_worker implementation re-panics on a failed worker join. Existing C exports, including pool-funded identity creation, call it without the panic guard used by some sibling exports.
    • Follow-up: Resolve #3805 separately, preserving each export's unconfirmed-payment contract.
  • Other pre-broadcast failures still lose their delivery status at the FFI boundary — Anchor-fetch and spend-build failures already fell through to a generic result. This PR does not change their classification.
    • Follow-up: Continue the wallet-owned delivery classification in #5928, as documented in the PR.

@github-actions

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Nov 25, 2026
romchornyi and others added 3 commits November 25, 2026 15:25
…to 88

85 is ErrorShieldedTipPending on v5.1-dev (#6191, published in
v5.1.0-dev.4), and 86-87 are taken there too, so a host that shares
numeric handling across SDK versions could read a pending tip as a spend
to retry after sync. 88 is free on v5.1-dev, v5.2-dev and every open PR.

Applied at the Rust enum and its docs, the registry (row, next
allocatable 89, 85-87 recorded as held by v5.1-dev), the Swift raw value
and doc, the Kotlin fromNative arm and KDoc, and the Rust, Swift and
Kotlin test pins.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… error

witness_at_depth returns Ok(None) only for a leaf the tree holds that no
checkpoint covers yet, the case the next sync resolves. A position at or
past the tree size (notes restored against a shorter tree, or a tree
reset whose note purge failed) is not something a sync adds, so the file
store now returns Err there and the spend path reports
ShieldedStoreError instead of the retryable variant.

The trait docs state the contract, with a migration note for stores
that returned Ok(None) for unmarked or pruned positions; witness() points
to it. Tests: an absent leaf gives ShieldedStoreError, kept apart from
the held leaf awaiting its checkpoint; the cache-invalidation test's
position 50 now expects the store error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…export's result handling

The export's result handling is now map_identity_create_from_pool_result,
which the export calls. A test drives it with a sentinel id buffer: a
witness refusal returns 88 and leaves the buffer as set, and code 17
writes the derived id that Swift and JNI read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

…ess-unavailable-typed

# Conflicts:
#	packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md
#	packages/rs-platform-wallet-ffi/src/error.rs
#	packages/rs-platform-wallet-ffi/src/shielded_send.rs
#	packages/rs-platform-wallet/src/wallet/shielded/file_store.rs
#	packages/rs-platform-wallet/src/wallet/shielded/sync/cancel_tests.rs
#	packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

@romchornyi romchornyi changed the title fix(platform-wallet): checkpoint the shielded tree on every sync pass and report an uncovered note as retryable code 85 fix(platform-wallet): checkpoint the shielded tree on every sync pass and report an uncovered note as retryable code 88 Nov 25, 2026

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review — Final validation — Phase 1 + Phase 2

New on this head: This head merges the latest v5.2-dev base and updates shielded spend handling so code 88 tells callers to retry after sync when a local note is awaiting a checkpoint. Rust workspace tests, Kotlin SDK build and tests, and the Swift frozen-schema check passed; the Swift SDK build and tests and PR Hygiene are pending.

🔴 0 blocking | 🟡 0 suggestion(s) | 💬 0 nitpick(s)

Approved: nothing here blocks the merge. The non-blocking findings are optional: fix them forward, in this PR or a follow-up, without waiting for another review round.

Follow-up candidates (optional) (2)

New non-blocking observations on code unchanged since the last full review. No inline threads are opened for them and later reviews do not repeat them: fix forward or track separately if they are worth it.

🟡 Suggestion: Token spends get retry-after-sync advice when the local token tree cannot be rebuilt
Impact: Swift and Kotlin callers transferring or unshielding tokens can repeatedly get code 88 for a bad cached commitment that ordinary sync does not replace.
packages/rs-platform-wallet-ffi/src/shielded_send.rs:695-699

A successful sync can leave the user stuck with the same “try again shortly” message. The v5.2-dev merge brought in token transfer and unshield exports that both delegate through map_token_spend_result to this arm, changing these failures from generic code 6 to retryable code 88. In token_pool.rs:1226–1262, spend_paths already rebuilds and checkpoints a separate in-memory token tree on every attempt. It returns ShieldedMerkleWitnessUnavailable for build and witness failures, as well as for a selected note beyond the contiguous cached leaves. For example, GroveDB rejects a cached commitment that is not a valid field element, and apply_chunk uses INSERT OR IGNORE, so even refetching that position leaves the bad row in place. Classify token-tree build and witness failures as store errors in the Rust wallet, and keep missing token leaves distinct from a note awaiting a checkpoint. Add regression coverage that a token-tree failure does not return 88 but an uncovered credit-pool note paying the fee still does.

source: gpt-6.2-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality)

🟡 Suggestion: The code 88 documentation omits what happens when the note is missing from the local tree
Impact: FFI integrators using the result-code docs cannot see explicitly that a missing local leaf returns generic code 6 rather than retryable code 88.
packages/rs-platform-wallet-ffi/src/error.rs:847-848

The enum docs explain how to handle an uncovered note but omit the outcome for a note the tree does not hold. Commit 7f2bc653255 now returns a store error for that case instead of a retryable witness refusal, and the wallet error docs and registry already reflect the distinction. Add the missing-leaf case to the FFI enum docs so callers know that waiting for a checkpoint will not help.

    /// tree at its size. Only that case: a store that cannot produce the path
    /// (unreadable, poisoned, a position the tree does not hold, or a covered
    /// position the tree cannot witness)

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality)

Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 3: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.2-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 6: gpt-6.2-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 7: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: normal by gpt-6.2-sol (effort low) — The patch spans wallet sync, witness lookup, and SDK error mappings, but it changes checkpoint timing and pre-broadcast failure classification rather than spend selection, cryptography, or transaction execution.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (lane failed), glm-5.3-flash (not used above high effort; tier asks max)
  • New since the last final review (640ae875): 2 suggestion(s) on unchanged code listed as follow-up candidates
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — rust-quality (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify the current code and confirm that no unresolved issues remain.

No unresolved findings remain from the prior review on this head.

@github-actions

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

…ess-unavailable-typed

Conflict in rs-platform-wallet-ffi/src/error.rs: kept the retry-after-sync message for ShieldedMerkleWitnessUnavailable and the base's with_consensus_of.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review — Final validation — Phase 1 + Phase 2

New on this head: This round merges v5.2-dev’s Tokio update and invitation-claim preflight; the merge preserves shielded checkpoint recovery and code 88’s retry message alongside the base branch’s structured consensus-error metadata. Rust workspace and Kotlin SDK CI passed, as did the Swift code-88 test; the Swift SDK job’s only failure was a SQLite write-lock error in an unchanged historical migration test that does not exercise the shielded wallet path. PR Hygiene is pending.

🔴 0 blocking | 🟡 0 suggestion(s) | 💬 0 nitpick(s)

Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 3: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.2-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 6: gpt-6.2-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 7: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); reviewer 8: gpt-6.2-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: normal by gpt-6.2-sol (effort low) — The change spans persisted checkpoint recovery, witness error classification, and SDK error mappings, but it does not change which notes are selected, how funds move, how proofs are constructed, or the storage schema.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (lane failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — security-auditor (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify the current code and confirm that no unresolved issues remain.

No unresolved findings remain from the prior review on this head.

@github-actions

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

@HashEngineering HashEngineering left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at 15652d36ad for the kotlin-sdk side and downstream impact on the Android wallet. The checkpoint fix looks right to me, and so does code 88 as a pre-broadcast, retry-after-sync signal. The Kotlin change (ShieldedMerkleWitnessUnavailable, retryable, the 88 -> arm in fromNative) only marshals the code, which is what we want. A few things before I approve:

1. A token-pool tree that won't build now reports "retry after sync" (88)

rs-platform-wallet/src/wallet/shielded/token_pool.rs:1226-1230: the built closure maps every CommitmentTreeError from rebuilding a token pool's tree (append, checkpoint, anchor, witness) to ShieldedMerkleWitnessUnavailable ("the tree of the shielded pool of token … does not build"). Token transfer/unshield reach this through map_token_spend_result → map_spend_result, so a failure that used to come back as 6 now comes back as 88 with "Wallet is still syncing… try again shortly". No sync fixes a tree that does not build, so every retry fails the same way. Nothing is broadcast, so no funds are at risk, but it breaks the PR's point that the variant "now means one thing". Could that closure return ShieldedBuildError or ShieldedStoreError instead?

The "past the leaves kept; sync the shielded pools first" case at :1257 does fit 88. But then the registry row and KDoc should list token transfer / unshield / purchase among the operations that return it; today they only name the note-pool spends.

2. Registry / PR body wording (nits)

  • The 88 row says "77–82 are held by open branches", but 80 is already merged on v5.2-dev (ErrorIdentityLookupFailed). The PR body also says 83–84 are held by open branches, but both are merged.
  • The next-allocatable paragraph still describes 85–87 as proposed by the shielded tips branch.

3. Depth-0 mapping relies on GroveDB's private checkpoint table

I checked the Ok(None) → 88 path in file_store.rs against the pinned GroveDB (sql_helpers.rs) and shardtree 0.6.2 witness_at_checkpoint_depth. The query, offset and covered rule match today. Fine to leave this to dashpay/grovedb#1069 as you note.

Code numbering: 88 is free on both release lines, and I don't see it on any other open PR. My #5931/#5933 had planned to move to 88; I'll take 89 after this lands.

Downstream (dash-wallet feat/kotlin-sdk-phase-1): nothing to change in this PR. When dash-wallet moves to an SDK that includes it, classifyBroadcastFailure needs ShieldedMerkleWitnessUnavailable in its NotBroadcast group (next to ShieldedNoRecordedAnchor). Otherwise 88 falls through to "may be on chain", and a shielded username creation sticks at "may have gone through". I'll handle that on the wallet side.

Ran locally: platform-wallet shielded sync/select/token_pool tests (91 passed), platform-wallet-ffi witness/merkle/identity_create/map_spend tests (11 passed), Kotlin DashSdkErrorTest (45 passed), clippy -D warnings clean.

@HashEngineering HashEngineering left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving for kotlin-sdk: the Kotlin change only marshals code 88, and the checkpoint fix looks right. Please still look at the comments in my review above, mainly the token-pool tree-build error in token_pool.rs:1226 that now reports 88 (retry after sync) when a sync can't fix it, plus the registry wording nits.

@romchornyi

Copy link
Copy Markdown
Contributor Author

/self-reviewed

@github-actions

Copy link
Copy Markdown
Contributor

Policy satisfied — this can merge.
Full checklist in the description.

@github-actions github-actions Bot removed the waiting-self-review Waiting for the author to post /self-reviewed label Nov 25, 2026
@romchornyi
romchornyi merged commit d460be2 into v5.2-dev Nov 25, 2026
44 of 45 checks passed
@romchornyi
romchornyi deleted the fix/shielded-witness-unavailable-typed branch November 25, 2026 22:10
QuantumExplorer added a commit that referenced this pull request Nov 25, 2026
…cycle-boundary

One conflict, in the FFI's identity create from the pool: the base now
maps every remaining error through the spend contract (#6276), which
already covers the two refusals this branch mapped there by hand, so the
base's arm is kept.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
PastaPastaPasta added a commit that referenced this pull request Nov 25, 2026
@romchornyi

Copy link
Copy Markdown
Contributor Author

@HashEngineering thanks for the review. This merged before I got to it, so the fixes are in a follow-up: #6309.

  1. Token pool tree that won't build → 88. Agreed. In fix(platform-wallet): report a token pool tree that does not build as a store error #6309, a token pool tree that does not build from its kept leaves (append, checkpoint, anchor, witness) is ShieldedStoreError (code 6), like the note pool's store faults. The "past the leaves kept; sync the shielded pools first" case stays 88. Row 88 and the variant doc now list token transfer and unshield (token pool) and the token purchase from the pool among the spends that return it.
  2. Registry wording. Fixed in fix(platform-wallet): report a token pool tree that does not build as a store error #6309: row 88 says 80 is ErrorIdentityLookupFailed on v5.2-dev, and the numbering notes say 83–88 are merged. The fix(platform-wallet): checkpoint the shielded tree on every sync pass and report an uncovered note as retryable code 88 #6276 description is merged history, so I left it.
  3. GroveDB checkpoint table. Thanks for checking it against the pinned revision; it stays with commitment tree: return a typed witness outcome instead of a flattened error string grovedb#1069.

89 is yours for #5931/#5933. And thanks for the dash-wallet note on classifyBroadcastFailure.

romchornyi added a commit that referenced this pull request Nov 25, 2026
…let-payment-delivery

Brings in #6276 (code 88 `ErrorShieldedMerkleWitnessUnavailable`, the
retry-after-sync message) and #6288 (the unused broadcast-and-release
wrapper removed).

- FFI `error.rs`: kept this PR's `payment_class` / `outcome_message` beside
  the base's `retry_after_sync_message`.
- FFI `shielded_send.rs`: the identity create from the pool maps every
  other error through `map_spend_result`, as the base does; the result
  still carries the wallet error's class.
- JNI `funding.rs`: kept this PR's note that retry is the result's class,
  never the code.
- Swift: `shieldedMerkleWitnessUnavailable` carries `payment` like every
  case (declaration, `payment`, message, mapping).
- Code 88: Rust classes it NotSent (as before) and now retryable, the
  retry after sync #6276 promises, so `is_retryable` decides it. Kotlin's
  host-side `isRetryable = true` override goes: retry is the native flag.
  Registry row 88 states the class.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants