Repository navigation
feat(platform-wallet)!: detect inconsistent shielded commitment trees and add explicit rebuild - #5565
Claudius-Maginificent wants to merge 52 commits into
Conversation
…ncurrent shielded syncs Two syncs over the same shielded store snapshot the tree size under a read lock and append under a later write lock, so both append the same commitments (8 leaves instead of 4 cold, 6 instead of 4 resumed). Observed on testnet as witness roots matching no Platform-recorded anchor. Co-Authored-By: Codex <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_019H9THphMnuQyh9oPY13SoE
…hotting sync gates Hold the write guard from the tree-size/watermark snapshot through the streamed append, so a concurrent sync cannot append between them and make this pass re-append commitments already in the tree. The stream already ran under this guard; SDK fetches never touch the store. Co-Authored-By: Codex <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_019H9THphMnuQyh9oPY13SoE
…ify rebuild RED: a duplicated tree returns Ok instead of rejecting the sync (3 passed, 1 failed). Typed-error and rebuild contracts additionally fail compilation until their APIs exist. Fixtures are offline and deterministic. Co-Authored-By: OpenAI Codex <[email protected]> Co-Authored-By: Codex <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_019H9THphMnuQyh9oPY13SoE
… and add explicit rebuild Require a response at least as fresh as the tree's recorded height bound before diagnosing excess leaves. Persist the bound before corresponding appends in the same SQLite database; skip stale or unknown provenance and never infer a height from another response's speculative count. Expose explicit tree-only rebuild while retaining notes, nullifiers and spent status. Use indexed nullifier lookups during receipt reconciliation. Keep spend-time classification deferred and add no FFI or automatic repair. BREAKING CHANGE: exhaustive matches on PlatformWalletError must handle ShieldedTreeInconsistent. Existing method signatures are unchanged. Validation: 224 offline shielded tests; one-block-behind regression fails without freshness comparison and passes with it. Clippy all-targets / all-features with --no-deps -D warnings, cargo fmt --all, git diff --check. Co-Authored-By: OpenAI Codex <[email protected]> Co-Authored-By: Codex <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_019H9THphMnuQyh9oPY13SoE
|
Important Review skippedReview was skipped as selected files did not have any reviewable changes.
|
| Layer / File(s) | Summary |
|---|---|
Tree consistency evidence and outcomes packages/rs-platform-wallet/src/wallet/shielded/*, packages/rs-platform-wallet/src/manager/shielded_sync.rs, packages/rs-platform-wallet/src/error.rs |
Sync tracks tree provenance and compares local tree size with sufficiently fresh chain evidence. It reports a typed inconsistency with local and chain leaf counts. Tests cover detection, cancellation, rescan behavior, and related failure cases. |
Persisted rebuild recovery and restoration packages/rs-platform-wallet/src/wallet/shielded/file_store.rs, packages/rs-platform-wallet/src/wallet/shielded/store.rs, packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs, packages/rs-platform-wallet/src/wallet/platform_wallet.rs, packages/rs-platform-wallet/src/wallet/shielded/cancelled_scan_tests.rs, packages/rs-platform-wallet/src/wallet/shielded/token_pool.rs |
The store persists tree-height provenance, scan coverage, and spent nullifiers. Restore validates saved cursors and reapplies recorded spend state. Reset and purge changes update related data transactionally. |
Tree rebuild and sync lifecycle packages/rs-platform-wallet/src/manager/*, packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs, packages/rs-platform-wallet-ffi/src/handle.rs, packages/rs-platform-wallet-ffi/src/manager.rs, packages/rs-platform-wallet-ffi/src/shielded_sync.rs |
The manager drains shielded sync before rebuilding and restarts it only when its prior state and current stop conditions allow. The FFI adds a rebuild export, coordinates rebuild leases, and waits for admitted rebuilds during shutdown. |
Typed FFI outcomes packages/rs-platform-wallet-ffi/src/*, packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md |
The FFI adds result code 67 and typed per-wallet sync outcomes. The legacy result layout remains available, and the typed callback takes precedence when registered. |
Kotlin and Swift SDK integration packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/{errors,ffi,wallet}/*, packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/*, packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/*, packages/rs-unified-sdk-jni/src/*, packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/*, packages/swift-sdk/SwiftTests/SwiftDashSDKTests/* |
Both SDKs expose typed tree-inconsistency errors and a rebuild method. JNI and Swift callback wiring use the outcomes callback and pass per-wallet error codes to SDK results. |
Estimated code review effort: 5 (Critical) | ~90 minutes
Change: Feature
Sequence Diagram(s)
sequenceDiagram
participant PlatformWalletManager
participant SyncLoop
participant NetworkShieldedCoordinator
participant FileBackedShieldedStore
PlatformWalletManager->>SyncLoop: Drain shielded sync
PlatformWalletManager->>NetworkShieldedCoordinator: Rebuild shielded tree
NetworkShieldedCoordinator->>FileBackedShieldedStore: Reset tree and rewind scan watermarks
FileBackedShieldedStore-->>NetworkShieldedCoordinator: Return reset result
PlatformWalletManager->>SyncLoop: Restart when previously running and allowed
Possibly related issues
- fix(kotlin-sdk): drop buffered shielded sync events from before a Clear or rebuild #6449: The Swift SDK holds shielded completion events during rebuild drains and publishes them only when their generation remains current, which relates to stale buffered events after a rebuild.
Suggested reviewers: quantumexplorer, thepastaclaw, lklimek
Merge Risk: 
Moderate · up to f3b51
-
The new rebuild feature has several edge cases around interrupted or cancelled rebuilds, restart restore, and spent-note handling. These can leave a spent receipt selectable until the next scan, or return a non-retryable error for a note that a rescan would later fix. Resolve or explicitly accept these before merging; none is a broad outage.
Pre-merge checks: 
4
-
Full details: Title check
-
Explanation
The title names the main change: detection of inconsistent shielded commitment trees (ShieldedTreeInconsistent, error code 67) and a new explicit rebuild operation (rebuildShieldedTree / shielded_rebuild_tree). The raw summary and PR objectives both center on these two items across Rust, FFI, JNI, Kotlin and Swift. The title is specific and matches the changeset. It is long, at 94 characters, but it is still one sentence and conveys the primary change.
-
Finishing Touches
-
Generate unit tests (beta)
-
- Commit to this branch
- Create a new PR
-
- 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.
|
✅ Final review complete — no blockers (commit f3b517b) |
thepastaclaw
left a comment
There was a problem hiding this comment.
Final validation — Phase 1 + Phase 2
The tree consistency detection and preserving rebuild are generally coherent, but the advertised recovery path is unavailable to the FFI/mobile wallet consumers and the new typed error is flattened at that boundary. The implementation also has two non-blocking correctness and coverage gaps around proof-count freshness pairing and scan metadata after rebuild.
🔴 1 blocking | 🟡 3 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.1-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 6: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.1-sol(effort low) — This is a large, intricate change to shielded-wallet persistence and concurrent synchronization, including a SQLite storage migration and recovery logic that can affect note, nullifier, and spend-state integrity. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity quota lookup failed),glm-5.3-flash(not used above high effort; tier asks max) - Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
- Fresh verifier:
gpt-6.1-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.1-sol— general (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— rust-quality (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— security-auditor (completed, effort xhigh); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `packages/rs-platform-wallet/src/manager/mod.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/mod.rs:1038-1051: Expose the preserving rebuild and typed inconsistency result through FFI
The only non-destructive recovery operation, `rebuild_shielded_tree`, is reachable only through the Rust manager/coordinator API. No corresponding entry point exists in `rs-platform-wallet-ffi` or the Swift/Kotlin wrappers. The FFI sync path maps `ShieldedTreeInconsistent` to the generic `ErrorWalletOperation` with a rendered string, so mobile hosts cannot reliably distinguish this terminal tree condition from a transient sync failure or invoke the required repair. The existing `shielded_clear` operation is not equivalent because it removes registrations, notes, spent status, and related wallet state. Add a thin FFI marshal entry point for the Rust rebuild method and a stable result-code mapping for `ShieldedTreeInconsistent`.
In `packages/rs-platform-wallet/src/wallet/shielded/sync.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/shielded/sync.rs:418-420: Keep shielded count evidence paired with its proof height
`chain_leaf_count` is accumulated as the maximum of all emitted `batch.total_count` values, while `response_height` is accumulated independently. However, the SDK's `ShieldedChunkBatch.total_count` is itself a monotonic max across fetch completions, while `batch.block_height` belongs to the response that produced the emitted chunk. A stale or forked response with a larger count can therefore be carried into a batch emitted at a fresh height, causing the final gate to accept an excessive local tree because the stale larger count masks the fresh lower count. Preserve count and height as a pair, or only use count evidence from responses whose own proof height meets the recorded tree-height bound.
In `packages/rs-platform-wallet/src/wallet/shielded/file_store.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/shielded/file_store.rs:151-155: Reset host-visible scan metadata during a tree rebuild
`rewind_scan_watermarks` resets only `last_synced_index`, but `last_scanned_index` remains at the pre-rebuild value and `balance_source` remains `ScannedThisSession`. Until the rescan completes, `local_balance_snapshot` can therefore report the old scan coverage and a successfully scanned session even though the commitment tree has been emptied. Reset the session metadata as part of the same rewind while retaining the note ledger as restored state.
In `packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs:1338-1354: Test background sync handling of ShieldedTreeInconsistent
The typed `try_sync` path is tested, but the background `sync()` path is not tested for this new failure. `sync()` catches `ShieldedTreeInconsistent`, converts it through `fail_all_wallets`, and exposes per-wallet `Err(String)` outcomes to the event layer. Add a test that drives `sync(false)` with an excessive local tree and fresh count evidence, then asserts the per-wallet error outcome and error count before rebuilding.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tree-consistency Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ielded tree rewind_scan_watermarks reset only last_synced_index, so the local balance snapshot kept reporting the pre-rebuild last_scanned_index and a ScannedThisSession source while the commitment tree was empty. Clear the scan coverage with the cursor and mark retained notes as Restored (NoHistory when the account has none) until the rescan completes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t shielded tree Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ync test guards Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ream's fetch concurrency Name the note-sync stream's in-flight fetch bound so the concurrent sync test provisions exactly that many mocked chunks instead of a duplicated literal that could silently fall out of step. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tree-consistency Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tch concurrency Co-Authored-By: Claude Opus 5.5 <[email protected]>
… and restart sync after rebuild The background sync() path now reports an inconsistent commitment tree as WalletShieldedOutcome::TreeInconsistent instead of a stringified Err, so hosts detect it without matching message text. rebuild_shielded_tree restarts the background shielded sync loop it quiesced whenever the loop was running before, on every outcome, so the host no longer has to restart sync after the repair. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…le hosts - FFI: add ErrorShieldedTreeInconsistent = 67 (61-66 are claimed by open PRs #5395, #5487 and #5536), mapped by the blanket From and map_shielded_error; append error_code to ShieldedSyncWalletResultFFI so the sync-completed callback carries it per wallet; add the platform_wallet_manager_shielded_rebuild_tree export. - JNI: add shieldedRebuildTree; onShieldedSyncCompleted gains a trailing errorCode argument. - Kotlin: PlatformWalletManager.rebuildShieldedTree(), typed DashSdkError.PlatformWallet.ShieldedTreeInconsistent and WalletSyncEvent.ShieldedResult.error. - Swift: PlatformWalletManager.rebuildShieldedTree(), typed PlatformWalletError.shieldedTreeInconsistent and ShieldedWalletSyncResult.error. The appended repr(C) field changes the callback array layout: Swift and Kotlin must ship with the matching native library. Co-Authored-By: Claude Opus 5.5 <[email protected]>
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
The Rust implementation correctly detects excess shielded-tree leaves, preserves the local ledger during rebuild, and now tests the typed background-sync failure path. A blocking mobile integration gap remains: the new terminal condition and preserving rebuild are not exposed through the FFI or mobile wrappers, leaving hosts with only a generic error and destructive clear operation. The restart-before-rescan metadata issue and a concurrent unregister attribution race also remain; the Kotlin build check is queued and policy reconciliation is still in progress, with no failing code check in the supplied CI snapshot.
🔴 1 blocking | 🟡 2 suggestion(s)
1 carried-forward finding(s) already raised on this PR; not re-posting as new inline comments.
Review provenance
Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 3: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 6: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.1-sol(effort low) — This is a large, intricate change to wallet shielded-tree persistence and recovery, including a SQLite storage migration and concurrency-sensitive logic that affects spend availability and preservation of spent state. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity quota lookup failed),glm-5.3-flash(not used above high effort; tier asks max) - Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
- Fresh verifier:
gpt-6.1-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.1-sol— general (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— rust-quality (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— security-auditor (completed, effort xhigh); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs:1298-1307: Reset host-visible scan metadata during a tree rebuild
`rebuild_shielded_tree` rewinds only the coordinator's in-memory scan state. It does not emit a host-persistence update, so a process restart before the next full scan can restore the old persisted watermark and scan metadata through `restore_balance_metadata` while the SQLite commitment tree is empty. The next sync can recover because its local watermark is capped by the tree size, but a pre-rescan balance snapshot can still report stale scan coverage and restored state. Persist an explicit rebuild/reset marker or otherwise invalidate persisted scan metadata when the tree is reset, and cover the restart-before-rescan sequence.
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs:1341-1351: Preserve the pass snapshot when reporting sync errors
`try_sync` snapshots the registered subwallets before the network pass, but `sync` re-reads `self.accounts` after `try_sync` returns an error. Because `unregister_wallet` can run concurrently and the sync path does not hold the coordinator lifecycle mutex, the error summary can omit a wallet that participated in the failed pass or attribute the failure to a newly registered wallet with the same identifier. Preserve the original pass snapshot for the error-reporting path and use it when calling `fail_all_wallets`.
In `packages/rs-platform-wallet/src/manager/mod.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/mod.rs:1038-1051: Expose the preserving rebuild and typed inconsistency result through FFI
(existing thread: https://github.com/dashpay/platform/pull/5565#discussion_r4365720739)
The new `rebuild_shielded_tree` operation exists only on the Rust manager/coordinator. `platform_wallet_manager_shielded_sync_wallet` still routes `ShieldedTreeInconsistent` through `map_shielded_error`, which maps it to generic `ErrorWalletOperation` with a rendered message, and no FFI export or Swift/Kotlin wrapper invokes the preserving rebuild. Consequently mobile hosts cannot reliably distinguish this terminal condition from a transient sync failure or perform the non-destructive repair. `platform_wallet_manager_shielded_clear` is not equivalent because it removes registrations, notes, spent status, reservations, and related recovery state. The PR's Rust-only framing does not remove this responsibility because the advertised recovery flow is intended for wallet applications and there is no linked follow-up tracking the required FFI work.
…d win rebuild_shielded_tree restarted background sync whenever it was running before, so a stop or Clear issued while the rebuild was in flight was silently undone. ShieldedSyncManager now counts stop requests (stop, quiesce, Clear) and restarts only if none arrived since the rebuild began; one lock spans that check and the start, so no stop slips between them. The internal quiesce used by rebuild cancels the loop without recording a stop request. Co-Authored-By: Claude Opus 5.5 <[email protected]>
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
The PR correctly adds typed inconsistency reporting and a preserving rebuild across the Rust, FFI, JNI, Swift, and Kotlin layers. Two blocking lifecycle/correctness defects remain: count-only detection can permanently miss an initially oversized but misaligned tree after chain growth, and failed or timed-out rebuilds can restart background sync against a closed or partially reset tree. Several non-blocking state and callback consistency issues also remain.
🔴 2 blocking | 🟡 4 suggestion(s)
1 finding(s) not shown inline (the lines are not part of this PR's diff)
🟡 Suggestion: Suppress buffered Kotlin completion events after shielded-tree rebuild
packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt:263-267
The native callback bridge places shielded completion events into a buffered MutableSharedFlow with _syncEvents.tryEmit, but the Kotlin manager has no generation or invalidation boundary for rebuilds. A ShieldedTreeInconsistent event admitted before or during rebuildShieldedTree() can remain buffered and be delivered after the rebuild succeeds and background sync restarts, causing the host to display the repair state again or offer a redundant rebuild. Invalidate events admitted before the rebuild, or carry a native lifecycle generation through the callback and discard stale events.
source: gpt-6.1-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality, security-auditor)
2 carried-forward finding(s) already raised on this PR; not re-posting as new inline comments.
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.1-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 6: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 7: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); reviewer 8: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 9: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 10: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 11: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 12: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.1-sol(effort low) — This is a large, intricate change that modifies persisted wallet storage and recovery semantics in packages/rs-platform-wallet/src/wallet/shielded/file_store.rs, while also changing cross-language ABI surfaces. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity quota lookup failed),glm-5.3-flash(not used above high effort; tier asks max) - Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
- Fresh final gate: an independent Phase-2 review ran after iterative findings were reconciled
- Fresh verifier:
gpt-6.1-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.1-sol— general (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— rust-quality (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— security-auditor (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— general (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— rust-quality (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— security-auditor (completed, effort xhigh); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `packages/rs-platform-wallet/src/wallet/shielded/sync.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/shielded/sync.rs:555-566: Count-only detection can miss a corrupted tree after chain growth
The inconsistency verdict only checks whether `local_leaf_count > chain_leaf_count`; it never validates that the commitments at the overlapping positions match. For example, a concurrent-append defect can leave the local tree as `[A, B, B]` while the chain is `[A, B]`. If the chain appends `C` before the next check, both counts become three, so this condition no longer fires even though position two is wrong. The append gate at lines 468-470 then treats every fetched position as already present, skips the real `C`, advances the watermark, and leaves the tree permanently misaligned. This is different from the documented same-size-corruption limitation because the corruption initially has an excess leaf; ordinary chain growth masks the count inequality before detection. Compare authenticated commitment/root evidence for the overlapping range, or persist a durable rebuild-required marker as soon as an excess tree is observed.
In `packages/rs-platform-wallet/src/manager/mod.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/mod.rs:1042-1053: Do not restart background sync after a failed tree rebuild
The restart decision depends only on whether the worker was running before the operation, so it restarts even when `rebuild_shielded_tree_quiesced()` returns an error. The reset rewinds in-memory cursors before deleting several SQLite tables, checkpointing the WAL, and reopening the commitment-tree wrapper. A delete, checkpoint, or reopen failure can therefore leave the on-disk tables partially reset while the live wrapper still holds its old frontier; restarting sync in that state can append or skip against inconsistent tree state. The same problem occurs on a quiesce timeout: the gate is intentionally latched closed, but this code restarts a worker whose `sync_now` calls will immediately bail, leaving `is_running()` true while admission remains blocked. Restart only after a successful rebuild, and leave the worker stopped after any reset or quiesce error.
In `packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt`:
- [SUGGESTION] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt:263-267: Suppress buffered Kotlin completion events after shielded-tree rebuild
The native callback bridge places shielded completion events into a buffered `MutableSharedFlow` with `_syncEvents.tryEmit`, but the Kotlin manager has no generation or invalidation boundary for rebuilds. A `ShieldedTreeInconsistent` event admitted before or during `rebuildShieldedTree()` can remain buffered and be delivered after the rebuild succeeds and background sync restarts, causing the host to display the repair state again or offer a redundant rebuild. Invalidate events admitted before the rebuild, or carry a native lifecycle generation through the callback and discard stale events.
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift:493-502: Coordinate Swift callback generations with the native rebuild restart
Rust restarts background sync inside `platform_wallet_manager_shielded_rebuild_tree`, before this Swift method increments `shieldedSyncGeneration`. A callback from the newly restarted pass can therefore snapshot the pre-rebuild generation on the FFI thread. Its MainActor task is queued while the synchronous rebuild call is still executing; after the native call returns, Swift bumps the generation and the legitimate post-rebuild callback is discarded as stale. Bracket the rebuild/restart lifecycle with an explicit callback-generation protocol, or defer the Rust restart until the host has invalidated callbacks.
In `packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs:1340-1352: Preserve the pass snapshot when reporting sync errors
(existing thread: https://github.com/dashpay/platform/pull/5565#discussion_r4403439232)
`try_sync` snapshots the registered subwallets before the awaited network pass, but `sync` reconstructs the wallet list from `self.accounts` only after the pass fails. A concurrent unregister can remove a wallet that participated in the failed pass, so it receives no failure outcome; a concurrent registration can add a wallet that did not participate, so it receives an error for a pass it never ran. Carry the pre-pass snapshot through the error path and use it for `fail_all_wallets`.
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs:1298-1307: Reset host-visible scan metadata during a tree rebuild
(existing thread: https://github.com/dashpay/platform/pull/5565#discussion_r4403439226)
`rewind_scan_watermarks` now resets the coordinator's in-memory cursors, but the host-persisted `ShieldedSyncStartState` remains unchanged. If the process exits after a successful rebuild and before the next full scan, the next bind restores the old watermark through the advance-only `restore_balance_metadata` path. The sync path caps that watermark to the empty tree and will eventually rescan safely, but host-visible balance metadata can still claim the old scan coverage before that rescan completes. Persist an explicit rebuild/reset marker or otherwise invalidate the host persistence as part of the rebuild, and cover a restart before the first rescan.
The tree reset ran its five DELETEs as separate auto-committed statements, and the rebuild rewound scan cursors before the reset. A failure partway through left a half-emptied tree under a stale live frontier, with cursors already at zero. The background sync restarted by `rebuild_shielded_tree` then ran on that half-reset state. The DELETEs and the replacement tree wrapper are now staged in one transaction. The wrapper opens on the staging connection, so it reads the uncommitted empty state, and the live tree is swapped only after COMMIT. Any earlier failure rolls back. The rebuild rewinds cursors only once the live tree is empty, so a failed reset leaves both untouched and the next pass reports the same inconsistency. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01WunYYjpfLux1ByK7fGF7SG
…e timeout A quiesce timeout latched the sync gate, and only a later successful drain cleared it. `rebuild_shielded_tree` still restarts background sync on that path, so the restarted loop reported `is_running()` while every pass bailed on the latched gate. The rebuild resets nothing when its quiesce times out, so it now drains with the new `DrainTimeout::Release` policy. That policy drops only its own hold and sets no latch. Passes resume once the wedged pass releases `is_syncing`. Stop, Clear and shutdown keep the latching drain, and a latch set by an earlier drain stays. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01WunYYjpfLux1ByK7fGF7SG
… it ran for Splitting out `try_sync` made the error path of `sync()` re-read the account registry. A wallet registered or unregistered mid-pass then changed which wallets the failure was reported for. `sync()` and `try_sync()` now share `run_pass`, whose failure carries the pass's own subwallet snapshot. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01WunYYjpfLux1ByK7fGF7SG
|
On the Kotlin 🤖 Co-authored by Claudius the Magnificent AI Agent |
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
The typed inconsistency signal, transactional tree replacement, pass-snapshot attribution, and mobile plumbing are implemented correctly. Two blocking lifecycle/correctness issues remain: count-only detection can be masked by subsequent chain growth, and a prior quiesce latch can cause the automatic restart to run without admitting any passes. Several non-blocking callback, persistence, durability, and async-threading issues also remain. CI checks covering policy/runner selection were still pending at the supplied snapshot.
🔴 2 blocking | 🟡 5 suggestion(s)
1 finding(s) not shown inline (the lines are not part of this PR's diff)
🟡 Suggestion: Suppress buffered Kotlin completion events after shielded-tree rebuild
packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt:263-267
The Kotlin MutableSharedFlow has extraBufferCapacity = 256 and no generation or reset fence around rebuild or Clear. An active slow collector can receive a pre-rebuild ShieldedTreeInconsistent completion after the native tree has already been successfully reset and rescanning has begun. The flow's replay = 0 does not discard events already buffered for active collectors. This became actionable in this PR because code 67 is a terminal, repair-triggering result; add an owner-controlled generation/reset epoch or an equivalent ordered invalidation boundary.
source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality); gpt-6.1-sol (phase2-reviewer: general, ffi-engineer, rust-quality)
3 carried-forward finding(s) already raised on this PR; not re-posting as new inline comments.
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.1-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 6: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 7: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)
- Triage:
normalbygpt-6.1-sol(effort low) — This is a large, intricate cross-language change to wallet storage, synchronization, recovery logic, and FFI/ABI surfaces, but it does not itself modify consensus, funds movement, cryptography, key handling, peer-facing deserialization, or a storage migration. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity quota lookup failed),glm-5.3-flash(not used above high effort; tier asks max) - Fresh verifier:
gpt-6.1-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.1-sol— general (completed, effort high); agentphase2-reviewer,gpt-6.1-sol— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.1-sol— ffi-engineer (completed, effort high); agentphase2-reviewer,gpt-6.1-sol— rust-quality (completed, effort high); agentphase2-reviewer,gpt-6.1-sol— security-auditor (completed, effort high); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `packages/rs-platform-wallet/src/manager/mod.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/mod.rs:1090-1093: Do not restart while an earlier quiesce latch remains
`quiesce_held_releasing_within` releases only its own hold on timeout; an older latch created by a previous timed-out `quiesce` remains set. If the current rebuild also times out while the pass is wedged, `was_running` can still be true and `restart_unless_stopped_since` starts a worker while the gate remains closed. That worker reports as running but every pass exits at the quiescing-gate check, and no later event clears the old latch. The rebuild must not restart until admission is known to be open, or it must clear an old latch only after a successful drain.
- [SUGGESTION] packages/rs-platform-wallet/src/manager/mod.rs:1090-1093: Do not synchronously reap the worker from an async rebuild future
`rebuild_shielded_tree_within` is async but directly calls `restart_unless_stopped_since`, which calls `ThreadRegistry::start_thread`. The registry documents that restart can synchronously spin for up to its reap backstop and must not be called directly from an async context; on a current-thread runtime it can also hit the registry's multi-thread assertion. Move the restart/reap operation to `spawn_blocking` with join-error propagation, or expose an async-safe registry restart API.
In `packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt`:
- [SUGGESTION] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt:263-267: Suppress buffered Kotlin completion events after shielded-tree rebuild
The Kotlin `MutableSharedFlow` has `extraBufferCapacity = 256` and no generation or reset fence around rebuild or Clear. An active slow collector can receive a pre-rebuild `ShieldedTreeInconsistent` completion after the native tree has already been successfully reset and rescanning has begun. The flow's `replay = 0` does not discard events already buffered for active collectors. This became actionable in this PR because code 67 is a terminal, repair-triggering result; add an owner-controlled generation/reset epoch or an equivalent ordered invalidation boundary.
In `packages/rs-platform-wallet/src/wallet/shielded/file_store.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/shielded/file_store.rs:1098-1121: Classify post-commit checkpoint failures separately from reset failures
`reset_commitment_tree` swaps in the empty live tree after `COMMIT`, then runs `PRAGMA wal_checkpoint(TRUNCATE)` and returns an error if that checkpoint fails. The coordinator consequently rewinds cursors and the manager restarts background sync even though the public rebuild operation reports failure. The logical tree is consistent, but the documented all-or-nothing contract says a failed reset leaves state untouched, and hosts cannot distinguish a committed reset with reduced crash durability from a rolled-back reset that should be retried. Return a distinct committed-but-not-checkpointed result or otherwise make the post-commit state explicit to callers.
In `packages/rs-platform-wallet/src/wallet/shielded/sync.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/shielded/sync.rs:555-567: Count-only detection can miss a corrupted tree after chain growth
(existing thread: https://github.com/dashpay/platform/pull/5565#discussion_r4405452073)
The verdict still compares only `local_leaf_count > chain_leaf_count`; it does not compare authenticated commitments in the overlapping range or persist a rebuild-required marker. A local tree such as `[A, B, B]` versus chain `[A, B]` is initially detectable, but after the chain appends `C`, both counts become three and the check no longer fires. The append gate then skips position two because `global_pos < tree_size`, advances the watermark, and preserves the wrong commitment permanently. The documented absence of root/size evidence explains why the check is difficult, but the PR introduces the detection/rebuild path and this untracked limitation can defeat its stated recovery goal. Add authenticated overlap/root validation or persist a durable rebuild-required state as soon as excess leaves are observed.
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift:493-502: Coordinate Swift callback generations with the native rebuild restart
(existing thread: https://github.com/dashpay/platform/pull/5565#discussion_r4405452122)
Rust restarts background sync before this Swift method increments `shieldedSyncGeneration`. The FFI trampoline captures the current generation before enqueueing its `Task { @MainActor ... }`; therefore a fast failure or early progress/completion callback from the restarted pass can capture the old generation, remain queued while the synchronous rebuild call is executing, and then be discarded after the method bumps the generation. The full rescan makes the window unlikely but does not guarantee that no callback occurs during it. Coordinate the lifecycle epoch with the Rust restart or invalidate the host generation before the restart can begin.
In `packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs:1300-1316: Reset host-visible scan metadata during a tree rebuild
(existing thread: https://github.com/dashpay/platform/pull/5565#discussion_r4403439226)
`rewind_scan_watermarks` now resets Rust-side cursors and balance provenance, but `rebuild_shielded_tree` emits no invalidation for the Swift and Kotlin persistence rows. Those rows merge watermarks monotonically, so a restart before rescanning can restore the old host-visible scan coverage while the native tree is empty; the native cap prevents unsafe skipping, but UI and persisted status remain falsely advanced until the rescan catches up. Add a durable reset epoch or explicit host reset callback shared with Clear. The PR description defers this work but provides no tracking reference, so it cannot be treated as a resolved follow-up.
"All or nothing" oversold the reset. The transaction is atomic, but the durability checkpoint runs after COMMIT, so it can report an error for a reset that took effect. Say so where callers read it: the next sync rescans, and a retry just resets again. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01WunYYjpfLux1ByK7fGF7SG
…o a latched gate A rebuild restarted the background loop even when an earlier stop's timed-out drain still latched the gate, leaving a loop that reported running while every pass bailed. It now leaves the loop stopped in that case; a retry that drains clears the latch and the host starts the loop. The restart also reaped the prior loop thread on an async worker, spinning for up to the registry backstop against the contract on start_thread. It now runs on the blocking pool. If that task panics or is cancelled after a successful reset, the call returns ShieldedSyncRestartFailed, which reaches FFI hosts as ErrorWalletOperation, so the C ABI is unchanged. A failed reset keeps its own error. should_admit_passes_after_restart_when_rebuild_quiesce_times_out raced the restarted loop's first pass for the sync slot once the restart left the worker; it now waits for a completed pass, and still fails on a closed gate. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01WunYYjpfLux1ByK7fGF7SG
|
Ready for review — |
|
Per maintainer decision, addressed in the follow-up PR #6481. 🤖 Co-authored by Claudius the Magnificent AI Agent |
romchornyi
left a comment
There was a problem hiding this comment.
🟡 2 major (inline) · 9 non-blocking recommendations · no blockers — reviewed at f3b517b685
Scope: rs-platform-wallet, rs-platform-wallet-ffi and swift-sdk. Kotlin and JNI were not reviewed.
| Level | Verdict | |
|---|---|---|
| 1 · Idea | 🟡 interim fix | #5564 removed the cause; the rebuild is the lasting value. Detection cannot fire for trees damaged before this PR, which are the ones the bug hit (deferred, as the thread on sync.rs:566 says). |
| 2 · Architecture | ✅ right layer | Detection, rebuild order and restart rule live in Rust; FFI marshals. Swift holds sync events around a rebuild and Kotlin does not (#6449). |
| 3 · Completeness | 🟡 untracked gaps | Four "Known limitations" have no issue (list below). |
| 4 · Code | 🟡 2 major | Both inline. |
Major (inline)
mod.rs#L1452— a hoststartor manual sync issued while a rebuild holds the clearing latch returns Success and does nothing, so background sync can stay stopped after the rebuild.sync.rs#L1036— a code-67 verdict returns before notes are saved and spends applied, so the note ledger of every wallet on the coordinator freezes until the host rebuilds.
Level 3: Known limitations without an issue
- Spend-time classification, legacy trees with no height bound, and chain growth masking excess leaves.
- Host scan rows left ahead of real coverage after a rebuild.
- Offline balance taken from the host snapshot before the first post-reset commit.
- Clear resetting the tree before a purge that can fail.
9 non-blocking recommendations
- One killed launch after any reset costs a full pool rescan —
sync.rs#L1223,file_store.rs#L625— coverage is replaced in SQLite before the pass changeset reaches the host, andtree_scan_resetis never cleared. A kill or persister failure in between leaves coverage above the host cursor, so restore returnsNoneand the next pass starts from 0. Keeping the previous coverage row, or writing coverage after the host persists, avoids it. ShieldedSyncRestartFailedreaches the host as code 6 —mod.rs#L1432— the reset took effect but sync is stopped. A host that retries the rebuild getsOkwithwas_running == false, so sync stays stopped, and Swift publishes the held code-67 completion. Same rule as #6446 (Rust must say whether the reset took effect), different trigger; worth adding there. Rare on iOS (panic = "abort").- A send during the post-rebuild rescan fails with
ShieldedStoreError—file_store.rs#L2028— for a note above the rebuilt tree's size, instead of the retryableShieldedMerkleWitnessUnavailable(88).ShieldedStoreErroris classedMaybeSent. (Not traced whether the send path rewraps it.) sync_walletnow returns the pass's raw error —shielded_sync.rs#L650— before, a failed pass becameShieldedSyncFailed. Nowmap_shielded_errorattaches the raw error's payment class (MaybeSentfor a store error) to a call that moves no money, and the warn log is gone.try_syncalso dropsPassFailure.subwallets, so a wallet unregistered between the check and the snapshot can get another wallet's failure;sync()was fixed for exactly that.- One unparsable host note row fails every bind —
coordinator.rs#L1818— when its nullifier is a recorded spend,restore_lockedreturnsErr, and only Clear gets the wallet out. The store already holds that spend, so skipping the row loses nothing. _ =>overPlatformWalletError—coordinator.rs#L2781—fail_all_walletstypes onlyShieldedTreeInconsistent, whilemap_shielded_erroralso types the two recovery errors. One shared classifier with every variant named would keep the background and explicit paths from drifting.- The cancelled-prefix check propagates a store error —
sync.rs#L999—snapshot_still_current(...)?turns a read error during a requested stop into a failed sync. Treating it like a busy store (returnCancelled) matches the comment above it. - Tests — Swift
rebuildShieldedTree(held completion, generation bump, progress drop) has none; the rebuild export's codes 84 and 27 are untested; nothing shows destroy waiting for an in-flight rebuild. - Conventions —
a_dpns_era_event_extension_refuses_the_shielded_outcomes_slotandreset_commitment_tree_reports_a_busy_checkpoint_and_stays_appliedlack theshouldprefix;handle.rsandcoordinator.rsadd inlinecrate::paths (AGENTS.md).
Review details
Levels 1–3 by a separate reviewer. Level 4: /code-review high, four specialist lanes (funds, concurrency, persistence, FFI), and six edge-case lanes (failure injection, ordering and restart, ownership and legacy data, cross-layer parity, FFI and concurrency, tests). Both majors and recommendations 1, 2, 4, 5 and 6 were checked against the code by hand. Points already raised in the threads or tracked in #6446–#6449, #6452, #6454, #6455 and #5695 are not repeated.
🤖 Reviewed with Claude Code
| &self, | ||
| budget: Duration, | ||
| ) -> Result<(), PlatformWalletError> { | ||
| let _clearing = self.registry.hold_clearing(WalletWorker::ShieldedSync); |
There was a problem hiding this comment.
Major: a start during a rebuild is silently lost
While this latch is held, WorkerRegistry::start_thread returns without starting (rs-dash-async/src/registry.rs:379), but platform_wallet_manager_shielded_sync_start still returns Success (rs-platform-wallet-ffi/src/shielded_sync.rs:234). Swift's startShieldedSync, syncShieldedNow and syncShieldedWalletNow check only shieldedStopsInFlight (PlatformWalletManagerShieldedSync.swift:330), not shieldedRebuildsInFlight.
- Sync stopped → host calls
rebuildShieldedTree()→ during the quiesce or reset the app callsstartShieldedSync()→ Success, nothing starts → the rebuild seeswas_running == falseand does not restart. The tree is empty and nothing rescans. - Sync running → stop then start during the rebuild → the stop bumps
stop_intents, the start is swallowed → the rebuild skips its restart, though the host's last call was start.
Either refuse these calls while a rebuild is in flight (the Swift guard already gives that reason for an async stop), let the native start report the refusal, or record start intents for the rebuild to honour.
| return Ok(superseded(leaves_committed)); | ||
| } | ||
|
|
||
| check_tree_size( |
There was a problem hiding this comment.
Major: code 67 freezes the note ledger for every wallet until the host rebuilds
check_tree_size returns here, before save_note (L1124) and apply_scanned_nullifier_spends (L1179). run_pass then fails for every wallet on the coordinator, so release_stranded_spends and the spend re-drives do not run either. On every pass until rebuild_shielded_tree is called:
- incoming notes are not saved, so the balance is too low;
- notes spent on another device stay spendable in the ledger;
- stranded reservations are not released.
Before this PR the same overfull tree broke spending but kept the ledger right. Note positions come from the chain's global position, not from the local tree, so only the checkpoint and the cursor advance need to be withheld. A host that ships this SDK without wiring code 67 to the rebuild gets a frozen shielded balance for exactly the affected wallets.
Basic explanation
What this does: Lets a wallet app detect when its local shielded payment data contains extra entries and offer a repair that preserves payment history and remembers what has already been spent.
Value: Wallet apps get a specific error during both manual and background sync and can request the repair with one call. A repair can get shielded payments working again while keeping the app's saved data.
Risks:
Issue being fixed or feature implemented
When overlapping syncs duplicated entries in the wallet's local copy of shielded payment data, payments could get stuck. #5564 prevents those duplicates. Wallet apps can detect excess entries and offer a repair for affected wallets without clearing their saved data.
User story
As a mobile wallet user whose shielded payments keep failing, I want the app to tell me when my wallet needs repair and let me request it in one tap while keeping my payment history.
Scenario
What was done?
Detailed discussion
Detection
ShieldedChunkBatch.total_countemitted in the pass, independently of the progress denominator.ShieldedTreeInconsistent { local_leaf_count, chain_leaf_count }before checkpointing or advancing scan cursors when the local size exceeds that count and at least one emitted response reaches the tree's recorded height bound. A cancelled prefix can also prove the inconsistency if the scan snapshot is still current. When the source is stale or the bound is unknown, the excess count is logged at debug level and the scan cursors are never rewound by the check.Restoring scan coverage
Typed signal on both sync paths
NetworkShieldedCoordinator::try_syncandShieldedSyncManager::sync_walletkeep typed failures.sync()path reports the verdict as the newWalletShieldedOutcome::TreeInconsistent { local_leaf_count, chain_leaf_count }, not asErr(String). Hosts never match message text.Repair owns its call order
PlatformWalletManager::rebuild_shielded_treeresets only the tree and scan cursors. Notes, nullifiers, spent status, reservations and registrations survive.DrainTimeout::Release), and passes resume once the wedged pass ends. Stop, Clear and shutdown keep the latching drain. If an earlier stop's timed-out drain already latched the gate, the rebuild does not restart the loop into a gate that bars every pass; once a retry drains, the host starts the loop again. This covers the rebuild's own restart only: a hoststartfrom a stopped and latched state still reportsis_running()while every pass bails, until a later drain clears the latch. Concurrent rebuilds run one at a time. The restart runs on the blocking pool, and if that task dies after a successful reset the call returnsShieldedSyncRestartFailed(ErrorWalletOperationover FFI, no C ABI change).stop,quiesce, or the FFI/Swift/Kotlin stop) or a Clear that stops sync while the rebuild is in flight wins: the rebuild skips its restart.ShieldedSyncManagercounts stop requests under a lock that also covers the rebuild's "unchanged? then start" step, so no stop can slip between the check and the restart. Hosts need no guard of their own.FFI, JNI, Swift and Kotlin
These layers only marshal; every decision stays in Rust.
PlatformWalletFFIResultCode::ErrorShieldedTreeInconsistent = 67.From<PlatformWalletError>and bymap_shielded_error, which coversplatform_wallet_manager_shielded_sync_walletand the new rebuild export.EventHandlerCallbacksExtension::on_shielded_sync_outcomes_fnreceivesShieldedSyncWalletOutcomeFFI, containing the original result and anerror_code. The new slot is read only when the extension's declared size includes it.Successfor successful and skipped wallets,ErrorShieldedTreeInconsistentfor excess leaves, orErrorWalletOperationfor any other failure. The original result still carries the message.platform_wallet_manager_shielded_rebuild_tree(handle) -> PlatformWalletFFIResultis available in shielded builds.ErrorShutdownIncomplete. An admitted shielded operation that prevents the reset returnsErrorShieldedOperationInProgress(84). Other operation failures go throughmap_shielded_error.rs-unified-sdk-jni):Java_org_dashfoundation_dashsdk_ffi_WalletManagerNative_shieldedRebuildTreein shielded builds.onShieldedSyncCompletedgains a trailingerrorCode: Int. Its descriptor becomes([BZZZIJIJLjava/lang/String;I)V.WalletManagerNative.shieldedRebuildTree(managerHandle).PlatformWalletManager.rebuildShieldedTree()(suspend, runs onDispatchers.IO).DashSdkError.PlatformWallet.ShieldedTreeInconsistent(code 67, not retryable).DashSdkError.fromPlatformWalletCode(code, message).WalletSyncEvent.ShieldedResult.errorCodeand its typederror: DashSdkError?.NativeWalletEventBridge.onShieldedSyncCompleted(..., errorCode).PlatformWalletManager.rebuildShieldedTree()(async, runs the native call off the main actor).PlatformWalletResultCode.errorShieldedTreeInconsistent = 67.PlatformWalletError.shieldedTreeInconsistent(String).ShieldedWalletSyncResult.errorCodeand its typederror: PlatformWalletError?.Known limitations
ShieldedAnchorscontains only roots, without heights or tree sizes. A missing root cannot reliably distinguish a wallet that is behind or mid-block from a corrupted one. Chain growth can mask excess leaves before the first fresh check. A legacy tree with no recorded height bound also cannot be diagnosed until a proof covers its existing tail. A tree already overfull from the fix(platform-wallet): stop concurrent shielded syncs from duplicating commitments #5564 bug may require an explicit rebuild without a prior code 67.How Has This Been Tested?
The shielded Rust regression tests use deterministic SDK mocks and temporary SQLite stores.
An earlier all-features Nextest run for
platform-wallet,platform-wallet-ffi, andrs-unified-sdk-jnipassed 4,111 tests, with 8 skipped.cargo fmtandcargo clippy -p platform-wallet -p platform-wallet-ffi --all-targets --all-features -- -D warningspassed.cargo nextest run -p platform-wallet --all-featurespassed 3,111 tests with 3 skipped.Coverage for detection and repair
Selected regression tests
tree_consistency_tests::should_rebuild_tree_preserving_notes_and_spends_then_match_recorded_anchorchecks the typed background result and that the rebuilt tree matches the recorded anchor.cancel_tests::should_report_an_inconsistent_tree_proved_by_a_cancelled_prefixcancelled_scan_tests::should_recover_a_missing_receipt_after_an_interrupted_rebuildcancelled_scan_tests::should_keep_a_complete_ledger_without_duplicates_after_an_interrupted_rebuildcancelled_scan_tests::should_restore_completed_rebuild_cursor_after_local_spendcancelled_scan_tests::should_restore_completed_rebuild_cursor_without_local_spendshould_exclude_recorded_spends_from_a_stale_host_snapshot_after_restartchecks that restore keeps the verified cursor, excludes the spent receipt from the balance and marks the host row spent before any sync. Restoring the corrected snapshot emits no further changeset.manager::tests::should_restart_background_shielded_sync_after_rebuild_when_it_was_runningmanager::tests::should_leave_background_shielded_sync_stopped_after_rebuild_when_it_was_not_runningmanager::tests::should_restart_background_shielded_sync_when_rebuild_failsmanager::tests::should_not_restart_background_shielded_sync_stopped_during_rebuildmanager::tests::should_admit_passes_after_restart_when_rebuild_quiesce_times_outtree_consistency_tests::should_leave_tree_and_cursors_untouched_when_rebuild_reset_failstree_consistency_tests::should_attribute_a_failed_pass_to_the_wallets_it_snapshotted: a failed background pass is attributed to the wallets it snapshotted, even when one unregisters mid-pass.error::tests::should_map_shielded_tree_inconsistent_to_pinned_code_67shielded_sync::recovery_error_tests::should_preserve_recovery_errors_when_configuring_binding_or_syncingcovers the inconsistent-tree error.event_handler::release_tests::should_report_typed_error_codes_through_the_shielded_sync_callbackevent_handler::release_tests::should_keep_the_legacy_shielded_result_layoutmanager::tests::a_dpns_era_event_extension_refuses_the_shielded_outcomes_slotshielded_sync::rebuild_tree_tests::should_reject_rebuild_on_an_invalid_handleshielded_sync::rebuild_tree_tests::should_rebuild_tree_keep_registration_and_restore_background_syncEarlier cross-crate checks
platform-wallet,platform-wallet-ffiandrs-unified-sdk-jniwith all features and targets,--no-depsand-D warnings.The SDK CI workflows cover the following mobile tests. They were not run locally.
DashSdkErrorTest.shouldMapAnInconsistentShieldedTreeToItsTypedErrorandWalletEventFanOutTest.shouldTypeAnInconsistentShieldedTreeFromItsResultCode.ErrorHandlingTests.testShouldPreserveShieldedTreeInconsistentFromFFIandErrorHandlingTests.testShouldTypeShieldedSyncCallbackResultFromItsErrorCode.Breaking Changes
PLATFORM_WALLET_MANAGER_STORAGE.remove(handle)returnsOption<WalletManagerHandle>. The entry implementsDeref<Target = PlatformWalletManager<FFIPersister>>for borrowed access. Useplatform_wallet_manager_destroyto tear down a registered manager and wait for its rebuild lease.PlatformWalletErrorgainsShieldedTreeInconsistentandShieldedSyncRestartFailed.WalletShieldedOutcomegainsTreeInconsistent. Exhaustive matches must handle the new variants.PlatformWalletFFIResultCodealso gainsErrorShieldedTreeInconsistent.EventHandlerCallbacksExtensionwith a full struct literal must include the new slot or use the default for it.sync_walletbehaviour.ShieldedSyncFailed.ShieldedSyncWalletResultFFIare unchanged. Legacy hosts keep receiving the original result from the legacy callback. Hosts opt in to typed outcomes through the size-negotiated extension slot.onShieldedSyncCompletedsignature gains a trailingerrorCode: Int. CustomNativeWalletEventBridgesubclasses that override it must add the parameter and recompile. Precompiled overrides of the old signature no longer receive per-wallet results.WalletSyncEvent.ShieldedResultadds a defaulted constructor parameter. Callers must recompile against its updated JVM constructor and generatedcopysignatures. Exhaustivewhenexpressions overDashSdkError.PlatformWalletmust handle the new subtype.PlatformWalletResultCodeorPlatformWalletErrormust handle the new case.Checklist:
structure.rs, regeneratedgrovedb-structure.json, and checked the structure viewer link posted on this pull requestFor repository code-owners and collaborators only
🤖 Generated with Claude Code
https://claude.ai/code/session_01WunYYjpfLux1ByK7fGF7SG
🤖 Co-authored by Claudius the Magnificent AI Agent
PR Hygiene ·
f3b517bkotlin-sdk(packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/FfiSmokeTest.kt,packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/ffi/ShieldedSyncTestHook.kt,packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/wallet/WalletManagerRoundTripTest.ktand 9 more) — HashEngineeringrs-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/event_handler.rsand 4 more) — HashEngineering or ZocoLini or llbartekll or romchornyirs-platform-wallet(packages/rs-platform-wallet/src/error.rs,packages/rs-platform-wallet/src/manager/mod.rs,packages/rs-platform-wallet/src/manager/shielded_sync.rsand 13 more) — HashEngineering or ZocoLini or llbartekll or romchornyiswift-sdk(packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift,packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerAddressSync.swift,packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swiftand 3 more) — llbartekll or romchornyiWhen every merge requirement is met, the
PR Hygienecheck passes. Reviewer limits do not block merging; other required GitHub checks and protections still apply.Summary by CodeRabbit