Repository navigation
Conversation
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true
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. |
|
🕓 Review not started yet because this PR is a draft.
Commit ef29b2b. Normal review starts when eligible; priority review starts as soon as a slot is available. |
thepastaclaw
left a comment
There was a problem hiding this comment.
Final validation — Phase 1 + Phase 2
History replay is correctly centralized, and the normal FFI path test demonstrates that recorded confirmed spends guard redelivered funding outputs. However, the FFI also raw-inserts unresolved asset-lock records before shared replay, while the new held-txid skip suppresses replay of the same confirmed funding and spender rows; their spend guards therefore remain absent and a redelivered funding transaction can resurrect an already-spent output. This is a blocking correctness issue.
🔴 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: architecture-layering); reviewer 3: muse-spark-1.3-contributor (agent: phase1-reviewer, role: ffi-engineer); reviewer 4: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 5: muse-spark-1.3-contributor (agent: phase1-reviewer, role: security-auditor); reviewer 6: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 7: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 8: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 9: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 10: 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 cross-language persistence and wallet-replay change that directly alters funds movement and spent-output accounting in platform-wallet load paths, including FFI deserialization and storage restoration. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— architecture-layering (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— ffi-engineer (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— security-auditor (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity below 15% reserve: weekly 13% left, 5h 100% left),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 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/manager/history_replay.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_replay.rs:93-95: Do not skip history merely because a raw-restored transaction record exists
The `held` set only proves that an account contains a transaction-map entry; it does not prove that the checker restored the transaction's spend effects. The FFI load path raw-inserts unresolved asset-lock records, including confirmed spenders of asset-lock inputs, through `transactions_mut().insert(...)` before `recorded_history` is replayed. Swift supplies those same rows in both the unresolved-asset-lock array and the recorded-history array. Because their txids are already held, this branch skips them, and the raw synthetic records do not populate `spent_outpoints` or `observed_spent_outpoints`. A later redelivery of the funding transaction can therefore credit an output already consumed by the confirmed spender. The existing FFI regression does not include the raw unresolved-record array, so it does not exercise this overlap. Stage retention-only records after shared replay, avoid raw-inserting records that will be checker-replayed, or otherwise rebuild the spend guards independently; add a regression with a raw-restored confirmed spender and funding redelivery.
- [SUGGESTION] packages/rs-platform-wallet/src/manager/history_replay.rs:63-72: Build the held transaction set once instead of scanning all accounts per record
The `held` filter reconstructs `all_accounts()` and scans every account for every stored transaction. Since load replays the full persisted history on each startup, this adds repeated account-collection work proportional to history size. Build an owned txid set from all account transaction maps once before filtering; this also avoids retaining references into `wallet_info` across the subsequent mutable replay.
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:7140-7149: Prefetch transaction relationships during history restore
The new history fetch retrieves every `PersistentTransaction`, then evaluates `walletOwnsTransaction` for each restorable wallet. That predicate touches `involvedAccounts`, `outputs`, `inputs`, and `pendingInputs`, but this descriptor does not prefetch any of them. On a cold launch, relationship faults can therefore be triggered repeatedly while filtering the history for each wallet. Prefetch these relationships, or bucket ownership in one pass, to keep history restoration from scaling poorly as wallets and transaction history grow.
In `packages/rs-platform-wallet-ffi/src/persistence.rs`:
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/persistence.rs:5245-5257: Reject trailing bytes in recorded transaction rows
`consensus_decode(&mut &bytes[..])` accepts a valid transaction prefix without requiring the input cursor to be exhausted. Consequently, a row containing a valid transaction followed by arbitrary bytes passes the txid check and is replayed, despite the decoder's fail-closed contract and the surrounding use of full `deserialize` for other restore paths. Require complete cursor consumption before accepting the row; apply the same exact-consumption rule to the unconfirmed decoder for consistency.
Out-of-scope follow-up suggestions (1)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Define expiry for persisted unconfirmed spend reservations — The shared replay now also replays host-supplied FFI mempool rows, so a never-mined or invalid observed spender can reserve an outpoint across every restart until a conflicting confirmed or InstantSend transaction is observed. This is an availability concern, but the same policy already exists on the SQLite path and is explicitly tracked by the moved expiry TODO rather than being introduced as an implementation mistake in this change.
- Follow-up: Track a separate policy change defining how persisted unconfirmed reservations are revalidated or expired, including safe release of dependent transactions.
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
The shared history replay fixes the confirmed-spend reconstruction gap and the four prior findings are resolved. Two replay-order defects remain: load-time chain-lock finalization can erase asset-lock conflict evidence before it is seeded, and final conflict reconciliation is skipped when the checker regenerates a conflicting raw record. Both can leave incorrect asset-lock wait behavior or wallet balance/spend state after restore.
🔴 2 blocking
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:
criticalbygpt-6.1-sol(effort low) — This is a large, intricate cross-language change that directly alters wallet transaction-history replay, spent-output reconstruction, and spend reservations in persistence and loading paths, affecting funds movement and coin-selection state across SQLite, FFI, Swift, and Rust. - 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 below 15% reserve: weekly 13% left, 5h 100% left),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— 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/manager/history_replay.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_replay.rs:168-170: Preserve asset-lock conflict evidence before load-time finalization
The replay finalizes the restored chain lock after rebuilding history, but `load_from_persistor` seeds `observed_input_conflicts` only afterward. With the default `keep-finalized-transactions = OFF`, `apply_chain_lock` evicts a confirmed spender record once its block is buried, leaving only its finalized txid. The subsequent seeder reads `transaction_history()` and the cache, so a restored confirmed spender that was needed to identify an `AssetLockInputContested` conflict disappears before it can be recorded. This regresses the bounded proof-wait behavior for a Built/Broadcast asset lock whose input was spent by a restored transaction. Capture conflict evidence before applying the restored chain lock, or seed the cache from the replayed records before finalization while retaining the finalization needed to rebuild spend guards.
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_replay.rs:162-166: Reconcile final conflicts after raw-history restoration
`sweep_conflicts` is invoked only when `restored_fallback` becomes true. If a final winner is replayed before a conflicting mempool loser, all raw records have already been detached, so the winner's initial sweep cannot see the loser. The checker can then regenerate the loser because its wallet-owned change output is attributable, causing metadata restoration to take the existing-record branch at lines 152–155 and leaving `restored_fallback` false. For an InstantSend winner, the checker also does not populate `observed_spent_outpoints`, so the loser can recreate change and reserve additional inputs. Because the persisted projection filter preserves that change when it was present in the restored UTXO set, both conflicting state and an inflated balance can survive load. Reconcile all final transactions after the complete replay and metadata-restoration pass, independently of whether fallback records were reinserted; add a regression with an attributable loser and an InstantSend winner replayed first.
Out-of-scope follow-up suggestions (2)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Revalidate indefinitely retained unconfirmed spend reservations — Stored incoming or outgoing mempool records are replayed across restarts without expiry or chain revalidation. A never-mined transaction can therefore keep a wallet outpoint reserved indefinitely. This behavior predates the shared replay and is explicitly tracked by
TODO(expire-unconfirmed-spend-reservations), so it should not be fixed in this PR.- Follow-up: Track a separate change for safe admission and reservation revalidation that does not release inputs belonging to genuinely broadcast transactions merely because peers become silent.
- Bound startup history replay without discarding spend guards — A peer can accumulate many wallet-relevant unconfirmed records, increasing retained history and startup replay work on every launch. The SQLite path already replayed complete history, and this PR moves that behavior into the shared implementation; truncating history here would reopen spent-output resurrection. This is explicitly tracked by
TODO(bound-load-history-replay)and is outside this fix.- Follow-up: Design a separate bounded-history mechanism backed by durable spend-guard or finality checkpoints, with adversarial history-size coverage.
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
Static verification confirms two prior blockers remain: block-confirmed conflicts can retain persisted losing change, and load-time finalization can erase asset-lock conflict evidence before recovery caches it. The new descendant cleanup also fails to remove already-reconstructed descendants and introduces avoidable quadratic startup work; four prior findings are fixed. No builds or tests were run; the supplied CI snapshot confirms Kotlin validation but contains no Rust or native Swift validation results.
🔴 3 blocking | 🟡 1 suggestion(s)
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: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 6: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.1-sol(effort low) — The intricate cross-persister replay in packages/rs-platform-wallet/src/manager/history_replay.rs::replay_recorded_history changes spend reservations, conflict resolution, and spendable UTXO reconstruction, directly affecting funds availability and coin selection after wallet reload. - 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 below 15% reserve: weekly 39% left, 5h 11% left),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— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— rust-quality (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/history_replay.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_replay.rs:157-163: Remove reconstructed descendants when their parent was already swept
drop_swept_descendants only extends the swept set, and this continue only skips restoration of the held original. Neither operation removes a live descendant already reconstructed by the checker. The permitted replay order loser → InstantSend winner → mempool child exposes this: the winner removes the parent while the child is detached, then a child with a wallet-owned output is reconstructed and its persisted output survives retention. The post-replay InstantSend sweep cannot discover that child because the conflicting parent record is already absent; the pinned conflict walker returns when it finds no direct loser. This helper identifies the child through held history, but skipping its original leaves the live record and selectable output intact. Remove reconstructed records and UTXOs for the swept descendant closure, with appropriate spend-mark cleanup, or prevent those descendants from being applied. The existing orphan regression uses an unattributable child and does not exercise this case.
- [SUGGESTION] packages/rs-platform-wallet/src/manager/history_replay.rs:202-226: Index held descendants instead of repeatedly scanning them
This closure repeatedly scans every followable held record until no new txid is added. Held records are collected in account/transaction-map order rather than dependency order, so a deep descendant chain can require one pass per generation, producing O(depth × held history) startup work. The pinned checker's conflict walker already avoids this scaling problem with a parent-to-children index. Build that index once and traverse newly swept txids with a worklist, preserving the existing confirmed/locked exclusions while making traversal linear in records and input edges.
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_replay.rs:175-179: Reconcile final conflicts after raw-history restoration
(existing thread: https://github.com/dashpay/platform/pull/5220#discussion_r4153965344)
The final reconciliation runs only when an unattributable held record was reinserted. A block-confirmed winner replays before its conflicting mempool loser while the held loser is detached, so the initial sweep cannot remove it. If the loser pays a wallet-owned address, the checker subsequently reconstructs its record. The pinned checker's observed-spend guard returns before modifying UTXOs, which prevents new credits but leaves the loser's already-restored change untouched. That change passes the projection retention filter, and restoring the held record takes the metadata-only branch, leaving restored_fallback false. The unconditional sweep at lines 122–123 covers only InstantSend winners, so neither the reconstructed loser nor its selectable change is removed. Reconcile block-confirmed winners after complete replay and raw restoration independently of fallback insertion, and cover an attributable loser whose change is present in the restored UTXO projection.
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_replay.rs:181-184: Preserve asset-lock conflict evidence before load-time finalization
(existing thread: https://github.com/dashpay/platform/pull/5220#discussion_r4153965337)
Replay applies the restored chain lock before load_from_persistor constructs PlatformWalletInfo and calls seed_observed_input_conflicts at load.rs:283. With keep-finalized-transactions disabled, as it is by default, the pinned key-wallet implementation promotes and evicts covered InBlock spender records, retaining only their txids. Swift explicitly supplies confirmed spenders of unresolved asset-lock inputs through its unresolved-record buffer, but restoring those records before this finalization does not preserve their input-to-spender association afterward. The seeder reads only surviving transaction_history(), and the new conflict cache starts empty, so a Built/Broadcast asset lock loses its conflict-capped proof wait and contested-input verdict. Already-chainlocked history can also be evicted during checker replay when no held fallback preserves it. Capture the relevant input, spender, and height observations before either eviction point and carry them into PlatformWalletInfo while retaining core finalization. Cover manager load with a competing confirmed spender and a higher persisted chain lock under the default retention configuration.
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
Static verification at f6f2004 confirms that all eight prior findings are addressed. Two in-scope blockers remain: unchecked monetary operands in shared replay and attacker-amplifiable whole-history conflict sweeps; rebroadcasting transactions already swept as losers is a lower-impact issue. No builds or tests were run in this lane; the supplied exact-head CI snapshot shows successful Kotlin checks but no dedicated Rust-wallet or native Swift validation.
🔴 2 blocking | 🟡 1 suggestion(s)
1 finding(s) not shown inline (the lines are not part of this PR's diff)
🟡 Suggestion: Do not rebroadcast unconfirmed sends that the history replay swept as losers
packages/rs-platform-wallet/src/manager/load.rs:373-387
Shared replay excludes defeated transactions from accounting, but pending_resends still receives the complete unconfirmed_outgoing_txs list because replay returns only a count. A send present in both lists can therefore be swept as a loser and then handed back to SPV's broadcast/retry machinery. Swift's outgoing selection reduces this overlap but does not eliminate it: a losing send with an additional wallet input can remain selected through that still-unspent input even after a winner takes the shared input. This retries a transaction the restored history has already classified as defeated and, for an attributable transaction, routes it through mempool processing again after its record was removed. Return or otherwise expose the swept txids and exclude them from pending_resends, while retaining rebroadcast for surviving overlapping sends.
source: muse-spark-1.3-contributor (phase1-reviewer: general)
Review provenance
Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 6: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 7: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 8: 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) — The intricate replay in packages/rs-platform-wallet/src/manager/history_replay.rs changes spent-output reconstruction, conflicting-spend resolution, and balance accounting during wallet load, directly affecting which funds remain available to spend. - 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 below 15% reserve: weekly 14% left, 5h 100% left),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— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— platform-versioning (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/history_replay.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_replay.rs:128-139: Validate replay amounts before invoking the wallet checker
Shared replay stages stored input values and invokes the checker without the operand validation already used by SQLite's restore_recorded_transactions. The FFI decoder checks complete encoding, txid and context, but those checks do not bound transaction amounts. In the exact pinned key-wallet dependency, ManagedCoreFundsAccount::record_transaction calculates `received as i64 - sent as i64`, and wallet_checker performs the equivalent subtraction for wallet totals. A stored transaction spending a restored 1-duff wallet coin and paying `1_u64 << 63` duffs to a wallet address therefore reaches `i64::MIN - 1`: overflow-checked builds panic during load, while unchecked builds produce wrapped accounting. Owned-output accumulation can overflow as well, and the projection filter runs only after this arithmetic. Add a checked preflight before mutating the restored state, covering individual values and aggregate checker operands from existing coins, replayed parent outputs, owned-input details and asset-lock credit outputs. Handle unsafe records through a controlled restore outcome; excluding an unsafe mempool record must preserve its input reservations rather than silently making those coins spendable. Add shared/FFI regressions corresponding to SQLite's operand-safety coverage.
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_replay.rs:273-278: Avoid whole-history sweeps for every contested historical spender
The planner's contested-input filter does not bound the total sweep work. The scratch account contains the complete stored history, and the pinned drop_conflicted_transactions scans that account's transaction map on every sweep_conflicts call, including calls that remove nothing. A wallet-paying mempool transaction listing inputs already spent by N distinct stored confirmed transactions puts all N confirmed transactions into the precomputed winners list. The first sweep removes the mempool competitor, but the other N−1 winners remain eligible and each scans the retained confirmed history, producing Ω(N²) planning work from an O(N)-sized conflicting record. This is reachable from an unauthenticated SPV peer: mempool handling routes transactions through wallet relevance checks, and a matching wallet output still produces a transaction record even when update_utxos rejects its outputs as doomed by an observed block spend. The FFI store retains rows removed only by shared replay, so the same startup amplification recurs on subsequent loads. Resolve conflicts with an input-to-spenders index and a shared descendant worklist, or invalidate candidates as their remaining competitors disappear while keeping work restricted to affected records. Preserve finality precedence and cross-account descendant removal.
In `packages/rs-platform-wallet/src/manager/load.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/manager/load.rs:373-387: Do not rebroadcast unconfirmed sends that the history replay swept as losers
Shared replay excludes defeated transactions from accounting, but pending_resends still receives the complete unconfirmed_outgoing_txs list because replay returns only a count. A send present in both lists can therefore be swept as a loser and then handed back to SPV's broadcast/retry machinery. Swift's outgoing selection reduces this overlap but does not eliminate it: a losing send with an additional wallet input can remain selected through that still-unspent input even after a winner takes the shared input. This retries a transaction the restored history has already classified as defeated and, for an attributable transaction, routes it through mempool processing again after its record was removed. Return or otherwise expose the swept txids and exclude them from pending_resends, while retaining rebroadcast for surviving overlapping sends.
Out-of-scope follow-up suggestions (2)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Preserve pre-finalization asset-lock conflict evidence on SQLite load — SQLite finalizes history inside its own load transaction and returns an empty recorded_history, so the manager's new pre-replay evidence capture cannot preserve SQLite's equivalent conflict evidence. This is an unchanged, explicitly acknowledged limitation tracked by #5379, not an unresolved instance of the shared-replay finding.
- Follow-up: Keep #5379 as the separate follow-up for capturing evidence before SQLite finalization and carrying it through the startup snapshot.
- Authenticate or explicitly manage peer-originated spend reservations — The underlying unauthenticated mempool reservation policy predates this PR and is explicitly acknowledged by TODO(expire-unconfirmed-spend-reservations). A broader authentication, expiry or user-recovery policy is outside this change; the newly introduced startup-work amplification is retained separately as an in-scope finding.
- Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
The shared replay addresses eight of the eleven prior findings, including raw-record detachment, descendant exclusion, finality reconciliation, and complete-buffer decoding. Two blockers remain: cross-account duplication can bypass the amount preflight and overflow the checker, and independent competitors still cause quadratic conflict planning; swept-send rebroadcast and duplicate competitor counting also remain actionable. Validation was static only; the supplied head-matched CI snapshot had Rust workspace tests and several builds pending, wallet-specific tests skipped, and no native Swift build evidence.
🔴 2 blocking | 🟡 2 suggestion(s)
1 finding(s) not shown inline (the lines are not part of this PR's diff)
🟡 Suggestion: Do not rebroadcast unconfirmed sends that the history replay swept as losers
packages/rs-platform-wallet/src/manager/load.rs:381-386
History replay excludes defeated transactions and their descendants, but returns only a count, while this queue receives the original unconfirmed_outgoing_txs unchanged. The history_txids filter prevents duplicate accounting but does not distinguish surviving sends from swept ones. This is reachable through Swift's TXO-based selection: an unconfirmed loser spending A+B can remain selected through the unspent B row when a stored confirmed winner spends only A. Replay correctly removes the loser, yet resend_one checks only wallet-generation liveness before broadcasting it. The known loser is consequently handed back to SPV's rebroadcast timer on subsequent loads. Re-sending identical bytes does not authorize a new spend, but retrying transactions already defeated by restored finality is unnecessary and inconsistent with replay's settlement decision. Return swept txids from replay and filter the resend list, preserving eligible overlapping survivors; cover both the defeated parent and its descendants.
source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality); gpt-6.1-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality)
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: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: platform-versioning); 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: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.1-sol(effort low) — The intricate replay_recorded_history implementation in packages/rs-platform-wallet/src/manager/history_replay.rs directly changes spend reservations, conflicting-transaction handling, and spendable UTXO reconstruction, affecting funds availability and coin selection. - 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 below 15% reserve: weekly 14% left, 5h 100% left),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— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— platform-versioning (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/load.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/manager/load.rs:381-386: Do not rebroadcast unconfirmed sends that the history replay swept as losers
History replay excludes defeated transactions and their descendants, but returns only a count, while this queue receives the original `unconfirmed_outgoing_txs` unchanged. The `history_txids` filter prevents duplicate accounting but does not distinguish surviving sends from swept ones. This is reachable through Swift's TXO-based selection: an unconfirmed loser spending A+B can remain selected through the unspent B row when a stored confirmed winner spends only A. Replay correctly removes the loser, yet `resend_one` checks only wallet-generation liveness before broadcasting it. The known loser is consequently handed back to SPV's rebroadcast timer on subsequent loads. Re-sending identical bytes does not authorize a new spend, but retrying transactions already defeated by restored finality is unnecessary and inconsistent with replay's settlement decision. Return swept txids from replay and filter the resend list, preserving eligible overlapping survivors; cover both the defeated parent and its descendants.
In `packages/rs-platform-wallet/src/manager/history_replay.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/manager/history_replay.rs:467-475: Deduplicate transaction identities when counting live competitors
`unconfirmed_spends` counts account records rather than distinct spending transactions. The checker records a pooled or multi-account transaction in each affected account, but `is_contested` subtracts only one occurrence for the candidate itself. An InstantSend transaction represented in two accounts is therefore considered contested even when no other transaction spends its inputs. After replay, N independent multi-account InstantSend transactions trigger N additional whole-history sweeps that remove nothing, introducing quadratic work on legitimate restored history. Count each txid's inputs once before applying `is_contested`, and add a regression with a surviving InstantSend transaction represented in multiple accounts and no competing spender.
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_replay.rs:325-333: Validate replay amounts before invoking the wallet checker
(existing thread: https://github.com/dashpay/platform/pull/5220#discussion_r4246956206)
The preflight bounds unique outpoints, but the checker aggregates account matches, and replay can temporarily duplicate an outpoint across accounts. Restore a coin worth `1_u64 << 62` in account A whose output script belongs to account B, and supply its funding transaction plus a child spending it to a 1-duff wallet output. Every individual value and preflight sum fits `i64`. Funding replay creates the coin in B without removing A's fallback; the child therefore matches the input in both accounts. In the pinned key-wallet revision, `ManagedAccountCollection::check_transaction` adds both matches into `total_sent`, yielding `1_u64 << 63`, and the wallet checker evaluates `1 - i64::MIN`. This panics with overflow checks or wraps without them. The `misplaced` cleanup occurs only after all checker calls. Normalize fallback duplicates before they can be spent during replay, or make the preflight bound actual cross-account checker operands. Add a two-account misplaced-projection regression.
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_replay.rs:426-432: Avoid whole-history sweeps for every contested historical spender
(existing thread: https://github.com/dashpay/platform/pull/5220#discussion_r4246956215)
Removing confirmed records from the scratch map and updating competitor counts fixes the single competitor naming many historical inputs, but independent competitors still cause quadratic planning. With N confirmed winners, N separate unconfirmed competitors, and N unrelated unconfirmed bystanders, each winner remains contested until its own sweep. The pinned `drop_conflicted_transactions` scans the retained transaction map for direct losers and rebuilds its descendant index on every successful sweep, so the bystanders alone contribute N full scans. The second half of `should_plan_sweeps_only_while_a_competitor_remains` constructs this shape and permits 200 sweeps without bounding record visits. This is attacker-reachable: SPV's peer transaction handler forwards transactions to wallet relevance checking without validating their signatures or input spendability, and a matching wallet output produces a persisted record even when observed-spend guards prevent crediting it. The FFI store retains the losing rows, so the startup cost repeats across launches. Reuse an input-to-spenders index and a shared descendant worklist, or restrict each sweep to affected records while preserving finality precedence and cross-account descendants. Test total record visits for independent competitors and bystanders, not only sweep count.
Out-of-scope follow-up suggestions (2)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Consolidate backend-neutral replay while preserving transactional storage repair — Outside this PR's scope: SQLite's in-transaction replay is unchanged from the base, and the PR explicitly retains that implementation and defers consolidation. The confirmed-conflict evidence limitation is separately tracked in #5379; a broader persistence redesign is not an additional finding against this change.
- Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.
- Complete history restoration inputs on the remaining mobile paths — Outside this PR's scope: the PR explicitly documents Kotlin's null/zero history fields and the FFI decoder's empty owned-input details as deferred limitations. These are known follow-up areas, not newly undisclosed defects warranting expansion of this review.
- Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.
|
Answering the review of 2a4368f (two carried blockers and the suggestion that had no inline thread). Validate replay amounts before invoking the wallet checker — Confirmed, and wider than the overflow: with an ordinary 100,000-duff coin the fallback account recorded a spend of a coin it never owned. Fixed in 28254bc. Avoid whole-history sweeps for every contested historical spender — Confirmed: 200 confirmed spenders, each with its own unconfirmed competitor, next to 200 unrelated unconfirmed records, made planning examine 60,100 records. Fixed in 2c7d590. Planning indexes the unconfirmed records once, by spent outpoint and by parent transaction, and each settled record's sweep runs in a scratch account holding only the records still spending one of its inputs and their unconfirmed descendants ( Do not rebroadcast unconfirmed sends that the history replay swept as losers — Confirmed on the Rust side and fixed in 24f56c6. 🤖 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
At head 24f56c6, all twelve prior findings are fixed, but overlapping unsafe-record reservations become permanent guards that normal conflict removal cannot release. Fallback reconciliation also loses persisted coin-lock flags, and a randomized replay-order fixture can fail before exercising replay. Verification was static only: the supplied CI snapshot still had Rust workspace tests and Drive/JS builds pending, and native Swift validation was not demonstrated.
🔴 1 blocking | 🟡 2 suggestion(s)
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: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 6: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 7: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 8: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); reviewer 9: gpt-6-astra (agent: phase2-reviewer, role: general); reviewer 10: gpt-6-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 11: gpt-6-astra (agent: phase2-reviewer, role: ffi-engineer); reviewer 12: gpt-6-astra (agent: phase2-reviewer, role: platform-versioning); reviewer 13: gpt-6-astra (agent: phase2-reviewer, role: rust-quality); reviewer 14: gpt-6-astra (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) — The intricate new replay_recorded_history implementation in packages/rs-platform-wallet/src/manager/history_replay.rs reconstructs spend reservations, removes conflicting transactions and UTXOs, and filters rebroadcasts, directly changing which coins remain spendable. - 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 below 15% reserve: weekly 14% left, 5h 100% left),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— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— platform-versioning (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-astra— general (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— platform-versioning (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— rust-quality (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— security-auditor (completed, effort xhigh); agentphase2-reviewer - Model comparison: every Phase-2 reviewer also ran on
gpt-6-astra; the verifier weighed both sets without knowing which model wrote which
🤖 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/history_replay.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_replay.rs:203-206: Keep overlapping unsafe-record reservations releasable
Two set-aside records spending the same restored outpoint add different claimants to `reserved`. When this list reaches `restore_spent_outpoints` at line 324, the exact pinned key-wallet implementation merges those claimants into `None`, meaning a permanent guard; `release_spent_claims` removes only claims naming a removed txid. For example, unsafe records A spending X/Y and B spending X/Z reserve X permanently. A confirmed winner spending Y/Z can sweep both records without spending X, but X remains unavailable and funding redelivery cannot credit it. Abandoning both records has the same problem. This newly introduced reservation path therefore keeps real funds inaccessible even after every pending claimant is conclusively removed. Track all pending claimant identities and release the guard once none remain, without releasing it while another claimant survives. Add coverage for overlapping unsafe records and a winner that removes both without consuming their shared coin.
- [SUGGESTION] packages/rs-platform-wallet/src/manager/history_replay.rs:603-606: Preserve restored coin locks when removing fallback copies
The destination coin does not inherit the fallback coin's persisted flags before the original is deleted. In the exact pinned key-wallet implementation, `update_utxos` constructs a fresh UTXO and preserves `is_locked`, `is_instantlocked`, and `is_trusted` only from an existing entry in that same account. Restore an unspent locked coin into account 0 whose address derives from account 1, then replay its funding transaction: account 1 receives an unlocked copy, this helper deletes the locked original, and retention keeps the unlocked copy. `Utxo::is_spendable` consequently permits a coin that persistence explicitly prohibited spending. Persisted InstantSend status is also lost when funding replays as mempool, which is relevant to the FFI path that supplies no lock bytes. Transfer the original reservation and applicable monotonic flags to the deriving account before deleting the fallback copy. Extend the fallback regression with an unspent locked output; its current child spend removes the coin and masks this loss.
- [SUGGESTION] packages/rs-platform-wallet/src/manager/history_replay.rs:1249-1257: Make the bounded replay-order fixture deterministic
`wallet_with_receive_address()` calls `Wallet::new_random`, so the funding, loser, winner, and child txids change between runs. The Cartesian search visits 3,969 pairs but contains only 63 distinct winners. If the loser sorts below every winner, the `first` case has no match; if it sorts above every winner, the `between` and `last` cases have no match. The resulting `find(...).unwrap()` can panic before replay is exercised, causing intermittent CI failures unrelated to the behavior under test. Use a fixed wallet seed with verified matching candidates or explicit deterministic fixtures for all three orders.
Out-of-scope follow-up suggestions (3)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Enforce checked amount arithmetic in the live wallet checker — The pinned key-wallet checker still casts received/sent totals to signed integers and subtracts them without checked arithmetic. The shared replay preflight and retired-send filter protect load-time replay, but the unchanged live-ingestion delegate does not establish that protection for peer-delivered transactions. This is a concrete availability/accounting issue, explicitly acknowledged by the PR, rather than an unresolved defect in its new replay guard.
- Follow-up: Track a separate upstream key-wallet change that validates individual and aggregate accounting operands before mutation for every checker caller, then update the Platform dependency pin.
- Share backend-neutral replay policy with the SQLite path — Out of scope: sqlite/rehydrate.rs is unchanged from base d280e72. SQLite still replays inside its load transaction, and the added empty recorded_history prevents a second replay. The PR explicitly defers convergence of the two implementations; extracting their policy is broader redesign, not a defect caused by this change.
- Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.
- Converge SQLite and shared replay without moving database transaction ownership — Out of scope: this is the same explicitly deferred SQLite convergence work. The unchanged in-transaction replay does not justify expanding this PR to replace the backend's reconstruction implementation.
- Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
The shared replay and conflict-planning changes address the previously identified replay, accounting, retention, and performance defects. Two blocking correctness gaps remain: the SwiftData FFI restore path drops owned-input evidence needed to rebuild confirmed-spend guards, and the single-claim reservation can release a shared outpoint while another claimant remains when the omitted record is unsafe only because its persisted input metadata is corrupt.
🔴 2 blocking
1 carried-forward finding(s) already raised on this PR; not re-posting as new inline comments.
Review provenance
Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); reviewer 6: gpt-6-astra (agent: phase2-reviewer, role: general); reviewer 7: gpt-6-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 8: gpt-6-astra (agent: phase2-reviewer, role: ffi-engineer); reviewer 9: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 10: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 11: gpt-6-astra (agent: phase2-reviewer, role: rust-quality); 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 alters wallet fund attribution and spend reservations through history replay, conflict handling, persistence restoration, and FFI deserialization in files such asmanager/history_replay.rsandrs-platform-wallet-ffi/src/persistence.rs. - 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 below 15% reserve: weekly 14% left, 5h 100% left),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— 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-astra— general (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— rust-quality (completed, effort xhigh); agentphase2-reviewer - Model comparison: every Phase-2 reviewer also ran on
gpt-6-astra; the verifier weighed both sets without knowing which model wrote which
🤖 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-ffi/src/persistence.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/persistence.rs:5291-5297: Carry owned input details through the recorded-history FFI
The SwiftData restore buffer transports only the transaction body and display metadata, and this decoder therefore always constructs `StoredTransaction` with `owned_inputs: Vec::new()`. That breaks the documented height-only funding case: the funding transaction is absent or has no replayable body, the spent output is absent from the restored UTXO projection, and `stage_recorded_spent_inputs` cannot synthesize the input needed for the checker to rebuild its spent mark. After finality or sync pruning removes the temporary observed-spend evidence, a redelivered funding transaction can credit the already-spent output again. Swift's history fetch already prefetches `PersistentTransaction.inputs`, `outputs`, and `pendingInputs`, so the ownership data exists at the host boundary but is discarded before Rust replay. Extend `RecordedTransactionRestoreFFI` and the Swift marshaller to carry wallet-owned input index, value, and address details, decode them into `owned_inputs`, and add coverage for a missing funding body followed by finalization, pruning, and funding redelivery.
In `packages/rs-platform-wallet/src/manager/history_replay.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_replay.rs:336-358: Keep overlapping unsafe-record reservations releasable
(existing thread: https://github.com/dashpay/platform/pull/5220#discussion_r4249695152)
The one-claimant map fixes the previous permanent `None` reservation, but it still releases a shared outpoint when the selected smallest-txid claimant is swept even if another unsafe record continues to name that outpoint. The stated justification that an unsafe transaction cannot confirm applies to invalid transaction amounts, but `unsafe_replay_amounts` also rejects a record solely because persisted `owned_inputs` metadata is oversized or has an overflowing aggregate; the signed transaction body can still be valid in that case. Two valid transactions A and B can therefore share input X while both are set aside because their stored input metadata is corrupt. If A is selected as X's claimant and is later swept by a confirmed winner that does not spend X, X's guard is released while B remains recorded. Funding redelivery can then re-credit X even though B may still be delivered or confirmed. Preserve the reservation while any claimant remains, or distinguish corrupted persistence metadata from transactions that cannot validly confirm and reject or sanitize the former.
|
Answering the carried finding of the review of f96d256. Keep overlapping unsafe-record reservations releasable — You are right, and the earlier justification was too broad: "an unsafe record can never confirm" holds only for a record unsafe by its own outputs. Fixed in 654044b. Remaining cost, listed under known limitations: a pair unsafe by stored amounts only holds its shared coin until the next load, even once both are swept, because the pinned key-wallet keeps one claimant per coin and a claim does not pass to another transaction (dashpay/rust-dashcore#1114). 🤖 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
Static review of the exact head found three in-scope blocking issues and one performance suggestion. The shared replay still fails to preserve spend guards for FFI-restored InstantSend records with missing funding, can permanently reserve coins when multiple potentially valid unsafe records share an input, and does not retire newly added claims after a block reorg. CI checks were still queued or pending in the supplied snapshot, and no builds or tests were run.
🔴 3 blocking | 🟡 1 suggestion(s)
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: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 5: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); 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:
criticalbygpt-6.1-sol(effort low) — This is a large, intricate change to wallet history replay, persistence restoration, conflict handling, and spent-output reconstruction, directly affecting funds movement and coin accounting in both SQLite and Swift/FFI persistence paths. - 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 below 15% reserve: weekly 14% left, 5h 100% left),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— 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/manager/history_replay.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_replay.rs:699-712: Retire restored block-spend claims when their block is reorged out
`settled_spend_claims` creates durable claims for every restored context other than `Mempool`, including ordinary `InBlock` spends at lines 703-710. Ordinary block inclusion is reversible. `PlatformWalletInfo::truncate_above` delegates directly to the pinned key-wallet implementation, and this layer performs no corresponding cleanup of these claims. A spend restored at height 101 can therefore be removed by a reorg to height 100 while its `(funding_outpoint, Some(spender_txid))` claim survives; when the now-unspent funding transaction is delivered again, the wallet still rejects the output and leaves real funds unavailable. Make these claims participate in reorg retirement, or create them only for evidence whose lifecycle is genuinely irreversible, and add coverage for restore, truncate, and funding redelivery.
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_replay.rs:367-387: Keep overlapping unsafe-record reservations releasable
(existing thread: https://github.com/dashpay/platform/pull/5220#discussion_r4249695152)
The reason-aware claimant selection still produces an unreleasable reservation when two `UnsafeAmounts::Stored` records share an input: `reservation_claimant` returns `None` at lines 384-385. In the pinned key-wallet API, a `None` claim is permanent because release only removes claims associated with a transaction id. If both records are later swept or abandoned without either spending the shared coin, the coin remains unavailable and funding redelivery cannot restore it during the session. `Stored` is not limited to impossible transactions; it also covers oversized restored coins or recorded input values, so this is a real availability failure rather than only test corruption. Track all claimants through sweep and abandon, or provide an explicit controlled recovery path that releases the reservation only after the final claimant disappears.
In `packages/rs-platform-wallet/src/wallet/asset_lock/sync/recovery.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/asset_lock/sync/recovery.rs:524-547: Index pending asset-lock owners before scanning stored confirmations
The conflict seeding loop scans every pending lock for every stored transaction input that appears in `watched`. With N pending locks on distinct inputs and N stored confirmations of those inputs, each self-confirmation scans the other N-1 locks before finding no conflict, producing quadratic startup work. The inner loop also recomputes each pending transaction's txid and scans its inputs repeatedly. Compute each pending transaction id once and build an outpoint-to-pending-lock index, then exclude only the stored transaction's own lock while checking for another owner.
In `packages/rs-platform-wallet-ffi/src/persistence.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/persistence.rs:5256-5299: Carry owned input details through the recorded-history FFI
(existing thread: https://github.com/dashpay/platform/pull/5220#discussion_r4250313496)
The new settled-spend fallback does not close this case on the actual FFI path. The decoder maps both raw mempool and raw InstantSend contexts to `TransactionContext::Mempool` at lines 5256-5258, while `settled_spend_claims` only claims inputs for non-mempool records. Because the FFI still constructs every record with `owned_inputs: Vec::new()`, an InstantSend spend whose funding body is unavailable and that has no wallet-owned output neither stages its input nor creates a durable claim. After the observed spend is pruned, redelivery of the genuine funding transaction can re-credit the already-consumed output. Carry per-input ownership through the FFI, or preserve corroborated InstantSend settlement evidence so this guard also applies to those records.
Out-of-scope follow-up suggestions (2)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Validate peer-supplied amounts on live wallet ingress — The live mempool/checker path still accepts peer-supplied transaction amounts before the new load-time preflight and can reach unchecked signed arithmetic. This predates the replay change and is explicitly documented by the PR as a remaining limitation, so it should not block this PR.
- Follow-up: Track a separate key-wallet change covering checked amount accumulation and controlled rejection before all live checker calls.
- Move cross-account descendant cleanup into key-wallet — The pinned key-wallet live sweep remains account-local for some descendant cleanup, while this PR works around that limitation only during shared history replay with a scratch account. The live-path limitation is upstream and pre-existing rather than introduced by this PR.
- Follow-up: Land wallet-wide descendant closure and cleanup in rust-dashcore, then update the dependency and add an ordinary-ingestion regression.
|
Answering the two carried findings of the review of 654044b. Carry owned input details through the recorded-history FFI — False for the shipped host, by reading the Swift store (read, not run). The decoder does map raw InstantSend to Keep overlapping unsafe-record reservations releasable — No change in this push. The reviews of 24f56c6 and f96d256 asked that the shared coin never be released while a claimant that may confirm remains; this review asks that it be released once the last claimant is gone. Both cannot be met at the pinned key-wallet. It keeps one claimant per coin, never releases a 🤖 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
Static verification at head 35951bf confirms fixes for 16 prior findings, but two in-scope blockers remain: incomplete FFI spend evidence can allow consumed outputs to be credited again, and overlapping unsafe-record reservations can remain permanently guarded after all claimants are removed. No builds or tests were run; the supplied head-specific CI snapshot has no completed Rust validation and still shows Kotlin validation queued and policy checks pending or running.
🔴 2 blocking
2 carried-forward finding(s) already raised on this PR; not re-posting as new inline comments.
Review provenance
Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 5: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 6: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); reviewer 7: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); 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 platform-wallet transaction replay, persistence, conflict resolution, and spend reconstruction that directly affects funds movement and coin ownership across storage and FFI boundaries, particularly in history_replay.rs and load_from_persistor. - 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 below 15% reserve: weekly 14% left, 5h 100% left),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— 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-ffi/src/persistence.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/persistence.rs:5291-5299: Carry owned input details through the recorded-history FFI
(existing thread: https://github.com/dashpay/platform/pull/5220#discussion_r4250313496)
The restored-coin regression covers ordinary unconfirmed sends, but the shipped Swift host does not always restore their input coins. `persistAssetLocks` marks linked input TXOs spent at status >= InstantSendLocked, and `loadWalletList` independently excludes inputs whose spender belongs to `finalizedAssetLockFundingTxids`, even when its transaction row still says mempool or InstantSend. With no replayable funding body, this decoder supplies neither owned inputs nor lock evidence: contexts 0/1 become Mempool, staging reconstructs nothing, and `irreversible_spend_claims` creates no guard. Restoring the asset-lock proof into `unused_asset_locks` does not establish a core-wallet spent mark. Funding redelivery can therefore credit a genuinely consumed coin.
There is also a confirmed-spend variant that does not depend on InstantSend restoration: Swift excludes the input of an InBlock spender above the restored chain lock. Without input ownership or a wallet-owned output, replay establishes only an observed-spend guard. A later chain lock and sync checkpoint prune that guard without creating a replacement. `should_guard_unreplayed_funding_against_irreversible_spends_only` explicitly expects the consumed coin to be credited after that sequence. Thus the ownership omission remains necessary for the PR's spend-safety goal, not merely transaction attribution. Carry wallet-owned input index, value, and address through the ABI, or restore equivalent reorg-aware evidence that survives subsequent finalization. Cover both finalized asset-lock inputs excluded from the projection and an ordinary restored block spend that becomes final during the session; do not restore unconditional ordinary-block claims, which would reopen the fixed reorg defect.
In `packages/rs-platform-wallet/src/manager/history_replay.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_replay.rs:381-386: Keep overlapping unsafe-record reservations releasable
(existing thread: https://github.com/dashpay/platform/pull/5220#discussion_r4249695152)
Returning None for two Stored-unsafe claimants creates a guard that cannot be released after both records are swept or abandoned. At the exact pinned rust-dashcore revision, `restore_spent_outpoints` treats None as permanent and `release_spent_claims` removes only claims naming a removed txid. The existing shared-coin regression explicitly preserves the guard after removing both claimants.
This trigger is not restricted to corrupt database values. `unsafe_replay_amounts` imports amounts from other recorded transactions' outputs and classifies a spend as Stored when its aggregate inputs exceed i64::MAX. An SPV peer can supply two wallet-paying fake funding transactions, each with one `1_u64 << 62` output, followed by two forged spends A/B that consume those outputs and a genuine wallet coin X. Give A an additional attacker-controlled input Y, B an input Z, and both small wallet-owned outputs. Each parent passes the per-record output check, while A/B fail the aggregate input check and receive Stored classifications. The pinned mempool manager and wallet-manager path perform relevance checking and emit transaction records without an amount-validity preflight. Choosing the small received amount below X also avoids the existing signed-subtraction panic, so this shape can reach persistence without changing stored values externally.
After restart, X receives the permanent None claim. A valid wallet-paying transaction spending Y/Z can then sweep both forged records without consuming X, but the guard remains and genuine funding redelivery cannot recover X during the session. Track the surviving claimant set, or provide an equivalent lifecycle mechanism that releases the reservation after the last claimant disappears while retaining it whenever another claimant survives. Upstream multi-claim support is an appropriate implementation location, but the current permanent reservation is a network-reachable availability defect introduced by this replay path.
Out-of-scope follow-up suggestions (3)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Validate live peer transaction amounts before wallet accounting — The pinned live SPV mempool path reaches wallet accounting without the operand validation added to shared replay. ManagedCoreFundsAccount and the wallet checker still perform unsigned accumulation and signed-cast subtraction on peer-supplied values. This independently permits malformed accounting or overflow failures and predates this PR; it is separate from the new reservation-release defect.
- Follow-up: Track a separate rust-dashcore change that validates transaction accounting operands before live wallet mutation and applies the same checked contract to native and FFI callers.
- Unify replay semantics without moving SQLite transaction ownership — Out of scope: sqlite/rehydrate.rs is unchanged relative to the supplied base, and the PR explicitly retains SQLite's transactional replay. Consolidating the engines is adjacent architecture work rather than a defect introduced by this range.
- Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.
- Add recorded-history restore to the Android JNI host — Out of scope: the JNI host deliberately supplies null/zero history fields and does not attest CORE_HISTORY_RESTORE. Android history implementation is explicitly excluded and tracked by TODO(android-core-history-restore), rather than falsely advertised as implemented.
- Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.
|
Answering the two carried findings of the review of 35951bf. Carry owned input details through the recorded-history FFI — First a correction. "False for the shipped host" was wrong for asset-lock funding spends. It holds for ordinary unconfirmed spends, whose coins the Swift store keeps unspent. For asset locks the earlier reading missed that Fixed for that case in c95c984 without an ABI change. The load already receives every tracked asset lock with its funding transaction and status, so after the replay it restores a spend claim for each input of a lock at The confirmed-spend variant is the residue stated in 2aa1497, and it stays open in this push. A spend in a block above the restored chain lock that pays nothing to the wallet has only the observed spend, and nothing replaces it once the block becomes final in the session. By reading, block sync does not deliver the funding again below the wallet's synced height ( Keep overlapping unsafe-record reservations releasable — Confirmed: the trigger is not limited to a corrupt store, and the earlier reply that said so was wrong. Fixed in 96fb93c by classification rather than by tracking claimants. An outpoint commits to its transaction, so an amount read from a recorded body is certain, and consensus rejects a transaction whose total input value is out of range ( What remains unreleasable is two records whose overflow depends on a restored coin value or a recorded owned-input value, with bodies that prove nothing. That needs stored values no transaction body backs. Releasing it needs claims that hold several claimants in key-wallet. 🤖 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 shared replay fixes sixteen prior findings, but the FFI path still loses spend protection for an ordinary confirmed spend that becomes final after loading. Conflict planning also ignores genuine InstantSend proofs already restored with tracked asset locks, allowing stale competing state to survive or locked history to be incorrectly retired. This was a static review of c95c984; the supplied CI snapshot has Rust workspace tests and one browser shard pending, the wallet-specific job skipped, and no native Swift build/test evidence.
🔴 2 blocking
1 carried-forward finding(s) already raised on this PR; not re-posting as new inline comments.
Review provenance
Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 6: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 7: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 8: 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) — The intricate replay_recorded_history implementation in packages/rs-platform-wallet/src/manager/history_replay.rs changes spend reservations, conflict resolution and restored UTXO eligibility, directly affecting coin selection and preventing already-spent funds from becoming spendable again. - 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 below 15% reserve: weekly 14% left, 5h 100% left),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— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— platform-versioning (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/load.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/load.rs:173-176: Settle tracked asset-lock proofs before planning history conflicts
The replay receives only recorded_history, although unused_asset_locks already contains restored finality evidence. On the FFI path, recorded InstantSend contexts are decoded as Mempool and history.instant_locks is empty, but build_unused_asset_locks separately decodes the tracked row's AssetLockProof::Instant, which contains the genuine InstantLock and funding transaction. That proof never reaches conflict planning. With a tracked locked funding transaction and a competing mempool record, neither becomes a settled winner, so the competitor and its persisted change can survive load. A plain-block competitor can instead retire the locked funding because the planner sees it as mempool, contrary to the pinned key-wallet precedence that only a ChainLock may overrule an InstantSend lock. The later final_lock_input_claims call protects inputs but does not remove competing change or restore settlement context. Before replay, populate RecordedHistory::instant_locks from matching tracked Instant proofs, validating the proof, funding, and history transaction identities, and let the existing replay upgrade and upstream sweep handle settlement. Add a restore regression with a genuine tracked Instant proof, stale mempool history context, and a competing record with persisted change. This proof-backed case does not require extending the ordinary history ABI: its lock bytes already cross the boundary.
In `packages/rs-platform-wallet-ffi/src/persistence.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/persistence.rs:5291-5299: Carry owned input details through the recorded-history FFI
(existing thread: https://github.com/dashpay/platform/pull/5220#discussion_r4250313496)
Every decoded history row still receives empty owned_inputs. Swift excludes the inputs of ordinary in-block spends from its unspent projection, so a spend above the restored ChainLock, paying nothing back to the wallet and lacking a replayable funding body, has no coin to stage and produces no account-local spend mark. irreversible_spend_claims correctly excludes this reversible block, and final_lock_input_claims covers only asset locks. Once a later ChainLock and sync checkpoint prune observed_spent_outpoints, nothing guards the already-spent output. The exact pinned dash-spv handle_tx forwards a previously untracked loose transaction to process_mempool_transaction without a historical-height check; the missing funding body also means replay has created no finalized funding identity to suppress that delivery. Relaying the authentic old funding can therefore credit the spent coin again. The current should_guard_unreplayed_funding_against_irreversible_spends_only fixture explicitly expects this credit after pruning. Transport the host's wallet-owned input index, value, and address into StoredTransaction so stage_recorded_spent_inputs reconstructs the account spend lifecycle, or implement equivalent protection that survives finality while retiring correctly on reorg. Cover FFI restore, subsequent finality/checkpoint pruning, and loose funding redelivery.
Out-of-scope follow-up suggestions (3)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Validate amount operands on live SPV transaction arrivals — The new replay preflight does not protect live ingress. In the exact pinned dependency, dash-spv forwards peer transactions to wallet processing, while ManagedCoreFundsAccount::record_transaction and wallet_checker still subtract unsigned amounts cast to i64 without checking the operands. A wallet-relevant transaction spending a 1-duff coin and receiving 1 << 63 duffs can therefore panic with overflow checks or produce wrapped accounting. This path predates the PR and is not newly introduced by recorded-history restoration.
- Follow-up: Track a separate rust-dashcore fix that validates individual and accumulated accounting operands before live wallet mutation, with SPV-ingress coverage, then update the dependency pin.
- Expose repair results so SQLite can share the replay engine — Out of scope: sqlite/rehydrate.rs is unchanged from the PR base, and the PR explicitly retains SQLite's existing in-transaction replay and defers unification. Extending the replay outcome to support a common transactional repair engine is a broader redesign, not necessary to correct the newly introduced record-returning path.
- Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.
- Complete Android recorded-history restore separately — Out of scope: the JNI adapter explicitly initializes the new history fields to null/0 and does not attest CORE_HISTORY_RESTORE. This preserves the pre-existing Android behavior rather than introducing a restore regression; parity is an explicitly deferred feature.
- Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
Verified the combined reviewer claims against head 712ff9d and the exact pinned wallet dependency. Most prior findings are fixed, but three blocking restore defects remain: loss of a confirmed-spend guard after finality advances, destructive settlement against chain-proven funding, and recreation of claims for defeated tracked funding; the new proof-import helper also adds quadratic history lookup work. This was a static review: the supplied exact-head CI snapshot shows successful Kotlin checks but does not establish Rust-wallet or native Swift validation.
🔴 3 blocking | 🟡 1 suggestion(s)
1 carried-forward finding(s) already raised on this PR; not re-posting as new inline comments.
Review provenance
Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); reviewer 6: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 7: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); 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 platform-wallet persistence and replay logic that directly affects funds movement, spent-output tracking, coin ownership, and duplicate-credit prevention across storage and FFI boundaries, particularly in manager/history_replay.rs and manager/load.rs. - 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 below 15% reserve: weekly 14% left, 5h 100% left),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— 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/asset_lock/sync/recovery.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/asset_lock/sync/recovery.rs:541-544: Preserve chain-proven funding during history conflict planning
Skipping Chain proofs leaves destructive conflict planning unaware of finality already restored through the tracked asset-lock envelope. A ChainLocked tracked funding can still have a stale Mempool history row. With a competing plain-block record, plan_replay_sweeps consequently treats that funding as an unconfirmed loser, excludes it from replay and removes its persisted change. The Chain branch of should_settle_stored_conflicts_with_a_tracked_instant_lock explicitly expects (false, true): the tracked funding's change disappears while the competitor's change remains. The base load retained the persisted funding change, so this destructive loss is introduced by the new replay rather than merely inherited. final_lock_input_claims runs afterward but protects inputs only; it cannot recover the removed outputs. The proof's lack of a funding block hash prevents inventing BlockInfo, not preservation of its stronger settlement evidence. Reconcile matching tracked Chain finality before planning, using real host block context or an explicit finality representation. If the snapshot cannot resolve the contradiction, reject or defer destructive settlement rather than selecting the weaker record. Require preservation of the proven funding's change or a controlled restore failure in the regression.
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/asset_lock/sync/recovery.rs:548-551: Index history txids when importing tracked InstantSend locks
Each matching tracked Instant proof searches the complete history vector for its funding txid. With L tracked proofs and T history records, this adds O(L × T) identity comparisons on every load. The Swift restore includes retained consumed lock rows, so L is not bounded by the currently pending operations; retained proofs and history growing together produce quadratic work even without conflicts. Build the history txid membership set once, or move load_from_persistor's existing history_txids construction before this call and pass that index to the helper.
In `packages/rs-platform-wallet/src/manager/load.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/load.rs:256-259: Do not recreate spend claims for defeated tracked funding
This call restores claims from every final-status tracked lock after replay has already removed conflict losers. For example, tracked InstantSend funding spends two coins, while a stored ChainLocked winner spends only the first. The pinned conflict rules correctly let the ChainLock defeat the InstantSend funding, but final_lock_input_claims then recreates a claim naming that defeated funding for the second coin too. If the host withheld the second coin because of the tracked lock's status, a later funding observation cannot credit this genuinely unspent output. The losing funding has already been excluded from replay and raw-record restoration, so a later sweep cannot find its record and release the recreated claim. Live settlement already removes defeated tracked locks through remove_tracked_asset_locks_for_swept; load does not perform the equivalent reconciliation and discards the replay outcome after resend filtering. Preserve the identities actually defeated by settlement and exclude their tracked locks from claim restoration, distinguishing those identities from records merely omitted for unsafe stored amounts. Add a regression with a ChainLocked competitor and an additional input consumed only by the defeated tracked funding.
In `packages/rs-platform-wallet-ffi/src/persistence.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/persistence.rs:5291-5299: Carry owned input details through the recorded-history FFI
(existing thread: https://github.com/dashpay/platform/pull/5220#discussion_r4250313496)
The remaining ordinary confirmed-spend case still violates this PR's confirmed-history restoration goal. Swift excludes an in-block spend's input from its unspent projection, but this decoder supplies empty owned_inputs. If the funding body is unavailable and the spender pays nothing to the wallet, replay creates neither an account record nor a durable account spent mark. For a block above the restored ChainLock, irreversible_spend_claims correctly installs no unconditional claim because that block can reorg. However, the pinned wallet's apply_chain_lock only promotes existing account records, and its subsequent sync-checkpoint pruning deletes the observed-spend evidence without creating a replacement guard. The above-ChainLock branch of should_guard_unreplayed_funding_against_irreversible_spends_only explicitly expects the consumed output to be credited after this transition. Historical block filtering does not make that safe: the pinned SPV loose-transaction path independently invokes wallet processing. Carry wallet-owned input index, value and address through the ABI into owned_inputs, or retain reorg-aware provisional evidence and promote it at finality. Change the regression to require the consumed output to remain absent after finality, pruning and funding reobservation; restoring unconditional claims for reversible blocks would reopen the fixed reorg defect.
Out-of-scope follow-up suggestions (2)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Validate transaction amounts on ordinary SPV delivery — The exact pinned key-wallet still performs unchecked signed accounting subtraction in both record_transaction_with_observed_spends and wallet_checker. Ordinary SPV delivery reaches that checker without the new replay operand preflight. This is a concrete live-path reliability and security follow-up, but the dependency arithmetic and live ingress predate this PR, whose new validation protects stored-history replay.
- Follow-up: Track checked operand validation and controlled invalid-transaction handling in the canonical key-wallet checker so replay and live delivery share the same safety boundary.
- Complete Android recorded-history restore parity — Out of scope: JNI initializes the new fields to null/0, Android does not attest CORE_HISTORY_RESTORE, and the PR explicitly excludes Android history transport. This preserves the pre-existing Android behavior rather than introducing a restore or ABI defect.
- Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
The shared replay and restore adapters address nineteen of the twenty-two prior findings, but chain-final funding preservation and the FFI confirmed-spend finality transition still have blocking correctness gaps. Overlapping reservations dependent on corrupt stored amounts remain a narrower recovery suggestion. Verification was static only; the supplied exact-head CI snapshot shows Kotlin validation queued and contains no completed Rust or native Swift validation results.
🔴 2 blocking | 🟡 1 suggestion(s)
3 carried-forward finding(s) already raised on this PR; not re-posting as new inline comments.
Review provenance
Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 6: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); reviewer 7: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 8: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.1-sol(effort low) — The intricate shared replay in manager/history_replay.rs and its integration in manager/load.rs reconstruct spent-output claims and resolve conflicting transactions, directly changing which wallet funds remain available to spend. - 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 below 15% reserve: weekly 14% left, 5h 100% left),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— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— platform-versioning (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/asset_lock/sync/recovery.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/asset_lock/sync/recovery.rs:588-591: Preserve chain-proven funding during history conflict planning
(existing thread: https://github.com/dashpay/platform/pull/5220#discussion_r4252334942)
Withholding now protects the history-only case, but not every representation accepted by the shared restore API. If the chain-final funding also has a raw Mempool record in wallet_info, removing its history row removes it from replay_txids. The detachment pass in history_replay.rs:124–136 therefore leaves that raw copy attached. plan_replay_sweeps imports it into the unconfirmed pool at lines 539–545, where a weaker plain-block competitor can defeat it. The resulting swept identity removes the funding's persisted change at lines 224–227, and the competitor's checker call can sweep the attached raw record too. The public startup snapshot permits existing records, and this replay explicitly supports raw-record overlap; Swift's current restriction of its raw asset-lock buffer to unresolved locks does not establish a restriction for all record-returning persisters.
There is also an evidence-validation bypass here: locked.contains_key accepts a mismatched InstantLock entry as sufficient to avoid withholding, although lock_matches_record subsequently rejects that entry. The chain-proven funding then replays as Mempool and can lose its change through the same conflict plan. Preserve chain-final evidence across both stored and raw representations, and use the replay's identity validation before treating a history lock as settlement evidence. Extend the settlement matrix with raw overlap and a mismatched history-lock entry; the proven funding's change must survive or restore must fail in a controlled way.
In `packages/rs-platform-wallet-ffi/src/persistence.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/persistence.rs:5291-5299: Carry owned input details through the recorded-history FFI
(existing thread: https://github.com/dashpay/platform/pull/5220#discussion_r4250313496)
The remaining finality-transition case still violates the PR's confirmed-history restore guarantee. Swift excludes a confirmed spend's consumed input from its UTXO projection, but this decoder supplies no owned inputs. When the funding body is unavailable and the spender pays nothing to the wallet, replay cannot stage the input or create an account-level spend mark. For an ordinary block above the restored ChainLock, irreversible_spend_claims intentionally creates no durable claim either.
When that block later becomes final and the sync checkpoint advances, the pinned key-wallet prunes its observed-spend entry. PlatformWalletInfo delegates both operations without retaining ownership or promoting a provisional guard, leaving no protection against a later funding observation. Mempool delivery is independent of the below-checkpoint block-fetch restriction, so that restriction does not close the balance-resurrection window. should_guard_unreplayed_funding_against_irreversible_spends_only explicitly expects re-credit in this case, while should_rebuild_spent_mark_for_height_only_funding_from_owned_inputs documents the protected outcome when ownership is supplied.
Transport the host's wallet-owned input index, value, and address through RecordedTransactionRestoreFFI and the Swift marshaller into StoredTransaction::owned_inputs. Alternatively, retain provisional input evidence that becomes durable at finality and retires on reorg; adding permanent claims at load for reversible blocks would reintroduce the fixed reorg defect.
In `packages/rs-platform-wallet/src/manager/history_replay.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/manager/history_replay.rs:387-393: Keep overlapping unsafe-record reservations releasable
(existing thread: https://github.com/dashpay/platform/pull/5220#discussion_r4249695152)
The recorded-body classification fixes the peer-data variant, but two overlapping UnsafeAmounts::Stored records still return None here. In the pinned key-wallet, None is a permanent guard: release_spent_claims removes only claims naming a removed transaction. If both reserving records are conclusively swept through their other inputs, their otherwise unspent shared coin remains unavailable, and funding redelivery cannot recover it during that session. The [0, 1] case in should_hold_shared_coin_while_a_record_that_may_confirm_spends_it explicitly asserts this residue.
This now requires inconsistent persisted amounts, so it is a corrupt-snapshot recovery suggestion rather than the original security blocker. Preserve the conservative guard while any potentially valid claimant survives, but retain enough claimant lifecycle information to release it after the last claimant disappears, or return a controlled recovery failure for this ambiguous snapshot instead of installing an unreleasable reservation.
Out-of-scope follow-up suggestions (4)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Repair cross-account descendant removal in live conflict settlement — At the unchanged rust-dashcore pin, the wallet-wide sweep invokes each funds account independently. A funds account with no direct loser returns before following descendants, and removed identities are propagated only to keys-only accounts. Consequently, a live conflict can leave a descendant credited in another funds account. The new replay planner compensates by combining affected records into one scratch account; the live defect predates this PR, and neither the dependency pin nor PlatformWalletInfo's live-checker delegation changes here.
- Follow-up: Track a separate upstream key-wallet fix for wallet-wide descendant closure and cleanup, with a live-checker regression spanning funds accounts.
- Validate arithmetic at the live wallet-checker boundary — The exact pinned checker still performs unchecked amount aggregation and signed net-amount subtraction on live transaction processing. The new replay preflight protects stored-history replay, not subsequent live ingress. This exposure exists at the review base and is not introduced by the restore adapter changes.
- Follow-up: Track a separate upstream fix making operand validation checked and fallible before wallet mutation, then reuse that validation for live processing and restoration.
- Move cross-account descendant removal into the wallet-wide sweep owner — Out of scope as a blocking PR finding: Cargo.toml retains rust-dashcore revision 844da0e8febc264c07fe8400b41651042fbfaae6, and platform_wallet_traits.rs is unchanged from the base. The independently verified live sweep defect predates this PR; the introduced replay planner fixes its restore-side manifestation. Retained only as a separate upstream follow-up.
- Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.
- Centralize replay policy while retaining SQLite transaction ownership — Out of scope: sqlite/rehydrate.rs is unchanged, and the PR explicitly retains SQLite's in-transaction replay while adding the shared path for record-returning persisters. General policy unification is an acknowledged follow-up, not a demonstrated new failure requiring this PR to expand its scope.
- Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
Verified the exact head against the supplied reviewer claims and all 22 prior findings: 19 are fixed, one conservative recovery limitation remains intentionally deferred, and two blockers remain. Confirmed-spend guards can still disappear when finality advances after FFI restore, and mixed-status credit outputs can cause the shipped Swift host to expose chain-final funding to destructive conflict planning. This was static verification only; the supplied exact-head CI snapshot shows Rust workspace tests queued, the wallet-only job skipped, and the Swift frozen-schema check in progress.
🔴 2 blocking
2 carried-forward finding(s) already raised on this PR; not re-posting as new inline comments.
Review provenance
Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 6: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); reviewer 7: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 8: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.1-sol(effort low) — The intricate replay_recorded_history implementation in packages/rs-platform-wallet/src/manager/history_replay.rs changes spend reservations, conflict resolution, and the restored spendable UTXO set, directly affecting coin selection and funds movement. - 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 below 15% reserve: weekly 14% left, 5h 100% left),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— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— platform-versioning (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-ffi/src/persistence.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/persistence.rs:5291-5299: Carry owned input details through the recorded-history FFI
(existing thread: https://github.com/dashpay/platform/pull/5220#discussion_r4250313496)
The decoder still supplies no owned inputs. Swift excludes spent TXOs from its restored projection, so a confirmed spend with no replayable funding body and no wallet-paying output cannot reconstruct an account-level spent mark. If its block is above the restored chain lock, irreversible_spend_claims also creates no durable claim. The pinned key-wallet prunes its temporary observed-spend evidence once both finality and the sync checkpoint pass that block, while PlatformWalletInfo's lifecycle wrappers retain no replacement evidence. A later funding observation can therefore recreate a selectable output that was already spent.
Your pending-list alternative must capture the inputs before replay consumes the history: this ownership-less, no-payout spender creates no account record from which a later finality hook could recover them. Neither that retained list nor owned-input transport exists at this head. The regression should_guard_unreplayed_funding_against_irreversible_spends_only explicitly advances finality and synced height to 300 without a reorg and then expects the spent output to return for the above-chain-lock case. Carry owned-input details through the coordinated host/FFI boundary, or retain provisional input evidence below the adapters and promote it at finality while retiring it on truncation. The finalized branch must keep the output absent, independently of the separate regression that correctly releases it after a fork.
In `packages/rs-platform-wallet/src/wallet/asset_lock/sync/recovery.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/asset_lock/sync/recovery.rs:593-599: Preserve chain-proven funding during history conflict planning
(existing thread: https://github.com/dashpay/platform/pull/5220#discussion_r4252334942)
This removes only the history row, leaving any matching raw record attached to wallet_info. The claimed Swift precondition is not enforced across a funding transaction's credit outputs: reconstruct_candidates creates a tracked entry for each owned credit output, but advance_asset_lock_status_if updates only the selected outpoint. One funding txid can consequently have a ChainLocked or Consumed entry carrying a Chain proof and a sibling still at Broadcast, while its transaction row remains mempool. Swift's buildUnresolvedAssetLockTxRecordBuffer selects individual rows with statusRaw < 2 and emits the sibling's funding transaction without excluding txids proven chain-final by another row.
After this helper withholds that funding's history row, replay's detachment set no longer contains its txid. plan_replay_sweeps then imports the attached raw record as an unconfirmed competitor, allowing a stored plain-block conflict to defeat it and remove its persisted change. Thus the documented raw-record restriction does not eliminate the regression for the shipped host; the per-row status argument overlooks the shared funding identity. Protect withheld fundings at the common load boundary, including attached raw records, or enforce the host exclusion by funding txid whenever any sibling supplies chain-final evidence. Add coverage for two credit outpoints sharing a funding txid, mixed tracked statuses, stale mempool history, and a plain-block competitor.
Out-of-scope follow-up suggestions (1)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Apply checked amount handling to live transaction ingestion — The exact pinned key-wallet revision still calculates wallet totals with unchecked signed casts and subtraction in wallet_checker.rs, and live mempool processing reaches that checker without the new load-time preflight. This is a concrete accounting and availability concern, but the ingestion path and dependency revision are unchanged by this PR; the shared replay now validates its own operands.
- Follow-up: Track a separate rust-dashcore change that validates live accounting operands and uses checked arithmetic before mutating wallet state.
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
Static verification at the exact head confirms 20 prior findings are fixed, one inconsistent-snapshot reservation limitation is intentionally deferred, and one confirmed-spend restoration blocker remains. A spend restored above the saved chain lock can lose its guard when finality advances, allowing an already-spent output to return on funding redelivery. No builds or tests were run; the supplied CI snapshot has Kotlin validation pending and does not independently establish the author-reported Rust results or native Swift validation.
🔴 1 blocking
1 carried-forward finding(s) already raised on this PR; not re-posting as new inline comments.
Review provenance
Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 6: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); reviewer 7: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 8: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.1-sol(effort low) — The intricate replay in packages/rs-platform-wallet/src/manager/history_replay.rs and load_from_persistor changes spent-output reconstruction, spend-conflict resolution, and spendable UTXO restoration, directly affecting funds availability and subsequent coin selection. - 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 below 15% reserve: weekly 14% left, 5h 100% left),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— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— platform-versioning (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-ffi/src/persistence.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/persistence.rs:5291-5299: Carry owned input details through the recorded-history FFI
(existing thread: https://github.com/dashpay/platform/pull/5220#discussion_r4250313496)
The decoder still supplies empty owned inputs, although Swift's stored input TXOs retain the input index, amount, and address. For a confirmed spend above the saved chain lock, with no replayable funding body, no restored spent coin, and no wallet-owned output, stage_recorded_spent_inputs stages nothing and replay cannot reconstruct an account spent mark. irreversible_spend_claims also excludes this reversible InBlock context. Later chain-lock and synced-height updates delegate without promoting this evidence into a durable guard, so funding redelivery after pruning can restore the consumed output. The above-chain-lock case in should_guard_unreplayed_funding_against_irreversible_spends_only explicitly expects that result; this is a later finality transition, not pruning of the above-lock spend by the original load's saved chain lock.
The proposed pending-list design can close this without extending the ABI, but it must be seeded from recorded_history: this unattributable spend may produce no account transaction record, so a list populated only from reported record promotions would miss it. Preserve the evidence before pruning, make it durable at finality, and retire reversible entries on truncation; alternatively transport owned inputs through the ABI. Require the above-chain-lock regression to keep the spent output excluded after finality, while retaining the separate fork-recovery regression.
Out-of-scope follow-up suggestions (4)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Support multiple claimants for conservative spend reservations — reservation_claimant deliberately produces an ownerless claim for overlapping UnsafeAmounts::Stored records, and the regression retains that guard even after both records are swept. The current amount classification removes transaction-body-proven cases from this residue; what remains depends on inconsistent stored values and conservatively withholds a coin rather than inflating available funds. This is a concrete recovery limitation, but extending reservation retirement across sweep and abandonment paths is separate from the remaining ordinary confirmed-spend blocker.
- Follow-up: Track multi-claimant reservation support in the wallet owner, including preservation while any claimant remains and release after the last claimant retires.
- Consolidate replay policy without moving storage transactions upward — Out of scope: SQLite's rehydrate implementation is unchanged against the PR base, and its load explicitly returns empty recorded_history after its existing transactional replay. Consolidating the engines is an explicitly excluded redesign; the separately tracked SQLite conflict-evidence issue does not justify expanding this PR.
- Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.
- Implement recorded-history restore on Android — Out of scope: the JNI constructor explicitly initializes recorded history to null/0, preserving its previous behavior, and Android history transport is expressly excluded in the PR description. This is a separate integration task, not a regression caused by the constructor update.
- Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.
- Validate transaction amounts on the live SPV processing path — Out of scope: this PR changes load-time replay and does not change the pinned wallet dependency or ordinary live processing path. Live-path amount validation is explicitly excluded; no new or worsened live-path defect was established in the reviewed diff.
- Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.
Dismissed by the PR owner: the one remaining finding (owned inputs through the recorded-history FFI) is out of scope for this PR and tracked in #5412. It predates this PR, which narrows it; see the thread reply and Known limitations.
commented
Nov 17, 2026
|
Your move: thepastaclaw left review threads unresolved; resolve them. |
|
Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them. |
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
Five blocking issues remain on this head. The shared replay still has correctness gaps for legacy physical transaction aliases and replay-created durable spend claims, while the Swift callback can abort network-less wallet restoration; the full-history load remains unbounded, and the pinned rust-dashcore revision does not export the authorization API this change imports. No build or tests were run in this static review lane; the available CI snapshot has no completed code-check failure, with review and hygiene checks still pending.
🔴 5 blocking
Still open from earlier rounds (1)
- 🔴 Blocking: Bound the attacker-amplifiable full-history replay during wallet load —
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:7789-7803(thread)
Review provenance
Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 5: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 6: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); reviewer 7: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); 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 alters wallet history replay, spent-output tracking, funds availability, cross-language persistence, and SQLite migrations, directly affecting coin selection and prevention of double-crediting spent funds. - 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)
- Code unchanged since the last final review (
dfed0ead): 2 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 2 confirmed - 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
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/rs-platform-wallet/src/manager/history_claims.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_claims.rs:329-347: Persist replay-created irreversible spend claims for surviving unbacked spends
The replay creates irreversible claims in memory for surviving chain-locked or InstantSend-locked records through `irreversible_spend_claims`, but `HistoryReplay::storage_effects` only adds inputs to `affected` when a record is removed, an existing claim is touched, or a withheld asset-lock input is processed. A surviving final spend whose funding row is absent and which has no pre-existing durable claim therefore appears only in `survivors`; no `ReplayClaimEffect::Hold` is emitted. `repair_wallet_history` then sees no storage effect to write and returns a wallet whose protection exists only in memory. If that history row is later pruned or the wallet is reconstructed without it, redelivering the funding can credit an already-spent output. Include every surviving irreversible spend input requiring protection in the durable claim projection and cover repair, reread, pruning, and redelivery with no funding row or pre-existing claim.
_Raised on code unchanged since the last review, and confirmed by an independent pass: A chain-locked or InstantSend-locked stored spend whose funding transaction is absent from history and has no existing durable claim is guarded only by `restore_spent_outpoints` in the replayed in-memory wallet. Because `storage_effects` does not mark survivor inputs as affected, `repair_wallet_history` emits no `ReplayClaimEffect::Hold` and writes nothing; after the history row is pruned or the wallet is reconstructed, redelivery of the funding output can credit an already-spent coin._
In `packages/rs-platform-wallet-storage/src/sqlite/persister.rs`:
- [BLOCKING] packages/rs-platform-wallet-storage/src/sqlite/persister.rs:1895-1905: Normalize legacy physical aliases before replay conflict planning and effect application
SQLite deliberately retains legacy AssetUnlock rows under their physical SQL keys, but `load_snapshot` constructs each `StoredTransaction` with that physical key while its decoded body has a different canonical transaction id. The shared replay and `raw_record` path use the body id for checker records and conflict results, whereas `HistoryReplay::storage_effects` and SQLite `apply_effects` still match removed records and evidence against physical keys and issue deletes by those ids. Consequently, a canonical sweep result can fail to match the legacy physical row, leaving the defeated alias and its evidence persisted and replayable on every subsequent load. The same mixed identity model can prevent tracked lock matching. Carry canonical body ids separately from physical storage keys throughout planning, then translate canonical results to all physical aliases only when producing backend effects; add a losing legacy AssetUnlock alias regression across repair and reload.
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:
- [BLOCKING] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:5484-5488: Do not abort history restoration when a legacy handler has no resolved network
`loadCoreInstantLock` always calls `coreInstantLockDescriptor`, which throws when both the handler's `network` and the persisted wallet's `networkRaw` are nil. The Rust FFI invokes this callback once for every recorded-history transaction, including ordinary confirmed and mempool records that have no InstantLock sidecar, and converts any nonzero callback result into a load error. Thus the supported network-less legacy configuration can fail the entire wallet restoration merely because a normal history row has no resolved network. Return an absent sidecar when the network cannot be resolved; Rust already applies the missing-evidence or legacy-recovery policy only when the transaction requires finality evidence.
_Raised on code unchanged since the last review, and confirmed by an independent pass: Restoring any wallet with an ordinary recorded confirmed or mempool transaction through a legacy handler whose handler network and persisted wallet `networkRaw` are both nil causes `loadCoreInstantLock` to throw while looking up the optional sidecar. The Swift callback returns an error, Rust propagates it from `load_core_instant_locks` through `build_wallet_start_state`, and the entire wallet-list restoration fails even though that transaction does not require InstantLock evidence._
- [BLOCKING] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:7789-7803: Bound the attacker-amplifiable full-history replay during wallet load
(carried; thread: https://github.com/dashpay/platform/pull/5220#discussion_r4265416171)
In `Cargo.toml`:
- [BLOCKING] Cargo.toml:73-77: Pin a rust-dashcore revision that exports the replay authorization API
`packages/rs-platform-wallet/src/manager/history_authorization.rs` imports `key_wallet::transaction_checking::spend_authorization::verify_input_authorization`, but the rust-dashcore revision pinned here (`bdf90431`, the #1336 head) contains no `transaction_checking::spend_authorization` module or function. The reviewed range therefore cannot compile independently of the replay logic. Select and pin an upstream revision that combines the required authorization API with the InstantLock and dev APIs this branch needs, then regenerate `Cargo.lock`; do not duplicate the upstream authorization implementation in this repository or an FFI layer.
| let mut affected = BTreeSet::new(); | ||
| let mut release_allowed = BTreeSet::new(); | ||
| let mut survivors: BTreeMap<OutPoint, BTreeMap<Txid, Option<u32>>> = BTreeMap::new(); | ||
| for (key, (body, record)) in &records_by_key { | ||
| for input in &record.transaction.input { | ||
| if removed_records.contains(key) { | ||
| affected.insert(input.previous_output); | ||
| if self.authorization.rejected.contains(body) { | ||
| release_allowed.insert(input.previous_output); | ||
| } | ||
| } else { | ||
| let height = record.context.block_info().map(|block| block.height()); | ||
| survivors | ||
| .entry(input.previous_output) | ||
| .or_default() | ||
| .entry(*body) | ||
| .and_modify(|stamp| *stamp = merge_same_claim_stamp(*stamp, height)) | ||
| .or_insert(height); | ||
| } |
There was a problem hiding this comment.
🔴 Blocking: Persist replay-created irreversible spend claims for surviving unbacked spends
The replay creates irreversible claims in memory for surviving chain-locked or InstantSend-locked records through irreversible_spend_claims, but HistoryReplay::storage_effects only adds inputs to affected when a record is removed, an existing claim is touched, or a withheld asset-lock input is processed. A surviving final spend whose funding row is absent and which has no pre-existing durable claim therefore appears only in survivors; no ReplayClaimEffect::Hold is emitted. repair_wallet_history then sees no storage effect to write and returns a wallet whose protection exists only in memory. If that history row is later pruned or the wallet is reconstructed without it, redelivering the funding can credit an already-spent output. Include every surviving irreversible spend input requiring protection in the durable claim projection and cover repair, reread, pruning, and redelivery with no funding row or pre-existing claim.
Raised on code unchanged since the last review, and confirmed by an independent pass: A chain-locked or InstantSend-locked stored spend whose funding transaction is absent from history and has no existing durable claim is guarded only by restore_spent_outpoints in the replayed in-memory wallet. Because storage_effects does not mark survivor inputs as affected, repair_wallet_history emits no ReplayClaimEffect::Hold and writes nothing; after the history row is pruned or the wallet is reconstructed, redelivery of the funding output can credit an already-spent coin.
source: gpt-6.1-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality, security-auditor)
| // Replay effects address physical rows; history projection may deduplicate aliases. | ||
| let recorded_transactions = core_state | ||
| .records | ||
| .iter() | ||
| .cloned() | ||
| .zip(record_keys) | ||
| .map(|(record, key)| { | ||
| let mut stored = platform_wallet::changeset::StoredTransaction::from(record); | ||
| stored.txid = key; | ||
| stored | ||
| }) |
There was a problem hiding this comment.
✅ Withdrawn at
f82a3d69; see the replies below.
🔴 Blocking: Normalize legacy physical aliases before replay conflict planning and effect application
SQLite deliberately retains legacy AssetUnlock rows under their physical SQL keys, but load_snapshot constructs each StoredTransaction with that physical key while its decoded body has a different canonical transaction id. The shared replay and raw_record path use the body id for checker records and conflict results, whereas HistoryReplay::storage_effects and SQLite apply_effects still match removed records and evidence against physical keys and issue deletes by those ids. Consequently, a canonical sweep result can fail to match the legacy physical row, leaving the defeated alias and its evidence persisted and replayable on every subsequent load. The same mixed identity model can prevent tracked lock matching. Carry canonical body ids separately from physical storage keys throughout planning, then translate canonical results to all physical aliases only when producing backend effects; add a losing legacy AssetUnlock alias regression across repair and reload.
source: gpt-6.1-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality, security-auditor)
There was a problem hiding this comment.
Withdrawn (re-reviewed at f82a3d69): I traced the pinned sweep to the scratch map keys, which are the physical keys your SQLite effects need. A valid aliased AssetUnlock has no inputs to lose that conflict or to match a verified InstantLock.
| func loadCoreInstantLock(walletId: Data, txid: Data) throws -> Data? { | ||
| try onQueue { | ||
| try backgroundContext.fetch(coreInstantLockDescriptor(walletId: walletId, txid: txid)) | ||
| .first?.consensusBytes | ||
| } |
There was a problem hiding this comment.
🔴 Blocking: Do not abort history restoration when a legacy handler has no resolved network
loadCoreInstantLock always calls coreInstantLockDescriptor, which throws when both the handler's network and the persisted wallet's networkRaw are nil. The Rust FFI invokes this callback once for every recorded-history transaction, including ordinary confirmed and mempool records that have no InstantLock sidecar, and converts any nonzero callback result into a load error. Thus the supported network-less legacy configuration can fail the entire wallet restoration merely because a normal history row has no resolved network. Return an absent sidecar when the network cannot be resolved; Rust already applies the missing-evidence or legacy-recovery policy only when the transaction requires finality evidence.
Raised on code unchanged since the last review, and confirmed by an independent pass: Restoring any wallet with an ordinary recorded confirmed or mempool transaction through a legacy handler whose handler network and persisted wallet networkRaw are both nil causes loadCoreInstantLock to throw while looking up the optional sidecar. The Swift callback returns an error, Rust propagates it from load_core_instant_locks through build_wallet_start_state, and the entire wallet-list restoration fails even though that transaction does not require InstantLock evidence.
source: gpt-6.1-sol (phase2-reviewer: ffi-engineer)
| # TODO(upstream-merge): move this wallet-restore authorization pin to merged rust-dashcore dev after PR #1336 lands. | ||
| dashcore = { git = "https://github.com/dashpay/rust-dashcore", rev = "bdf90431b300bffa1e5ede8d04a3d27a35532e94" } | ||
| dash-network-seeds = { git = "https://github.com/dashpay/rust-dashcore", rev = "bdf90431b300bffa1e5ede8d04a3d27a35532e94" } | ||
| dash-spv = { git = "https://github.com/dashpay/rust-dashcore", rev = "bdf90431b300bffa1e5ede8d04a3d27a35532e94" } | ||
| key-wallet = { git = "https://github.com/dashpay/rust-dashcore", rev = "bdf90431b300bffa1e5ede8d04a3d27a35532e94" } |
There was a problem hiding this comment.
✅ Resolved at
f82a3d69; see the replies below.
🔴 Blocking: Pin a rust-dashcore revision that exports the replay authorization API
packages/rs-platform-wallet/src/manager/history_authorization.rs imports key_wallet::transaction_checking::spend_authorization::verify_input_authorization, but the rust-dashcore revision pinned here (bdf90431, the #1336 head) contains no transaction_checking::spend_authorization module or function. The reviewed range therefore cannot compile independently of the replay logic. Select and pin an upstream revision that combines the required authorization API with the InstantLock and dev APIs this branch needs, then regenerate Cargo.lock; do not duplicate the upstream authorization implementation in this repository or an FFI layer.
source: gpt-6.1-sol (phase2-reviewer: architecture-layering)
There was a problem hiding this comment.
Resolved (re-reviewed at f82a3d69): Your ffcff0ab pin exports verify_input_authorization at the imported path and provides the SPV verification API. Replacing the integration pin after the upstream merges is a separate merge prerequisite.
commented
Nov 21, 2026
|
Status: What changed in this update (f82a3d6)
To merge
🤖 Co-authored by Claudius the Magnificent AI Agent |
|
PR Hygiene: the checklist is in the description. |
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
The new integration pin restores the required Rust APIs, and exact-head Rust and Kotlin CI passed, but the expanded V5 schema fails three Swift migration tests and V023 can discard wallet state that a rescan cannot safely replace. Dashmate’s local-network job timed out at the same block height on the exact base and head, so it is not a new failure. The ten-comment cap leaves seven verified items unlisted: the iOS wallet-drain and Android invitation capability regressions, the Swift bootstrap Retry latch, fatal handling of indeterminate pending-input authorization, and three narrower decode or replay-cost suggestions.
A pattern across this PR's review rounds
This is review round 24, and the PR has drawn 32 blocking findings so far. 16 of them share 4 underlying causes. They are listed with the other findings as usual; fixing the cause is likely to be cheaper than fixing each case.
1. Spend guards have no single lifecycle (1 new in this round, 5 earlier finding(s))
The wallet checker, HistoryReplay::storage_effects, and the V023 rescan each decide separately what keeps an outpoint spent. irreversible_spend_claims can guard an outpoint in memory without producing a durable hold, while restore_spent_outpoints can restore a hold that a fork cannot release. V023 reaches the same gap from the other direction: it can delete the stored guard and spender before the rescan has rebuilt either.
Already tracked: dashpay/rust-dashcore#1435
In this round: Preserve spend guards, used scripts, and labels across the V023 rescan
2. Repair is still reachable through ordinary reads (1 new in this round, 1 earlier finding(s))
Moving the repair loop into repair_wallet_history gave SQLite and FFI one owner for repair policy, but did not give repair a single entry point. SQLite load() can still enter write-capable replay without the verified evidence or publication fence used by load_wallet_with_replay. Candidate discovery and the fenced reread also use separate LoadCtx instances, so fixing the repair loop did not preserve the discovery pass's wallet isolation or degradation report.
In this round: Keep SQLite discovery and inspection separate from fenced history repair
3. Finality depends on how the evidence was stored (6 earlier finding(s))
A transaction's stored context, its tracked asset-lock proof, and its PersistentCoreInstantLock sidecar enter restore through different paths. Fixing one path left others behind: a mined row could miss its InstantLock, and an older row with only a status had no proof for a retry to verify. The sidecar fix also made an optional lookup a reason to reject ordinary history from a legacy wallet with no resolved network.
4. Startup work is tied to total history (5 earlier finding(s))
loadWalletList fetches the full PersistentTransaction table before filtering it per wallet, and Rust materializes the resulting history for conflict planning and replay. Prefetching relationships and indexing competitors reduce particular costs, but without a budget or checkpoint there is still no upper bound on the work required before a wallet can open.
Already tracked: #5962
Suggested decision (redesign the component): Redesign Core history restore as one wallet-owned operation that decides which spend guards to keep, promote, or release before publishing a spendable wallet. Only the fenced startup path should commit those decisions, and a migration or rescan should not discard history until equivalent protection is durable. Keep legacy snapshots that cannot meet that guarantee out of spendable restore rather than relying on later redelivery to make them safe.
🔴 10 blocking
10 finding(s) not shown inline (GitHub refused the PR diff as too large)
🔴 Blocking: Do not abort history restoration when a legacy handler has no resolved network
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:5465-5473
loadWalletList still admits wallets whose legacy network is unset, but loadCoreInstantLock calls a descriptor that throws for those same wallets. Rust probes that callback for every recorded transaction and propagates any error, so even an ordinary mined row with no sidecar prevents the wallet from opening. The current network helper uses try?, so treating its nil result as absence would also hide database errors. Give reads a throwing lookup that distinguishes a successfully read wallet with no sidecar namespace from a failed fetch, and keep the network requirement on writes.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality)
🔴 Blocking: Persist replay-created irreversible spend claims for surviving unbacked spends
packages/rs-platform-wallet/src/manager/history_claims.rs:329-347
A final spend can survive replay with no funding body, prior hold, or losing competitor. Its input enters survivors but not affected, so the claim protects the returned wallet without producing a durable Hold. If the spend body is later removed, a fresh load has no guard against crediting the old funding again. There is a second gap in the same claim path: irreversible_spend_claims ignores a verified InstantLock when the surviving record retains its InBlock context. mark_instant_send_utxos retains the lock identity, not the missing input guard. Derive the guard from surviving verified evidence without replacing BlockInfo, carry it in the verdict, and emit a hold only when equivalent protection is not already stored. Test idempotent repair, then remove the spend body, reopen, and redeliver the funding.
source: gpt-6.2-astra (phase2-reviewer: general, ffi-engineer, security-auditor)
🔴 Blocking: Do not turn unreadable confirmed history into missing spend evidence
packages/rs-platform-wallet-ffi/src/persistence.rs:6475-6491
Swift's independent spent-TXO export protects a dropped body when the host actually supplies that evidence. But CORE_HISTORY_RESTORE can be attested with only the wallet-list load/free pair, and load_wallet_replay_scope takes a raw-snapshot path on that configuration without reading claims. The decoder has already discarded any malformed or mismatched confirmed body, so the manager can publish a wallet whose host excluded the spent coin but supplied no surviving guard. Carry the decode failure to the restore owner or reject the snapshot when spend protection cannot be established. Also reject a null recorded-row pointer with a nonzero count.
source: gpt-6.2-astra (phase2-reviewer: ffi-engineer)
🔴 Blocking: Preserve InstantSend finality when decoding FFI history rows
packages/rs-platform-wallet/src/manager/history_replay.rs:194-214
The decoder now transports the marker, but the legacy branch removes it from the planner's input. A stale plain-block competitor can then defeat the status-only InstantSend row as mempool history. Atomic repair can delete that row and its change, then replace the rewound wallet with a reread that no longer sees any reason to rescan. The adjacent tracked-funding branch has the opposite failure: withholding a chain-final funding also hides its inputs from the planner, and the fixture explicitly retains both change outputs for mutually exclusive spends. Preserve both kinds of evidence in settlement: defer destructive repair when legacy finality is unresolved, and pass the chain-final funding's input set to the planner or reject the contradiction without inventing a block hash.
source: gpt-6.2-astra (phase2-reviewer: security-auditor)
🔴 Blocking: Bound the attacker-amplifiable full-history replay during wallet load
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:7884-7897
The new startup path fetches the entire transaction table, buckets it per wallet, and hands matching bodies to Rust for cloning, indexing and replay before the wallet can open. The new claim export has a separate failure at scale: after Swift allocates one row per TXO and pending input, Rust rejects the whole wallet at MAX_VEC_SIZE / size_of::<ReplayClaimRestoreFFI>()—38,461 rows on 64-bit iOS. That late wire-message cutoff neither bounds the host allocation nor supports valid large wallets. Implement checkpointed or paged restore that preserves spend evidence within the same snapshot, or establish an early, actionable restore budget rather than truncating evidence or rejecting a valid lifetime row count as malformed.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
🔴 Blocking: Do not let accounting backfill overwrite a newer live accounting row
packages/rs-platform-wallet/src/manager/load.rs:934-955
The linked #5417 comment describes the fix, but the unmerged stack on this head does not contain it. The manager drops its read lock after computing the rows, and FFIPersister::store_history_accounting later sends them through the live accounting upsert. A live update can commit in between; Swift then overwrites that newer amount, fee and direction and can commit the backfill completion marker in the same round. The target base does not have this backfill. Land insert-if-still-unaccounted or version-checked semantics in #5417 and update this stack to include them before merging.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
🔴 Blocking: Retire restored block-spend claims when their block is reorged out
packages/rs-platform-wallet/src/manager/history_repair.rs:156-171
The new exception handles the case where both bodies reached the checker, but a stored hold for a reversible spend with missing funding still goes into a claim map with no reorg lifecycle. The pinned truncate_above removes observed spends by height and passes the claim map through unchanged, so redelivery after the fork still rejects the now-unspent funding. The Swift producer also flattens ordinary pending-input observations into is_held = true, even though its live reconciliation only lets a swept tombstone establish a hold without resolving the spender. Preserve provenance and height across the ABI and let Rust distinguish a provisional block spend, an unresolved observation, and a settled hold. The missing-funding fork case needs lifecycle-aware restoration, not an unconditional release; rust-dashcore#1435 tracks that owner API.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
🔴 Blocking: Keep SQLite discovery and inspection separate from fenced history repair
packages/rs-platform-wallet-storage/src/sqlite/persister.rs:1517-1557
load() now runs whole-store repair with empty evidence. Existing callers use it to read registration cursors, viewing keys, and wallet-drain status. A lock in another wallet can therefore make those reads fail with MissingFinalityEvidence even after a successful verified restore, or an inspection can commit a repair for an already-live wallet. Startup has a related boundary problem: candidate discovery reconstructs every wallet with ? before Recovery mode can quarantine a damaged one, then a healthy per-wallet reread replaces the entire degradation report. Use the policy-filtered, read-only snapshot for discovery and inspection; preserve its degradation report across per-wallet rereads; and run evidence-bearing repair only on the admitted wallet under the manager's fence. Cover a healthy sibling beside a damaged wallet and an inspection after verified restore.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
🔴 Blocking: Preserve spend guards, used scripts, and labels across the V023 rescan
packages/rs-platform-wallet-storage/src/sqlite/migrations/v023.rs:35-53
For wallets outside core_rescan_preserved_wallets, V023 can delete both the spent UTXO and the mined spender body. Rewinding the cursor schedules a rescan but does not stop the wallet from exposing the funding as available before a later batch rediscovers its spend. The deletion also loses used-address evidence when a UTXO's script has no used pool row, and deleting or nulling record_blob loses labels that block redelivery cannot reconstruct. V021's archive only covers rows it actually repaired. Keep the guards until replacement evidence is committed, and migrate used scripts and local transaction metadata independently of the spendable projection. Test a V022 wallet before the first rescan, between funding and spend delivery, and after catch-up.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
🔴 Blocking: Make the expanded V5 schema pass both upgrade and preservation checks
packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift:459-463
Swift job 136820095353 reports five actual V5 additions, not two: the exact-set check also needs PersistentLockedOutpoint, PersistentPrivateContactRequestsPosition, and PersistentPrivateShieldedAddress from the merged base. The same job fails testAcceptedV1PreservesAllThirteenFieldsMissingFromHistoricalV2 and testHistoricalV2AddsDefaultsAndPreservesDocumentRelationships at DashLegacyStoreSQLite.swift:221 with “Migration removed or converted a column in ZPERSISTENTTOKENBALANCE”; the exact base passed. Both fixtures have Z13TOKENBALANCES with ordinal 13 mapped to PersistentIdentity, but the preservation checker normalizes only the Z_<ordinal> spelling. Validate the migrated relationship by logical entity and relationship identity while still comparing types and values. If those values differ, fix the migration itself. The log proves that the upgrade is rejected, not that balances were deleted.
Raised on code unchanged since the last review, and confirmed by an independent pass: The new V5-minus-V4 assertion expects two entities, but the schema difference contains five, so the Swift SDK test job fails. The same job also fails the accepted V1 and historical V2 fixture tests when their post-upgrade preservation checks throw on ZPERSISTENTTOKENBALANCE.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
Still open from earlier rounds (5)
- 🔴 Blocking: Do not abort history restoration when a legacy handler has no resolved network —
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:5465-5473(thread) - 🔴 Blocking: Persist replay-created irreversible spend claims for surviving unbacked spends —
packages/rs-platform-wallet/src/manager/history_claims.rs:329-347(thread) - 🔴 Blocking: Do not turn unreadable confirmed history into missing spend evidence —
packages/rs-platform-wallet-ffi/src/persistence.rs:6475-6491(thread) - 🔴 Blocking: Bound the attacker-amplifiable full-history replay during wallet load —
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:7884-7897(thread) - 🔴 Blocking: Do not let accounting backfill overwrite a newer live accounting row —
packages/rs-platform-wallet/src/manager/load.rs:934-955(thread)
Review provenance
Source: reviewer 1: gpt-6.2-astra (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.2-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.2-astra (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 5: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 6: gpt-6.2-astra (agent: phase2-reviewer, role: platform-versioning); reviewer 7: gpt-6.2-astra (agent: phase2-reviewer, role: rust-quality); reviewer 8: gpt-6.2-astra (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.2-sol(effort low) — The large, intricate change rewrites spent-output reconstruction inmanager/history_replay.rs, which determines whether restored coins are available to spend, and changes persistent storage through the SQLite V023 migration and SwiftData V5 schema. - 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)
- Code unchanged since the last final review (
72b06ac4): 1 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 1 confirmed - Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.2-astra— general (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— ffi-engineer (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— platform-versioning (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— rust-quality (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— security-auditor (completed, effort high); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
Several findings on this PR share an underlying cause (the review's "pattern" section): Spend guards have no single lifecycle; Repair is still reachable through ordinary reads; Finality depends on how the evidence was stored; Startup work is tied to total history. When you fix the findings below, fix the cause, not only the reported case. The review suggests (redesign the component): Redesign Core history restore as one wallet-owned operation that decides which spend guards to keep, promote, or release before publishing a spendable wallet. Only the fenced startup path should commit those decisions, and a migration or rescan should not discard history until equivalent protection is durable. Keep legacy snapshots that cannot meet that guarantee out of spendable restore rather than relying on later redelivery to make them safe. If that decision is not yours to make, say so to the PR's author or maintainer.
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/rs-platform-wallet/src/manager/history_replay.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_replay.rs:194-214: Preserve InstantSend finality when decoding FFI history rows
The decoder now transports the marker, but the legacy branch removes it from the planner's input. A stale plain-block competitor can then defeat the status-only InstantSend row as mempool history. Atomic repair can delete that row and its change, then replace the rewound wallet with a reread that no longer sees any reason to rescan. The adjacent tracked-funding branch has the opposite failure: withholding a chain-final funding also hides its inputs from the planner, and the fixture explicitly retains both change outputs for mutually exclusive spends. Preserve both kinds of evidence in settlement: defer destructive repair when legacy finality is unresolved, and pass the chain-final funding's input set to the planner or reject the contradiction without inventing a block hash.
In `packages/rs-platform-wallet/src/manager/history_repair.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_repair.rs:156-171: Retire restored block-spend claims when their block is reorged out
The new exception handles the case where both bodies reached the checker, but a stored hold for a reversible spend with missing funding still goes into a claim map with no reorg lifecycle. The pinned `truncate_above` removes observed spends by height and passes the claim map through unchanged, so redelivery after the fork still rejects the now-unspent funding. The Swift producer also flattens ordinary pending-input observations into `is_held = true`, even though its live reconciliation only lets a swept tombstone establish a hold without resolving the spender. Preserve provenance and height across the ABI and let Rust distinguish a provisional block spend, an unresolved observation, and a settled hold. The missing-funding fork case needs lifecycle-aware restoration, not an unconditional release; rust-dashcore#1435 tracks that owner API.
In `packages/rs-platform-wallet-storage/src/sqlite/persister.rs`:
- [BLOCKING] packages/rs-platform-wallet-storage/src/sqlite/persister.rs:1517-1557: Keep SQLite discovery and inspection separate from fenced history repair
`load()` now runs whole-store repair with empty evidence. Existing callers use it to read registration cursors, viewing keys, and wallet-drain status. A lock in another wallet can therefore make those reads fail with `MissingFinalityEvidence` even after a successful verified restore, or an inspection can commit a repair for an already-live wallet. Startup has a related boundary problem: candidate discovery reconstructs every wallet with `?` before Recovery mode can quarantine a damaged one, then a healthy per-wallet reread replaces the entire degradation report. Use the policy-filtered, read-only snapshot for discovery and inspection; preserve its degradation report across per-wallet rereads; and run evidence-bearing repair only on the admitted wallet under the manager's fence. Cover a healthy sibling beside a damaged wallet and an inspection after verified restore.
In `packages/rs-platform-wallet-storage/src/sqlite/migrations/v023.rs`:
- [BLOCKING] packages/rs-platform-wallet-storage/src/sqlite/migrations/v023.rs:35-53: Preserve spend guards, used scripts, and labels across the V023 rescan
For wallets outside `core_rescan_preserved_wallets`, V023 can delete both the spent UTXO and the mined spender body. Rewinding the cursor schedules a rescan but does not stop the wallet from exposing the funding as available before a later batch rediscovers its spend. The deletion also loses used-address evidence when a UTXO's script has no used pool row, and deleting or nulling `record_blob` loses labels that block redelivery cannot reconstruct. V021's archive only covers rows it actually repaired. Keep the guards until replacement evidence is committed, and migrate used scripts and local transaction metadata independently of the spendable projection. Test a V022 wallet before the first rescan, between funding and spend delivery, and after catch-up.
In `packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift`:
- [BLOCKING] packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift:459-463: Make the expanded V5 schema pass both upgrade and preservation checks
Swift job 136820095353 reports five actual V5 additions, not two: the exact-set check also needs `PersistentLockedOutpoint`, `PersistentPrivateContactRequestsPosition`, and `PersistentPrivateShieldedAddress` from the merged base. The same job fails `testAcceptedV1PreservesAllThirteenFieldsMissingFromHistoricalV2` and `testHistoricalV2AddsDefaultsAndPreservesDocumentRelationships` at `DashLegacyStoreSQLite.swift:221` with “Migration removed or converted a column in ZPERSISTENTTOKENBALANCE”; the exact base passed. Both fixtures have `Z13TOKENBALANCES` with ordinal 13 mapped to `PersistentIdentity`, but the preservation checker normalizes only the `Z_<ordinal>` spelling. Validate the migrated relationship by logical entity and relationship identity while still comparing types and values. If those values differ, fix the migration itself. The log proves that the upgrade is rejected, not that balances were deleted.
_Raised on code unchanged since the last review, and confirmed by an independent pass: The new V5-minus-V4 assertion expects two entities, but the schema difference contains five, so the Swift SDK test job fails. The same job also fails the accepted V1 and historical V2 fixture tests when their post-upgrade preservation checks throw on ZPERSISTENTTOKENBALANCE._
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:
- [BLOCKING] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:5465-5473: Do not abort history restoration when a legacy handler has no resolved network
(carried; thread: https://github.com/dashpay/platform/pull/5220#discussion_r4603783729)
- [BLOCKING] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:7884-7897: Bound the attacker-amplifiable full-history replay during wallet load
(carried; thread: https://github.com/dashpay/platform/pull/5220#discussion_r4265416171)
In `packages/rs-platform-wallet/src/manager/history_claims.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_claims.rs:329-347: Persist replay-created irreversible spend claims for surviving unbacked spends
(carried; thread: https://github.com/dashpay/platform/pull/5220#discussion_r4603783705)
In `packages/rs-platform-wallet-ffi/src/persistence.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/persistence.rs:6475-6491: Do not turn unreadable confirmed history into missing spend evidence
(carried; thread: https://github.com/dashpay/platform/pull/5220#discussion_r4389526583)
In `packages/rs-platform-wallet/src/manager/load.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/load.rs:934-955: Do not let accounting backfill overwrite a newer live accounting row
(carried; thread: https://github.com/dashpay/platform/pull/5220#discussion_r4498927685)
| // Replay effects address physical rows; history projection may deduplicate aliases. | ||
| let recorded_transactions = core_state | ||
| .records | ||
| .iter() | ||
| .cloned() | ||
| .zip(record_keys) | ||
| .map(|(record, key)| { | ||
| let mut stored = platform_wallet::changeset::StoredTransaction::from(record); | ||
| stored.txid = key; | ||
| stored | ||
| }) |
There was a problem hiding this comment.
Withdrawn (re-reviewed at f82a3d69): I traced the pinned sweep to the scratch map keys, which are the physical keys your SQLite effects need. A valid aliased AssetUnlock has no inputs to lose that conflict or to match a verified InstantLock.
| # TODO(upstream-merge): move this wallet-restore authorization pin to merged rust-dashcore dev after PR #1336 lands. | ||
| dashcore = { git = "https://github.com/dashpay/rust-dashcore", rev = "bdf90431b300bffa1e5ede8d04a3d27a35532e94" } | ||
| dash-network-seeds = { git = "https://github.com/dashpay/rust-dashcore", rev = "bdf90431b300bffa1e5ede8d04a3d27a35532e94" } | ||
| dash-spv = { git = "https://github.com/dashpay/rust-dashcore", rev = "bdf90431b300bffa1e5ede8d04a3d27a35532e94" } | ||
| key-wallet = { git = "https://github.com/dashpay/rust-dashcore", rev = "bdf90431b300bffa1e5ede8d04a3d27a35532e94" } |
There was a problem hiding this comment.
Resolved (re-reviewed at f82a3d69): Your ffcff0ab pin exports verify_input_authorization at the imported path and provides the SPV verification API. Replacing the integration pin after the upstream merges is a separate merge prerequisite.
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
The base merge leaves the shared replay design in place; this review also verifies mobile capability regressions, an SPV retry dead end, an authorization error that prevents catch-up, and a stale address snapshot that can reach publication. Exact-head Rust workspace and Kotlin checks passed; Swift failed three migration tests, Dashmate Local Network timed out waiting for its Core nodes to reach the same height before wallet replay was exercised, and the main Test Suite was pending. All blockers are included, four over the ten-comment budget; two lower-priority suggestions were omitted.
A pattern across this PR's review rounds
This is review round 25, and the PR has drawn 39 blocking findings so far. 19 of them share 4 underlying causes. They are listed with the other findings as usual; fixing the cause is likely to be cheaper than fixing each case.
1. Spend guards have no single lifecycle (6 earlier finding(s))
The wallet checker, HistoryReplay::storage_effects, and the V023 rescan do not share one rule for when an outpoint must stay spent. irreversible_spend_claims can protect an outpoint in memory without producing a durable hold, while restore_spent_outpoints can install a hold that a fork cannot release. V023 can remove the stored guard and spender before the rescan has rebuilt either.
Already tracked: dashpay/rust-dashcore#1435
2. Discovery and repair have no clean handoff (1 new in this round, 2 earlier finding(s))
repair_wallet_history owns the repair loop, but it does not define which read is authoritative for publication. SQLite load() can still run repair outside the startup fence, while load_from_persistor merges the fenced reread into discovery state, so an absent platform_addresses entry can leave old balances and a sync cursor in a newly admitted wallet.
In this round: Use only the fenced reread's platform-address state
3. Finality depends on how evidence was stored (1 new in this round, 7 earlier finding(s))
Stored transaction contexts, PersistentCoreInstantLock sidecars, and tracked asset-lock proofs are interpreted separately rather than turned into one settlement decision per transaction. withhold_chain_final_fundings keeps a funding out of the checker when its block is unknown, but it also hides its inputs from conflict planning and can leave an InstantSend proof requirement for a body the proof binder no longer sees. The same split is why earlier fixes carried finality for one kind of row while losing it for another.
In this round: Carry chain-final funding evidence through conflict planning
4. Startup work is tied to total history (5 earlier finding(s))
loadWalletList fetches the full PersistentTransaction table before filtering it per wallet, and Rust materializes the selected history for conflict planning and replay. Prefetching and indexing remove particular sources of repeated work, but there is still no budget or checkpoint that bounds the work before a wallet can open.
Already tracked: #5962
Suggested decision (redesign the component): Make Core history restore one wallet-owned admission operation: publish a spendable wallet only from the fenced snapshot, after bounded replay has settled the available evidence and made the required spend guards durable with the correct reorg behavior. Only that path should commit replay repair; a migration or rescan must not discard evidence before equivalent protection is durable. Keep snapshots that cannot meet that contract out of spendable restore and give the caller an explicit recovery path.
🔴 14 blocking
Still open from earlier rounds (4)
- 🔴 Blocking: Do not abort history restoration when a legacy handler has no resolved network —
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:5465-5473(thread) - 🔴 Blocking: Persist replay-created irreversible spend claims for surviving unbacked spends —
packages/rs-platform-wallet/src/manager/history_claims.rs:329-347(thread) - 🔴 Blocking: Do not turn unreadable confirmed history into missing spend evidence —
packages/rs-platform-wallet-ffi/src/persistence.rs:6461-6493(thread) - 🔴 Blocking: Bound the attacker-amplifiable full-history replay during wallet load —
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:7890-7904(thread)
Review provenance
Source: reviewer 1: gpt-6.2-astra (agent: phase2-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 3: gpt-6.2-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 4: gpt-6.2-astra (agent: phase2-reviewer, role: ffi-engineer); reviewer 5: gpt-6.2-astra (agent: phase2-reviewer, role: platform-versioning); reviewer 6: gpt-6.2-astra (agent: phase2-reviewer, role: rust-quality); reviewer 7: gpt-6.2-astra (agent: phase2-reviewer, role: security-auditor); reviewer 8: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.2-sol(effort low) — The diff adds intricate replay and atomic repair logic inmanager/history_replay.rsandmanager/history_repair.rsthat determines which wallet outputs are spendable after restart, and changes persisted schemas in SQLite and SwiftData. - 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)
- Code unchanged since the last final review (
f82a3d69): 3 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 3 confirmed - Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.2-astra— general (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— ffi-engineer (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— platform-versioning (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— rust-quality (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— security-auditor (completed, effort high); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
Several findings on this PR share an underlying cause (the review's "pattern" section): Spend guards have no single lifecycle; Discovery and repair have no clean handoff; Finality depends on how evidence was stored; Startup work is tied to total history. When you fix the findings below, fix the cause, not only the reported case. The review suggests (redesign the component): Make Core history restore one wallet-owned admission operation: publish a spendable wallet only from the fenced snapshot, after bounded replay has settled the available evidence and made the required spend guards durable with the correct reorg behavior. Only that path should commit replay repair; a migration or rescan must not discard evidence before equivalent protection is durable. Keep snapshots that cannot meet that contract out of spendable restore and give the caller an explicit recovery path. If that decision is not yours to make, say so to the PR's author or maintainer.
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift`:
- [BLOCKING] packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift:459-463: Make the expanded V5 schema pass both upgrade and preservation checks
Swift SDK job 136842494784 reports five V5 additions, not two: the expected set omits `PersistentPrivateContactRequestsPosition`, `PersistentPrivateShieldedAddress`, and `PersistentLockedOutpoint`. The same job rejects both the accepted-V1 and historical-V2 fixture upgrades at `DashLegacyStoreSQLite.swift:221` with “Migration removed or converted a column in ZPERSISTENTTOKENBALANCE.” Both source fixtures contain the integer relationship column `Z13TOKENBALANCES`, with ordinal 13 mapped to `PersistentIdentity`; `normalize` handles `Z_<ordinal>` names but leaves this spelling unchanged. Compare the source and candidate relationship by logical identity and keep the declared-type and cell-value checks. The failures establish that the upgrade is rejected, not that token balances were deleted.
In `packages/rs-platform-wallet-storage/src/sqlite/migrations/v023.rs`:
- [BLOCKING] packages/rs-platform-wallet-storage/src/sqlite/migrations/v023.rs:35-53: Preserve spend guards, used scripts, and labels across the V023 rescan
The migration runner calls `v023::rescan` after creating the indexes. For a wallet outside the InstantSend-preserved set, the spent-row exception does not protect a coin with a mined spender, and the subsequent statements can remove the spender or clear its `record_blob`. Rewinding the cursor does not guard the interval in which catch-up redelivers the funding but not yet the spend. SQLite also derives part of its used-address set from `core_utxos`, and block data cannot reconstruct a local label from a deleted blob. Preserve each guard until replacement evidence is durable, and preserve used scripts and local metadata independently of the projection being rebuilt.
In `packages/rs-platform-wallet-storage/src/sqlite/persister.rs`:
- [BLOCKING] packages/rs-platform-wallet-storage/src/sqlite/persister.rs:1517-1531: Keep SQLite discovery and inspection separate from fenced history repair
`load()` still enters whole-store repair with empty `ReplayEvidence`. Registration uses it to read durable cursors, and drain status uses it to inspect an operation. On the default strict path, those reads can commit changes to a live wallet outside the manager's publication fence, or fail because an unrelated wallet needs verified lock evidence. Startup also collects candidates through `load_wallet_snapshot(...)?` before the recovery-aware discovery can isolate an unreadable sibling, and a successful per-wallet reread replaces the discovery degradation report. Route inspection and candidate collection through policy-aware read-only paths; keep committing repair under the admitted wallet's fence and preserve the aggregate degradation report.
In `packages/rs-platform-wallet/src/manager/history_repair.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_repair.rs:156-171: Retire restored block-spend claims when their block is reorged out
The exception works when both bodies were replayed, but when funding is absent, a reversible block claim becomes `(outpoint, claimant)` with no height. Pinned key-wallet truncates observed spends by height and leaves this claim in place, so it can suppress legitimately unspent funding after a fork. Swift also exports every pending input with `is_held = true`, losing its existing `isSweptTombstone` distinction. The same restore call at lines 105–106 ignores the opposite inconsistency: key-wallet returns any claimed outpoint still materialized as a UTXO and explicitly leaves that coin selectable. Preserve observation versus tombstone provenance, use height-aware restoration for reversible spends (upstream API tracked in dashpay/rust-dashcore#1435), and reconcile or reject a materialized coin that an authoritative surviving hold says is spent.
In `packages/rs-platform-wallet/src/manager/history_replay.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_replay.rs:194-214: Preserve InstantSend finality when decoding FFI history rows
`prepared_history` retains the marker for an uncontested recovery, but the planner receives the other copy with that marker removed. A stored ordinary-block rival can therefore defeat the status-only InstantSend row as if it were an ordinary mempool spend. The first pass rewinds in memory, then atomic repair can delete the defeated row and its change; the reread replaces that state and no longer has the marker that requested catch-up. Keep unresolved finality visible to the settlement decision and defer destructive repair until the conflict is resolved. Cover the contested row through repair and reopen, not just the initial rewind.
In `packages/rs-platform-wallet/src/wallet/asset_lock/sync/recovery.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/asset_lock/sync/recovery.rs:602-618: Carry chain-final funding evidence through conflict planning
Withholding removes the funding body before replay, but it neither reconciles the proof requirements nor gives settlement the funding's inputs. For a chain-final tracked lock with a stale FFI InstantSend row and no sidecar, the required txid remains after its body is removed. Legacy recovery and proof binding both iterate surviving bodies, so the orphan requirement blocks every retry. Without that marker, the opposite failure occurs: the load test explicitly expects both mutually exclusive change outputs to survive for `ChainFinal` versus `Unconfirmed` or `PlainBlock`. Carry the tracked finality and input set into the verdict without inventing a `BlockInfo`; reconcile any superseded InstantSend requirement and refuse a contradictory projection if it cannot be settled.
_Raised on code unchanged since the last review, and confirmed by an independent pass: A SwiftData wallet with a chain-final tracked asset lock and a stale InstantSend transaction row for its funding, but no InstantLock sidecar, fails every restore retry with MissingFinalityEvidence. If the snapshot instead has no InstantSend marker but retains change from both that funding and a competing spend of the same input, replay can count both outputs in the restored balance._
In `packages/rs-platform-wallet-ffi/src/persistence.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/persistence.rs:2915-2927: Preserve existing mobile capability contracts when negotiating history repair
The base grants `WALLET_RESTORE` with the list callback pair. This change requires all four replay callbacks too; JNI leaves those slots unset, so Kotlin's declared bit is stripped and `INVITATION_CREATION` fails preflight even on a fresh wallet. The same mask also stops granting `ASSET_LOCK_OPERATION_IDS` altogether. Swift declares it and wires both UUID callbacks, but `WALLET_DRAIN` requires the effective bit and now fails even without a history conflict. Keep the existing restore contract separate from atomic history repair. For drain, preserve the operation ID or terminal tombstone when replay deletes the tracked row, then attest the bit for hosts that satisfy that durability contract; restoring the bit alone does not fix it.
- [BLOCKING] packages/rs-platform-wallet-ffi/src/persistence.rs:6461-6493: Do not turn unreadable confirmed history into missing spend evidence
(carried; thread: https://github.com/dashpay/platform/pull/5220#discussion_r4389526583)
In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/SwiftExampleAppApp.swift`:
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/SwiftExampleAppApp.swift:465-469: Let bootstrap Retry restart SPV when the first start failed
The auto-start path sets `didAutoStartCoreSpv` before awaiting `CoreSpvLauncher.start` and leaves it set on error. When a wallet needs verified lock evidence, the post-start load throws if the verifier never started. Retry reuses the SDK and manager, and the auto-start decision exits on the latch before checking whether SPV is running. A transient native-start failure therefore becomes a persistent restore failure on this screen. Let explicit Retry start a stopped client without restarting one that is already running and waiting for quorum data.
_Raised on code unchanged since the last review, and confirmed by an independent pass: If the first native SPV start fails before publishing a client—for example, because its storage directory is temporarily locked—a wallet with a stored InstantLock that needs verification falls into the initialization error screen. Tapping Retry still cannot restore it after the directory lock is released, because Retry never starts SPV again._
In `packages/rs-platform-wallet/src/manager/history_authorization.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_authorization.rs:84-89: Keep indeterminate pending authorization from disabling wallet startup
The pinned verifier distinguishes invalid ownership (`Ok(false)`) from authorization its P2PKH/SIGHASH_ALL contract cannot decide. Its `UnsupportedSighash` and `UnsupportedScriptSig` branches can follow verification of a genuine owner signature. The `?` aborts all replay rather than isolating the unresolved record, and the manager cannot register the wallet for catch-up that could resolve it. Keep verification in key-wallet, but represent indeterminate evidence separately: preserve existing protection for its inputs, exclude the record from resend and destructive repair, and give the wallet an actionable recovery path.
_Raised on code unchanged since the last review, and confirmed by an independent pass: A caller can submit a wallet-owned P2PKH spend signed with SIGHASH_ALL|ANYONECANPAY through CoreWallet::broadcast_transaction and have SPV persist it while it is still pending. On restart, that single row aborts restore before the wallet is registered for the catch-up scan that could update its context._
In `packages/rs-platform-wallet/src/manager/load.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/load.rs:214-219: Use only the fenced reread's platform-address state
`extend` replaces the discovered address entry only if the admitted reread supplies one. FFI legitimately returns `None` when the wallet has no platform accounts and all platform watermarks are zero. If the durable wallet changes from populated to empty under the same ID between discovery and the fence, the manager takes the new wallet but passes the old balances and sync cursor to `initialize_from_persisted` instead of initializing fresh. Replace the optional entry, including when it is absent, and test a populated discovery result followed by a present wallet with no address state.
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:
- [BLOCKING] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:5465-5473: Do not abort history restoration when a legacy handler has no resolved network
(carried; thread: https://github.com/dashpay/platform/pull/5220#discussion_r4603783729)
- [BLOCKING] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:7890-7904: Bound the attacker-amplifiable full-history replay during wallet load
(carried; thread: https://github.com/dashpay/platform/pull/5220#discussion_r4265416171)
In `packages/rs-platform-wallet/src/manager/history_claims.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/manager/history_claims.rs:329-347: Persist replay-created irreversible spend claims for surviving unbacked spends
(carried; thread: https://github.com/dashpay/platform/pull/5220#discussion_r4603783705)
Out-of-scope follow-up suggestions (1)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Fix the stale accounting write in the accounting stack — The backfill can overwrite a newer live display-accounting row after releasing the manager read lock. The same lock scope, FFI callback, and Swift upsert are present in the open owning PR #5417 at
f0e4ac34506; replay does not depend on this write to reconstruct spend state.- Follow-up: Address in #5417 with insert-if-still-unaccounted semantics and a live-write-before-backfill regression.
| func testV5AddsPerWalletTransactionAccountingAndCoreInstantLocksToV4() { | ||
| XCTAssertEqual( | ||
| Set(Schema(versionedSchema: DashSchemaV5.self).entities.map(\.name)) | ||
| .subtracting(Schema(versionedSchema: DashSchemaV4.self).entities.map(\.name)), | ||
| ["PersistentTransactionAccounting", "PersistentCoreInstantLock"]) |
There was a problem hiding this comment.
🔴 Blocking: Make the expanded V5 schema pass both upgrade and preservation checks
Swift SDK job 136842494784 reports five V5 additions, not two: the expected set omits PersistentPrivateContactRequestsPosition, PersistentPrivateShieldedAddress, and PersistentLockedOutpoint. The same job rejects both the accepted-V1 and historical-V2 fixture upgrades at DashLegacyStoreSQLite.swift:221 with “Migration removed or converted a column in ZPERSISTENTTOKENBALANCE.” Both source fixtures contain the integer relationship column Z13TOKENBALANCES, with ordinal 13 mapped to PersistentIdentity; normalize handles Z_<ordinal> names but leaves this spelling unchanged. Compare the source and candidate relationship by logical identity and keep the declared-type and cell-value checks. The failures establish that the upgrade is rejected, not that token balances were deleted.
source: gpt-6.2-astra (phase2-reviewer: general, rust-quality)
| tx.execute_batch( | ||
| "DELETE FROM core_utxos WHERE wallet_id NOT IN (SELECT wallet_id FROM core_rescan_preserved_wallets) AND NOT ( | ||
| EXISTS (SELECT 1 FROM core_transactions t WHERE t.wallet_id = core_utxos.wallet_id | ||
| AND t.txid = substr(core_utxos.outpoint, 2, 32) AND t.height IS NULL) | ||
| OR (spent = 1 AND winner_mined_height IS NULL AND NOT EXISTS ( | ||
| SELECT 1 FROM core_transactions t WHERE t.wallet_id = core_utxos.wallet_id | ||
| AND t.txid = core_utxos.spent_in_txid AND t.height IS NOT NULL)) | ||
| ); | ||
| DELETE FROM core_instant_locks WHERE wallet_id NOT IN (SELECT wallet_id FROM core_rescan_preserved_wallets) | ||
| AND NOT EXISTS (SELECT 1 FROM core_transactions t WHERE t.wallet_id = core_instant_locks.wallet_id | ||
| AND t.txid = core_instant_locks.txid AND t.height IS NULL); | ||
| DELETE FROM core_transaction_inputs WHERE wallet_id NOT IN (SELECT wallet_id FROM core_rescan_preserved_wallets) | ||
| AND EXISTS (SELECT 1 FROM core_transactions t WHERE t.wallet_id = core_transaction_inputs.wallet_id | ||
| AND t.txid = core_transaction_inputs.txid AND t.height IS NOT NULL); | ||
| DELETE FROM core_transactions WHERE wallet_id NOT IN (SELECT wallet_id FROM core_rescan_preserved_wallets) | ||
| AND height IS NOT NULL AND NOT EXISTS (SELECT 1 FROM core_utxos u | ||
| WHERE u.wallet_id = core_transactions.wallet_id AND substr(u.outpoint, 2, 32) = core_transactions.txid); | ||
| UPDATE core_transactions SET block_hash = NULL, block_time = NULL, finalized = 0, record_blob = NULL | ||
| WHERE wallet_id NOT IN (SELECT wallet_id FROM core_rescan_preserved_wallets) AND height IS NOT NULL; |
There was a problem hiding this comment.
🔴 Blocking: Preserve spend guards, used scripts, and labels across the V023 rescan
The migration runner calls v023::rescan after creating the indexes. For a wallet outside the InstantSend-preserved set, the spent-row exception does not protect a coin with a mined spender, and the subsequent statements can remove the spender or clear its record_blob. Rewinding the cursor does not guard the interval in which catch-up redelivers the funding but not yet the spend. SQLite also derives part of its used-address set from core_utxos, and block data cannot reconstruct a local label from a deleted blob. Preserve each guard until replacement evidence is durable, and preserve used scripts and local metadata independently of the projection being rebuilt.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality)
| fn load(&self) -> Result<ClientStartState, PersistenceError> { | ||
| self.load_with_replay(&ReplayEvidence::default()) | ||
| .map(|loaded| loaded.state) | ||
| } | ||
|
|
||
| fn replay_lock_candidates(&self) -> Result<Vec<dashcore::InstantLock>, PersistenceError> { | ||
| let conn = self.conn().map_err(PersistenceError::from)?; | ||
| let ctx = LoadCtx::new(self.config.load_policy); | ||
| let mut candidates = Vec::new(); | ||
| for wallet_id in schema::wallets::list_ids(&conn).map_err(PersistenceError::from)? { | ||
| let state = load_wallet_snapshot(&conn, wallet_id, &ctx)?; | ||
| candidates.extend( | ||
| platform_wallet::changeset::recorded_history::replay_lock_candidates(&state), | ||
| ); | ||
| } |
There was a problem hiding this comment.
🔴 Blocking: Keep SQLite discovery and inspection separate from fenced history repair
load() still enters whole-store repair with empty ReplayEvidence. Registration uses it to read durable cursors, and drain status uses it to inspect an operation. On the default strict path, those reads can commit changes to a live wallet outside the manager's publication fence, or fail because an unrelated wallet needs verified lock evidence. Startup also collects candidates through load_wallet_snapshot(...)? before the recovery-aware discovery can isolate an unreadable sibling, and a successful per-wallet reread replaces the discovery degradation report. Route inspection and candidate collection through policy-aware read-only paths; keep committing repair under the admitted wallet's fence and preserve the aggregate degradation report.
source: gpt-6.2-astra (phase2-reviewer: general, ffi-engineer, platform-versioning, rust-quality)
| // TODO(restore-observed-spends): a claim on a coin whose funding the history | ||
| // lacks stays a claim even when its spend is reversible, which no fork | ||
| // releases; making it an observed spend that survives finality needs an | ||
| // upstream API such as `ManagedWalletInfo::restore_observed_spends`. | ||
| claims | ||
| .iter() | ||
| .filter(|claim| { | ||
| let released_by_fork = funded.contains(&claim.outpoint.txid) | ||
| && claim.claimant.is_some_and(|id| reversible.contains(&id)) | ||
| && !claim | ||
| .mined_height | ||
| .is_some_and(|height| chain_locked.is_some_and(|locked| height <= locked)); | ||
| !released_by_fork | ||
| }) | ||
| .map(|claim| (claim.outpoint, claim.claimant)) | ||
| .collect() |
There was a problem hiding this comment.
🔴 Blocking: Retire restored block-spend claims when their block is reorged out
The exception works when both bodies were replayed, but when funding is absent, a reversible block claim becomes (outpoint, claimant) with no height. Pinned key-wallet truncates observed spends by height and leaves this claim in place, so it can suppress legitimately unspent funding after a fork. Swift also exports every pending input with is_held = true, losing its existing isSweptTombstone distinction. The same restore call at lines 105–106 ignores the opposite inconsistency: key-wallet returns any claimed outpoint still materialized as a UTXO and explicitly leaves that coin selectable. Preserve observation versus tombstone provenance, use height-aware restoration for reversible spends (upstream API tracked in dashpay/rust-dashcore#1435), and reconcile or reject a materialized coin that an authoritative surviving hold says is spent.
source: gpt-6.2-astra (phase2-reviewer: general, ffi-engineer, platform-versioning, rust-quality)
| // Status-only legacy observations have nothing the verifier can retry. | ||
| // Keep the stored marker in prepared_history so every load recomputes recovery. | ||
| let legacy: BTreeSet<_> = history | ||
| .transactions | ||
| .iter() | ||
| .filter(|row| { | ||
| history.required_instant_locks.contains(&row.txid) | ||
| && matches!(row.context, TransactionContext::Mempool) | ||
| && !history.instant_locks.contains_key(&row.txid) | ||
| && !evidence.instant_locks.contains_key(&row.txid) | ||
| && !state | ||
| .unused_asset_locks | ||
| .values() | ||
| .flat_map(BTreeMap::values) | ||
| .any(|lock| lock.transaction.txid() == row.txid && lock.proof.is_some()) | ||
| }) | ||
| .map(|row| row.txid) | ||
| .collect(); | ||
| history | ||
| .required_instant_locks | ||
| .retain(|txid| !legacy.contains(txid)); |
There was a problem hiding this comment.
🔴 Blocking: Preserve InstantSend finality when decoding FFI history rows
prepared_history retains the marker for an uncontested recovery, but the planner receives the other copy with that marker removed. A stored ordinary-block rival can therefore defeat the status-only InstantSend row as if it were an ordinary mempool spend. The first pass rewinds in memory, then atomic repair can delete the defeated row and its change; the reread replaces that state and no longer has the marker that requested catch-up. Keep unresolved finality visible to the settlement decision and defer destructive repair until the conflict is resolved. Cover the contested row through repair and reopen, not just the initial rewind.
source: gpt-6.2-astra (phase2-reviewer: general, security-auditor)
| // A funding the history places in a block, or settles with a lock the | ||
| // replay accepts, replays like any other record. | ||
| let locked = &history.instant_locks; | ||
| for stored in &history.transactions { | ||
| if withheld.contains(&stored.txid) | ||
| && (!matches!(stored.context, TransactionContext::Mempool) | ||
| || locked | ||
| .get(&stored.txid) | ||
| .is_some_and(|lock| lock_matches_record(lock, stored))) | ||
| { | ||
| withheld.remove(&stored.txid); | ||
| } | ||
| } | ||
| history | ||
| .transactions | ||
| .retain(|stored| !withheld.contains(&stored.txid)); | ||
| withheld |
There was a problem hiding this comment.
🔴 Blocking: Carry chain-final funding evidence through conflict planning
Withholding removes the funding body before replay, but it neither reconciles the proof requirements nor gives settlement the funding's inputs. For a chain-final tracked lock with a stale FFI InstantSend row and no sidecar, the required txid remains after its body is removed. Legacy recovery and proof binding both iterate surviving bodies, so the orphan requirement blocks every retry. Without that marker, the opposite failure occurs: the load test explicitly expects both mutually exclusive change outputs to survive for ChainFinal versus Unconfirmed or PlainBlock. Carry the tracked finality and input set into the verdict without inventing a BlockInfo; reconcile any superseded InstantSend requirement and refuse a contradictory projection if it cannot be settled.
Raised on code unchanged since the last review, and confirmed by an independent pass: A SwiftData wallet with a chain-final tracked asset lock and a stale InstantSend transaction row for its funding, but no InstantLock sidecar, fails every restore retry with MissingFinalityEvidence. If the snapshot instead has no InstantSend marker but retains change from both that funding and a competing spend of the same input, replay can count both outputs in the restored balance.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
| if wallet_restore { | ||
| // History rides the same wallet-list load; a host that wires it | ||
| // must still declare the bit to attest it fills the rows. | ||
| capabilities = capabilities.union(PersistenceCapabilities::CORE_HISTORY_RESTORE); | ||
| if self.replay_callbacks.complete() { | ||
| capabilities = capabilities.union(PersistenceCapabilities::WALLET_RESTORE); | ||
| } | ||
| } | ||
| if self.callbacks.on_persist_asset_locks_fn.is_some() { | ||
| capabilities = capabilities.union(PersistenceCapabilities::TRACKED_ASSET_LOCKS); | ||
| } | ||
| // Replay cleanup has no durable operation tombstones yet; UUID callbacks | ||
| // alone cannot attest ASSET_LOCK_OPERATION_IDS after conflicting history is removed. |
There was a problem hiding this comment.
🔴 Blocking: Preserve existing mobile capability contracts when negotiating history repair
The base grants WALLET_RESTORE with the list callback pair. This change requires all four replay callbacks too; JNI leaves those slots unset, so Kotlin's declared bit is stripped and INVITATION_CREATION fails preflight even on a fresh wallet. The same mask also stops granting ASSET_LOCK_OPERATION_IDS altogether. Swift declares it and wires both UUID callbacks, but WALLET_DRAIN requires the effective bit and now fails even without a history conflict. Keep the existing restore contract separate from atomic history repair. For drain, preserve the operation ID or terminal tombstone when replay deletes the tracked row, then attest the bit for hosts that satisfy that durability contract; restoring the bit alone does not fix it.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
| await autoStartCoreSpvIfNeeded() | ||
| if platformState.sdk != nil { | ||
| // Starting SPV opens its cache but does not guarantee quorum readiness. | ||
| // A load error leaves SPV running and the existing Retry action can try again. | ||
| _ = try await walletManager.loadFromPersistor() |
There was a problem hiding this comment.
🔴 Blocking: Let bootstrap Retry restart SPV when the first start failed
The auto-start path sets didAutoStartCoreSpv before awaiting CoreSpvLauncher.start and leaves it set on error. When a wallet needs verified lock evidence, the post-start load throws if the verifier never started. Retry reuses the SDK and manager, and the auto-start decision exits on the latch before checking whether SPV is running. A transient native-start failure therefore becomes a persistent restore failure on this screen. Let explicit Retry start a stopped client without restarting one that is already running and waiting for quorum data.
Raised on code unchanged since the last review, and confirmed by an independent pass: If the first native SPV start fails before publishing a client—for example, because its storage directory is temporarily locked—a wallet with a stored InstantLock that needs verification falls into the initialization error screen. Tapping Retry still cannot restore it after the directory lock is released, because Retry never starts SPV again.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
| continue; | ||
| }; | ||
| if !verify_input_authorization(&record.transaction, index, prevout)? { | ||
| result.invalid_owner.insert(*txid); | ||
| } | ||
| } |
There was a problem hiding this comment.
🔴 Blocking: Keep indeterminate pending authorization from disabling wallet startup
The pinned verifier distinguishes invalid ownership (Ok(false)) from authorization its P2PKH/SIGHASH_ALL contract cannot decide. Its UnsupportedSighash and UnsupportedScriptSig branches can follow verification of a genuine owner signature. The ? aborts all replay rather than isolating the unresolved record, and the manager cannot register the wallet for catch-up that could resolve it. Keep verification in key-wallet, but represent indeterminate evidence separately: preserve existing protection for its inputs, exclude the record from resend and destructive repair, and give the wallet an actionable recovery path.
Raised on code unchanged since the last review, and confirmed by an independent pass: A caller can submit a wallet-owned P2PKH spend signed with SIGHASH_ALL|ANYONECANPAY through CoreWallet::broadcast_transaction and have SPV persist it while it is still pending. On restart, that single row aborts restore before the wallet is registered for the catch-up scan that could update its context.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
| Ok((mut loaded, cursors)) => { | ||
| outcomes.extend(loaded.outcomes); | ||
| platform_addresses.extend(loaded.state.platform_addresses); | ||
| if let Some(state) = loaded.state.wallets.remove(&expected_wallet_id) { | ||
| pending.push_front((expected_wallet_id, state, true)); | ||
| held = Some(cursors); |
There was a problem hiding this comment.
🔴 Blocking: Use only the fenced reread's platform-address state
extend replaces the discovered address entry only if the admitted reread supplies one. FFI legitimately returns None when the wallet has no platform accounts and all platform watermarks are zero. If the durable wallet changes from populated to empty under the same ID between discovery and the fence, the manager takes the new wallet but passes the old balances and sync cursor to initialize_from_persisted instead of initializing fresh. Replace the optional entry, including when it is absent, and test a populated discovery result followed by a present wallet with no address state.
| Ok((mut loaded, cursors)) => { | |
| outcomes.extend(loaded.outcomes); | |
| platform_addresses.extend(loaded.state.platform_addresses); | |
| if let Some(state) = loaded.state.wallets.remove(&expected_wallet_id) { | |
| pending.push_front((expected_wallet_id, state, true)); | |
| held = Some(cursors); | |
| Ok((mut loaded, cursors)) => { | |
| outcomes.extend(loaded.outcomes); | |
| platform_addresses.remove(&expected_wallet_id); | |
| platform_addresses.extend(loaded.state.platform_addresses); | |
| if let Some(state) = loaded.state.wallets.remove(&expected_wallet_id) { | |
| pending.push_front((expected_wallet_id, state, true)); | |
| held = Some(cursors); |
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
bf1948c to
0f2dee9
Compare
0f2dee9 to
6d2dcac
Compare
…r every persister Preserve the final PR scope, including merge resolutions, on the updated native stack. Co-Authored-By: Codex <[email protected]>
6d2dcac to
ef29b2b
Compare
Restores stored Core transaction history through the shared wallet load path so that rediscovered funding cannot make already-spent outputs available again.
Issue being fixed or feature implemented
Targets
v5.2-dev, which includes #5150. The branch also carries the still-open #5781, #5783 and #5417, which it is stacked on. Addresses the #5150 review thread "Confirmed-history replay is implemented only for SQLite".Depends on unmerged rust-dashcore work. Every rust-dashcore crate is pinned to the integration branch
integration/platform-5220(ffcff0ab), which merges dashpay/rust-dashcore#1336, dashpay/rust-dashcore#1416 and rust-dashcoredev. The branch also carries #5951 (Platform on rust-dashcoredev). Before merge: land #1336 and #1416, land #5951, then move the pin to a rust-dashcoredevrevision that contains both.After a restart the wallet must know which outputs its confirmed transactions already spent (
spent_outpoints/observed_spent_outpoints). Without that, a redelivered funding transaction (rescan, gap-limit rediscovery) credits an already-spent output again. Onv5.2-devonly the SQLite persister rebuilds this state, inside its own load. The FFI persister (iOS / SwiftData) replays only unconfirmed outgoing sends, so confirmed spends are never replayed on that path.What was done?
Where the replay runs
rs-platform-wallet(manager/history_replay.rs,replay_recorded_history). Every persister hands its stored records back throughClientWalletStartState::recorded_history(RecordedHistory { required_instant_locks, owned_prevouts, transactions, instant_locks }, types inchangeset/recorded_history.rs).load_from_persistorfirst collects the InstantSend locks the stored history relies on (replay_lock_candidates) and verifies them with the running SPV client. It then loads each wallet throughPlatformWalletPersistence::load_wallet_with_replay, which runs the replay before the balance is mirrored into the wallet.load_wallet_with_replayruns the replay inside its own storage transaction and writes the effects (removed losing records and evidence, spend claims) before it commits. The repair lives once in the wallet:repair_wallet_history(manager::history_repair) reads the snapshot and the stored claims, replays, writes the effects, re-reads and replays again to confirm the history settled (HistoryReplayError::UnsettledAfterReplayotherwise), and restores the claims. A backend implementsHistoryRepairStoreand only supplies snapshot, claim and effect access inside its transaction. A backend that does not override it gets the replay in memory, and a history that needs durable repair fails the load (HistoryReplayError::AtomicPersistenceRequired). History that needs InstantSend evidence the SPV client cannot verify yet fails the load (MissingFinalityEvidence); the caller retries after SPV synchronizes.sqlite/history_replay.rs. It declaresCORE_HISTORY_RESTORE. Migration V023 (V023__core_history_rescan) adds twocore_utxosindexes, by funding transaction and by claimant.sqlite/rehydrate.rsdoes not replay stored InstantSend lock rows onto restored coins; only the shared replay upgrades a coin, on verified evidence.loadWalletListfetches the stored history once and hands each restorable wallet its own records. InstantLock bytes are kept inPersistentCoreInstantLock, part of the unreleased V5 SwiftData schema. The fetch prefetches the relationships used to determine wallet ownership. A fetch error rejects the snapshot rather than claiming the wallet has no history.CORE_HISTORY_RESTORE(bit 17; bit 15 belongs to the private contact request scan state, bit 16 toOUTPOINT_LOCKS). SQLite and Swift declare it; the FFI attests it only when the wallet-list load callbacks are wired. It gates nothing:load_from_persistorlogs a warning when a persister restores wallets without it.What the replay does
irreversible_spend_claims), so a funding delivered later is not credited again. A spend in a plain block or in the mempool is not claimed, because nothing retires a claim when a fork or an eviction drops its claimant.replay_recorded_historyreturnsHistoryReplay { replayed, retired, defeated }.retiredholds every stored transaction the replay removed or left out;defeatedholds only those a stored conflict winner beat, with their descendants. An unconfirmed send the replay retired is dropped from the list re-dispatched at load (HistoryReplay::resendable).Amounts the checker cannot take
unsafe_replay_amountschecks its operands: restored coins, outputs including asset-lock credit outputs, and recorded owned inputs, each alone and summed. A failing unconfirmed record is left out of the replay and the load continues. No valid transaction carries such amounts, so a mined record that survives conflict settlement is store corruption and fails the load (HistoryReplayError::UnsafeMinedAmounts). The record still takes part in conflict settlement: a stored final winner removes it during planning, and one delivered after the load removes it and releases the input the winner does not spend.UnsafeAmounts).Outputsmeans the recorded transaction bodies prove the overflow on their own, so the transaction can never confirm.Storedmeans the overflow depends on a value stored beside the transaction (a restored coin or a recorded owned input), so the transaction itself may be valid. AStoredrecord can win a conflict; anOutputsrecord can only lose one.reservation_claimant). AmongOutputsrecords the smallest txid stands for all. A singleStoredrecord is named, so the coin stays guarded while that record stands. TwoStoredrecords leave no claimant whose removal proves the coin free.Tracked asset locks
recorded_input_conflicts), so that knowledge survives chain-lock finalization. The pending locks' inputs are indexed by outpoint once.InstantSendLocked,ChainLocked,ConsumedorRecoveredFromChain(final_lock_input_claims). A host may drop those inputs from the projection on the lock's status alone while the funding's own record guards nothing.Known limitations:
TODO(ffi-recorded-input-details)) or provisional evidence promoted at finality; tracked in platform-wallet: a spent coin can return as spendable within a session on FFI hosts (recorded history carries no owned inputs) #5412.StoredTransaction::owned_inputs: a store that drops the coin of an unconfirmed spend from the load projection must record that spend's owned inputs. The replay guards an unconfirmed spend through a restored coin or its recorded owned-input details.Storedrecords stays claimed until the next load, even once both records are swept.Outputsrecords is held for the one with the smaller txid. Sweeping that record alone drops the guard while the other still names the coin; neither record can ever confirm, so no funds are at risk.MissingFinalityEvidenceand needs an explicit retry.TODO(restore-observed-spends), key-wallet: restored spends cannot follow a fork of their block (restore observed spends with height) rust-dashcore#1435). The same applies to the inputs of a legacy InstantSend row whose funding is not in the history.i64::MAXstays in the projection and the balance; only records spending it are left out.TODO(bound-load-history-replay): every stored record is replayed on each load.TODO(expire-unconfirmed-spend-reservations): stored mempool records, incoming ones included on the FFI path, are replayed with no expiry.Out of scope:
key-wallet/dash-spv; only the load replay and the wallet's own re-dispatch are covered here.TODO(android-core-history-restore)).How Has This Been Tested?
Latest local runs on this branch:
platform-wallet(withshielded),platform-wallet-ffiandplatform-wallet-storagewith--all-targets -- -D warnings: clean.sqlite_identity_key_restore) come from a local temp directory without the sticky bit (InsecureParentDir), not from this change.should_reserve_absent_inputs_of_unsafe_stored_record_until_sweptfailed before the fix and covers absent funding, redelivery protection and release after confirmed conflict.What the main tests cover:
should_sweep_conflicting_spend_for_either_sibling_replay_order(block, chain-lock and persisted-chain-lock winners),should_drop_attributable_descendant_of_swept_conflict_for_any_replay_order,should_remove_cross_account_descendant_of_conflicting_spend, andshould_plan_the_same_removals_as_whole_history_sweeps, which compares the planner with whole-history sweeps on 500 generated histories.should_rebuild_spent_mark_for_height_only_funding_from_owned_inputs,should_guard_unreplayed_funding_against_irreversible_spends_only,should_credit_funding_again_after_a_fork_drops_the_restored_spend,should_keep_unsafe_amounts_from_the_checker_and_reserve_the_coins_they_spend,should_hold_shared_coin_while_a_record_that_may_confirm_spends_it,should_release_coin_shared_by_spends_of_impossible_recorded_amounts,should_let_instant_locked_record_with_unsafe_stored_amounts_sweep_its_competitor.should_settle_stored_conflicts_by_what_a_tracked_lock_provesasserts the rule as a table: lock evidence (Instant proof, chain-final status) against competitor (unconfirmed, plain block, chain-locked), checking the funding's change, the competitor's change and whether the funding's other input stays guarded; two more rows cover a history lock that names another transaction, and a funding with two credit outputs at mixed statuses whose record the host attached. Around it:should_not_credit_inputs_of_a_final_asset_lock_again,should_not_claim_inputs_of_a_tracked_funding_the_replay_defeated,should_keep_the_claim_of_a_final_lock_whose_funding_was_only_left_out,should_remember_stored_spender_of_pending_asset_lock_input_on_load.should_settle_an_attached_unconfirmed_record_the_history_does_not_holdpins what the replay does with an attached unconfirmed record, which is why the load detaches it;should_detach_unconfirmed_records_of_withheld_fundings_and_put_them_backcovers the detaching.Also covered: normal and overlapping FFI restore, malformed and trailing transaction bytes, proof-record and metadata retention, funding redelivery, and re-dispatch of retired sends. Each regression test was seen failing before its fix.
Not run:
swiftnorxcodebuild. The Swift changes were read, not run.Breaking Changes
WalletRestoreEntryFFIgains two trailing fields (recorded_transactions,recorded_transactions_count), plus the new element structRecordedTransactionRestoreFFI. The entry has no size field, so the host and the Rust library must be built together (same contract asunconfirmed_outgoing_tx_records).ClientWalletStartStategains the public fieldrecorded_history. Struct-literal constructors must set it;Default::default()gives the previous behaviour.CORE_HISTORY_RESTORE(bit 17) is additive.PersistenceCallbacksExtensiongains the replay and InstantLock slots listed above. They are trailing and size-negotiated; Rust struct literals must set them,..Default::default()leaves them unset.PlatformWalletPersistencegainsload_read_snapshot,load_with_replay,load_wallet_with_replayandreplay_lock_candidates, all with defaults.manager::history_replay(additive):replay_recorded_history,replay_wallet_history,HistoryReplay,HistoryReplayLoad,HistoryReplayError,unsafe_replay_amounts,UnsafeAmounts,ReplayOperands, and the repair ownerrepair_wallet_history,HistoryRepairStoreandHistoryRepairError.Checklist:
structure.rs, regeneratedgrovedb-structure.json, and checked the structure viewer link posted on this pull requestFor repository code-owners and collaborators only
🤖 Co-authored by Claudius the Magnificent AI Agent