Registry Mirror
Skip to content

Conversation

@Claudius-Maginificent

@Claudius-Maginificent Claudius-Maginificent commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

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:

  • No consensus changes.
  • Repair downloads and scans the full shielded payment history again, which can take time and use significant bandwidth.
  • Detection requires sufficiently recent network data. An already damaged wallet may still need a manual repair, and damage that leaves the number of entries unchanged falls outside the check.

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

  1. During background sync, the wallet checks its local payment data against a recent network response.
  2. If the wallet finds extra entries, the app receives a specific error and can offer a repair. A manual sync can report the same problem.
  3. The user accepts the repair. The app keeps its saved history and the wallet resets the local data it needs to rebuild.
  4. Background sync resumes if it was running and the user has left it enabled. It scans from the beginning. If that scan is interrupted, the wallet revisits any part it could not verify as complete.
  5. Once the scan finishes, shielded payments can use the rebuilt data.

What was done?

Detailed discussion

Detection

  • The sync compares the local tree size with the maximum proof-derived ShieldedChunkBatch.total_count emitted in the pass, independently of the progress denominator.
  • The sync returns 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.
  • The tree's SQLite database stores the height bound before the corresponding leaves are appended. Reset clears it. For a legacy tree, only a chunk that includes its existing last leaf can establish the bound. A proof-derived count alone is insufficient.

Restoring scan coverage

  • Reset invalidates completed scan cursors. Rust can resume at a recorded cursor when the host cursor reaches it and the account's receipt digest matches under the registered viewing key. Missing receipts or unusable coverage require a rescan from zero.
  • Each completed post-reset scan commits the receipt digest and newly recorded spends together. The Rust store keeps spent nullifiers in a separate account-scoped table across coverage resets and rewrites. A stale host spent flag preserves an otherwise verified cursor.
  • Restore validates the viewing key for all receipts matching recorded spends before loading any account from the snapshot. When a host receipt still says unspent, restore sends the store's spent copy and its nullifier through the scan persister. A rescan also sends the effective spent flag for rediscovered receipts.
  • A successful purge deletes spend evidence for its scope in the same transaction as the token-pool and applicable pending-spend records.

Typed signal on both sync paths

  • NetworkShieldedCoordinator::try_sync and ShieldedSyncManager::sync_wallet keep typed failures.
  • The background sync() path reports the verdict as the new WalletShieldedOutcome::TreeInconsistent { local_leaf_count, chain_leaf_count }, not as Err(String). Hosts never match message text.

Repair owns its call order

  • PlatformWalletManager::rebuild_shielded_tree resets only the tree and scan cursors. Notes, nullifiers, spent status, reservations and registrations survive.
  • It quiesces background sync for the reset and attempts to restart it if it was running before, including after a failed reset or a quiesce timeout. Restarting after a failure follows the state of the tree:
    • The reset itself is atomic. The tree-table DELETEs and the replacement tree wrapper are staged in one SQLite transaction, and the live tree is swapped only after COMMIT. Scan cursors are rewound whenever the live tree is empty. A reset that rolls back leaves a non-empty tree and its cursors untouched, so the next pass can report the same inconsistency. A durability checkpoint that fails or is busy after COMMIT also returns an error, but the reset has then taken effect (only a power loss or OS crash could still undo it), so the next sync rescans and a retry just resets again. Clear returns the same error and fails closed, so the host keeps its rows and retries.
    • A quiesce timeout resets nothing, so the rebuild drains without latching the sync gate (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 host start from a stopped and latched state still reports is_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 returns ShieldedSyncRestartFailed (ErrorWalletOperation over FFI, no C ABI change).
  • A stop (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. ShieldedSyncManager counts 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.
  • The rebuild is never invoked automatically. Its bandwidth and trial-decryption cost is the host's call.

FFI, JNI, Swift and Kotlin

These layers only marshal; every decision stays in Rust.

  • New result code PlatformWalletFFIResultCode::ErrorShieldedTreeInconsistent = 67.
    • Mapped by the blanket From<PlatformWalletError> and by map_shielded_error, which covers platform_wallet_manager_shielded_sync_wallet and the new rebuild export.
    • Code 67 is recorded in the error code registry, which lists 93 as the next allocatable integer.
  • Typed completion callback. EventHandlerCallbacksExtension::on_shielded_sync_outcomes_fn receives ShieldedSyncWalletOutcomeFFI, containing the original result and an error_code. The new slot is read only when the extension's declared size includes it.
    • The code is Success for successful and skipped wallets, ErrorShieldedTreeInconsistent for excess leaves, or ErrorWalletOperation for any other failure. The original result still carries the message.
    • When the typed slot is registered, it receives the pass once. Otherwise the legacy completion slot receives the original result array with its existing layout and message.
  • New FFI export. platform_wallet_manager_shielded_rebuild_tree(handle) -> PlatformWalletFFIResult is available in shielded builds.
    • The export releases the shared manager registry lock before waiting for repair. Stop and calls for other managers can still look up their handles while a repair waits.
    • A quiesce timeout returns ErrorShutdownIncomplete. An admitted shielded operation that prevents the reset returns ErrorShieldedOperationInProgress (84). Other operation failures go through map_shielded_error.
  • JNI (rs-unified-sdk-jni):
    • New Java_org_dashfoundation_dashsdk_ffi_WalletManagerNative_shieldedRebuildTree in shielded builds.
    • onShieldedSyncCompleted gains a trailing errorCode: Int. Its descriptor becomes ([BZZZIJIJLjava/lang/String;I)V.
  • Kotlin:
    • WalletManagerNative.shieldedRebuildTree(managerHandle).
    • PlatformWalletManager.rebuildShieldedTree() (suspend, runs on Dispatchers.IO).
    • DashSdkError.PlatformWallet.ShieldedTreeInconsistent (code 67, not retryable).
    • DashSdkError.fromPlatformWalletCode(code, message).
    • WalletSyncEvent.ShieldedResult.errorCode and its typed error: DashSdkError?.
    • NativeWalletEventBridge.onShieldedSyncCompleted(..., errorCode).
  • Swift:
    • PlatformWalletManager.rebuildShieldedTree() (async, runs the native call off the main actor).
    • A successful rebuild discards stale sync completion and progress events through the same generation check as Clear.
    • PlatformWalletResultCode.errorShieldedTreeInconsistent = 67.
    • PlatformWalletError.shieldedTreeInconsistent(String).
    • ShieldedWalletSyncResult.errorCode and its typed error: PlatformWalletError?.

Known limitations

  • Spend-time classification is out of scope. ShieldedAnchors contains 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.
  • Rebuild leaves host-persisted scan rows in place. Swift and Kotlin persist those rows advance-only, so a stored cursor can remain ahead of actual coverage. On restore, Rust uses the verified coverage described above.
  • Rust records spend evidence when a completed post-reset scan commits coverage. Before that first commit, the offline balance reflects the host snapshot. A lagging source can delay discovery of a spend that neither store has recorded.
  • Clear resets the tree before purging wallet data. If a token-pool delete fails, the tree can already be empty. The host keeps its snapshot, and Rust keeps the spend evidence and pending-debit guards for retry.
  • Swift can deliver an older repair prompt when the reset committed but the storage checkpoint reported an error. #6446
  • Cancelling an in-flight rebuild from Rust can leave background shielded sync stopped. #6447
  • A stop can wait for an in-progress restart before its own timeout starts. #6448
  • A slow Kotlin collector can receive an older repair prompt after a Clear or rebuild. #6449

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, and rs-unified-sdk-jni passed 4,111 tests, with 8 skipped.

  • cargo fmt and cargo clippy -p platform-wallet -p platform-wallet-ffi --all-targets --all-features -- -D warnings passed. cargo nextest run -p platform-wallet --all-features passed 3,111 tests with 3 skipped.

Coverage for detection and repair

  • concurrent syncs;
  • healthy, behind and stale sources;
  • provenance across a SQLite reopen;
  • speculative totals;
  • typed detection and explicit rebuild;
  • spent-note preservation and restored cursors;
  • cooldown reset;
  • witness roots against mocked anchors.

Selected regression tests

  • tree_consistency_tests::should_rebuild_tree_preserving_notes_and_spends_then_match_recorded_anchor checks the typed background result and that the rebuilt tree matches the recorded anchor.
  • cancel_tests::should_report_an_inconsistent_tree_proved_by_a_cancelled_prefix
  • cancelled_scan_tests::should_recover_a_missing_receipt_after_an_interrupted_rebuild
  • cancelled_scan_tests::should_keep_a_complete_ledger_without_duplicates_after_an_interrupted_rebuild
  • cancelled_scan_tests::should_restore_completed_rebuild_cursor_after_local_spend
  • cancelled_scan_tests::should_restore_completed_rebuild_cursor_without_local_spend
  • A cancelled scan publishes no partial receipts.
  • should_exclude_recorded_spends_from_a_stale_host_snapshot_after_restart checks 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.
  • After restart with no host receipts, a source ending before the spent action rediscovers the receipt. The Rust note and the host changeset both mark it spent.
  • An unreadable digest forces a rescan. The recorded spend still applies before the rescan, and the repaired cursor survives a second reopen. A wrong-key receipt aborts restore before any account is written.
  • SQLite trigger tests cover rollback and retry of a coverage write, all three purge scopes, and an actual failed Clear followed by reopen with an active identity-debit guard.
  • manager::tests::should_restart_background_shielded_sync_after_rebuild_when_it_was_running
  • manager::tests::should_leave_background_shielded_sync_stopped_after_rebuild_when_it_was_not_running
  • manager::tests::should_restart_background_shielded_sync_when_rebuild_fails
  • manager::tests::should_not_restart_background_shielded_sync_stopped_during_rebuild
  • manager::tests::should_admit_passes_after_restart_when_rebuild_quiesce_times_out
  • tree_consistency_tests::should_leave_tree_and_cursors_untouched_when_rebuild_reset_fails
  • tree_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_67
  • shielded_sync::recovery_error_tests::should_preserve_recovery_errors_when_configuring_binding_or_syncing covers the inconsistent-tree error.
  • event_handler::release_tests::should_report_typed_error_codes_through_the_shielded_sync_callback
  • event_handler::release_tests::should_keep_the_legacy_shielded_result_layout
  • manager::tests::a_dpns_era_event_extension_refuses_the_shielded_outcomes_slot
  • shielded_sync::rebuild_tree_tests::should_reject_rebuild_on_an_invalid_handle
  • shielded_sync::rebuild_tree_tests::should_rebuild_tree_keep_registration_and_restore_background_sync

Earlier cross-crate checks

  • Clippy passed for platform-wallet, platform-wallet-ffi and rs-unified-sdk-jni with all features and targets, --no-deps and -D warnings.
  • Rust formatting was checked for the affected crates.

The SDK CI workflows cover the following mobile tests. They were not run locally.

  • Kotlin unit tests: DashSdkErrorTest.shouldMapAnInconsistentShieldedTreeToItsTypedError and WalletEventFanOutTest.shouldTypeAnInconsistentShieldedTreeFromItsResultCode.
  • Swift unit tests: ErrorHandlingTests.testShouldPreserveShieldedTreeInconsistentFromFFI and ErrorHandlingTests.testShouldTypeShieldedSyncCallbackResultFromItsErrorCode.

Breaking Changes

  • Rust API.
    • PLATFORM_WALLET_MANAGER_STORAGE.remove(handle) returns Option<WalletManagerHandle>. The entry implements Deref<Target = PlatformWalletManager<FFIPersister>> for borrowed access. Use platform_wallet_manager_destroy to tear down a registered manager and wait for its rebuild lease.
    • PlatformWalletError gains ShieldedTreeInconsistent and ShieldedSyncRestartFailed. WalletShieldedOutcome gains TreeInconsistent. Exhaustive matches must handle the new variants.
    • The Rust enum PlatformWalletFFIResultCode also gains ErrorShieldedTreeInconsistent.
    • Rust code that constructs EventHandlerCallbacksExtension with a full struct literal must include the new slot or use the default for it.
  • sync_wallet behaviour.
    • An unregistered wallet id returns without starting a network-wide pass.
    • Pass-level failures return their typed variants. A per-wallet string failure still returns ShieldedSyncFailed.
  • C ABI. Existing FFI function signatures and the layout of ShieldedSyncWalletResultFFI are unchanged. Legacy hosts keep receiving the original result from the legacy callback. Hosts opt in to typed outcomes through the size-negotiated extension slot.
  • JNI and Kotlin.
    • The JNI onShieldedSyncCompleted signature gains a trailing errorCode: Int. Custom NativeWalletEventBridge subclasses that override it must add the parameter and recompile. Precompiled overrides of the old signature no longer receive per-wallet results.
    • WalletSyncEvent.ShieldedResult adds a defaulted constructor parameter. Callers must recompile against its updated JVM constructor and generated copy signatures. Exhaustive when expressions over DashSdkError.PlatformWallet must handle the new subtype.
  • Swift. Exhaustive switches over PlatformWalletResultCode or PlatformWalletError must handle the new case.

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

https://claude.ai/code/session_01WunYYjpfLux1ByK7fGF7SG

🤖 Co-authored by Claudius the Magnificent AI Agent

PR Hygiene · f3b517b

  • Bots — thepastaclaw ✓
  • Self-review — not asked of a bot author
  • Build green
  • Approvals
    • kotlin-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.kt and 9 more) — 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/event_handler.rs and 4 more) — HashEngineering or ZocoLini or llbartekll or romchornyi
    • rs-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.rs and 13 more) — HashEngineering or ZocoLini or llbartekll or romchornyi
    • swift-sdk (packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift, packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerAddressSync.swift, packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift and 3 more) — llbartekll or romchornyi

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.

Summary by CodeRabbit

  • New Features
    • Added an operation to rebuild an inconsistent shielded commitment tree while retaining wallet notes and spend status.
    • Shielded sync results now include typed errors, including a specific error for tree inconsistencies.
    • Shielded sync detects tree inconsistencies and reports them without automatically rebuilding the tree.
  • Bug Fixes
    • Rebuilds coordinate with active shielded operations and restart background sync when appropriate.
    • Failures during rebuild and sync are reported with specific error details.
    • Restored wallet data better preserves recorded spend status and scan progress.

lklimek and others added 4 commits October 23, 2026 20:20
…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 <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 <noreply@openai.com>

Co-Authored-By: Codex <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 <noreply@openai.com>

Co-Authored-By: Codex <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019H9THphMnuQyh9oPY13SoE
@coderabbitai

coderabbitai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

Run configuration

Commits

Reviewing files that changed from the base of the PR and between f3b517b and f3b517b.

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
Walkthrough

This change adds shielded commitment-tree consistency checks and a tree rebuild operation. It adds typed per-wallet sync errors and updates the FFI callback contract. Kotlin and Swift SDKs expose typed errors and rebuild methods.

Changes: Shielded tree consistency and rebuild

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
Loading

Possibly related issues

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: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: detection of inconsistent shielded commitment trees (ShieldedTreeInconsistent, error code 67) and a new explicit rebuild operation (rebuildShieldedTree / shielded_rebu…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
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.

Share

@thepastaclaw

thepastaclaw commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Final review complete — no blockers (commit f3b517b)

@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

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: critical by gpt-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); 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 (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; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — security-auditor (completed, effort xhigh); agent phase2-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.

lklimek and others added 10 commits October 28, 2026 15:23
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tree-consistency

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…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 <noreply@anthropic.com>
…t shielded tree

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ync test guards

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…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 <noreply@anthropic.com>
…tree-consistency

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tch concurrency

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… 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 <noreply@anthropic.com>
…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 <noreply@anthropic.com>

@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

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: critical by gpt-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); 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 (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; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — security-auditor (completed, effort xhigh); agent phase2-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 <noreply@anthropic.com>

@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

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: critical by gpt-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); 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 (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; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — ffi-engineer (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — security-auditor (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — general (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — ffi-engineer (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — security-auditor (completed, effort xhigh); agent phase2-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.

lklimek and others added 3 commits October 29, 2026 09:32
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WunYYjpfLux1ByK7fGF7SG
@Claudius-Maginificent

Copy link
Copy Markdown
Collaborator Author

On the Kotlin MutableSharedFlow note from the review summary: this pattern predates the PR. Kotlin has no generation counter for clearShieldedStorage either, and the line is outside this diff. The worst case here is one redundant repair prompt from a buffered ShieldedTreeInconsistent. Follow-up: port Swift's generation counter to Kotlin, covering Clear and rebuild together.

🤖 Co-authored by Claudius the Magnificent AI Agent

@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

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: normal by gpt-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); 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 (antigravity quota lookup failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.1-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 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.

lklimek and others added 2 commits October 30, 2026 12:33
"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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WunYYjpfLux1ByK7fGF7SG
Base automatically changed from fix/shielded-sync-concurrent-append to v5.1-dev October 30, 2026 14:37
@github-actions github-actions Bot added this to the v5.1.0 milestone Oct 30, 2026
@github-actions github-actions Bot added the waiting-self-review Waiting for the author to post /self-reviewed label Oct 30, 2026
@github-actions

github-actions Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Ready for review — kotlin-sdk: HashEngineering · rs-platform-wallet-ffi: HashEngineering or ZocoLini or llbartekll or romchornyi · rs-platform-wallet: HashEngineering or ZocoLini or llbartekll or romchornyi · swift-sdk: llbartekll or romchornyi.
Full checklist in the description.

@github-actions github-actions Bot added ready-for-human Bots have reported, the author has self-reviewed, and the build is green: this needs a human. and removed waiting-self-review Waiting for the author to post /self-reviewed labels Dec 3, 2026
@lklimek
lklimek changed the base branch from v5.2-dev to v5.1-dev December 3, 2026 09:15
@lklimek
lklimek added this pull request to stack #6483 December 3, 2026 09:15
@lklimek

lklimek commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

Per maintainer decision, addressed in the follow-up PR #6481.

🤖 Co-authored by Claudius the Magnificent AI Agent

@github-actions github-actions Bot modified the milestones: v5.2.0, v5.1.0 Dec 3, 2026
@lklimek
lklimek removed this pull request from stack #6483 December 3, 2026 09:41
@lklimek
lklimek changed the base branch from v5.1-dev to v5.2-dev December 3, 2026 09:41
@github-actions github-actions Bot modified the milestones: v5.1.0, v5.2.0 Dec 3, 2026

@romchornyi romchornyi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 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 host start or 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
  1. 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, and tree_scan_reset is never cleared. A kill or persister failure in between leaves coverage above the host cursor, so restore returns None and the next pass starts from 0. Keeping the previous coverage row, or writing coverage after the host persists, avoids it.
  2. ShieldedSyncRestartFailed reaches the host as code 6 — mod.rs#L1432 — the reset took effect but sync is stopped. A host that retries the rebuild gets Ok with was_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").
  3. 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 retryable ShieldedMerkleWitnessUnavailable (88). ShieldedStoreError is classed MaybeSent. (Not traced whether the send path rewraps it.)
  4. sync_wallet now returns the pass's raw error — shielded_sync.rs#L650 — before, a failed pass became ShieldedSyncFailed. Now map_shielded_error attaches the raw error's payment class (MaybeSent for a store error) to a call that moves no money, and the warn log is gone. try_sync also drops PassFailure.subwallets, so a wallet unregistered between the check and the snapshot can get another wallet's failure; sync() was fixed for exactly that.
  5. One unparsable host note row fails every bind — coordinator.rs#L1818 — when its nullifier is a recorded spend, restore_locked returns Err, and only Clear gets the wallet out. The store already holds that spend, so skipping the row loses nothing.
  6. _ => over PlatformWalletError — coordinator.rs#L2781 — fail_all_wallets types only ShieldedTreeInconsistent, while map_shielded_error also types the two recovery errors. One shared classifier with every variant named would keep the background and explicit paths from drifting.
  7. 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 (return Cancelled) matches the comment above it.
  8. 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.
  9. Conventions — a_dpns_era_event_extension_refuses_the_shielded_outcomes_slot and reset_commitment_tree_reports_a_busy_checkpoint_and_stays_applied lack the should prefix; handle.rs and coordinator.rs add inline crate:: 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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 calls startShieldedSync() → Success, nothing starts → the rebuild sees was_running == false and 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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed ready-for-human Bots have reported, the author has self-reviewed, and the build is green: this needs a human. labels Dec 3, 2026

This branch has not been deployed

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

Labels

waiting-self-review Waiting for the author to post /self-reviewed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants