Registry Mirror
Skip to content

Conversation

@lklimek

@lklimek lklimek commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Basic explanation

What this does: A wallet remembers an interrupted drain operation and its intended shielded recipient when the funding transaction loses a conflict. Restarting or retrying preserves the original funding output and recipient.

Value: A conflicted funding output stays non-actionable. It can resume after authenticated recovery of that same output, paying the recorded recipient and refusing a different address.

Risks: This changes local wallet persistence and host bindings. SwiftData migration/restart and Swift runtime validation require macOS CI.

Issue being fixed or feature implemented

Stacked on #5210 (feat/sqlite-wallet-restore). Funding-conflict cleanup discarded the metadata needed to distinguish an interrupted operation from a new one. It could also discard a shielded recipient even when the lock had no operation UUID. This addresses T3 from #5210's merge TODO.

What was done?

  • Retain operation bindings and shielded recipients as Conflicted, clear actionable proofs, and reactivate only after authenticated recovery of the original funding output. Mempool sightings leave the conflict intact.
  • Use revisions and compare-and-set persistence to reject stale snapshots/removals while accepting exact retries. Rust owns recipient inheritance, immutability and removal decisions; SQLite and SwiftData use that policy.
  • Preserve recipients through changeset folding, restored wallet state, SQLite reopen and FFI callbacks, including locks without UUIDs. Known-unsent Built rows remain removable.
  • SQLite V023 follows V020 recipient storage, V021 Core accounting and V022 locked outpoints. It adds conflict/revision storage while preserving lifecycle bytes and the recipient column/trigger. SQLite supports durable operation recovery and wallet draining.
  • Add revision-aware callbacks through the size-negotiated FFI extension. The operation carrier introduced by this PR includes the recipient; its removal predicate accepts recipient presence. Rust and Swift bindings must be built together.
  • Keep Swift's operation revision in the unreleased schema V5. Legacy hosts without recovery sidecars keep their existing storage format, with recipient protection retained in memory. Ordered UUID-only hosts keep their existing contract; incomplete recipient/revision callback configurations fail closed.

How Has This Been Tested?

  • Confirmed failing regressions before each fix: recipient loss in wallet/SQLite, and rollback of a Core sweep round on a legacy FFI host.
  • 33 focused Rust tests passed: wallet 6, FFI 8, SQLite 19. Coverage includes both finality-return paths, stale writes/removals, first-delivery and repeated CAS with omitted recipient, file-backed SQLite reopen, and legacy/partial/UUID-only/full FFI hosts.
  • The public Type18 funding test restores wallet state, refuses conflicted funding, rejects another recipient with unchanged live/persisted state, and lets the recorded recipient reach the fixture's next local key-path check.
  • Clippy passes for platform-wallet, platform-wallet-storage and platform-wallet-ffi with CI flags (--locked --all-targets --all-features -- --no-deps -D warnings). Rust formatting and diff checks pass.
  • 28 schema tests passed. Generated headers pass a Clang C11 check covering the recipient array and removal predicate.
  • Added a file-backed SwiftData close/reopen regression. XCTest execution requires macOS/Xcode; CI was dispatched for this draft.

Breaking Changes

Rust asset-lock structs gain revision fields and enums gain Conflicted. The new operation carrier and removal predicate require corresponding Rust/Swift bindings. Existing legacy asset-lock rows use their existing layout. Hosts need ordered persistence callbacks for durable operation recovery.

Core accounting issue dashpay/rust-dashcore#1213 and general history repair remain outside scope.

🤖 Co-authored by Claudius the Magnificent AI Agent

@coderabbitai

coderabbitai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Share

@lklimek lklimek added this to the v5.1.0 milestone Oct 21, 2026 — with ChatGPT Codex Connector
@thepastaclaw

thepastaclaw commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

🕓 Review not started yet because this PR is a draft.

  • Request normal review — click when the PR is ready for review.
  • Request priority review — click to move this review to the front of the queue.

Commit 6057fa6. Normal review starts when eligible; priority review starts as soon as a slot is available.

@lklimek
lklimek added this pull request to stack #5520 October 21, 2026 23:33

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Final validation — Phase 1 + Phase 2

Verified the supplied findings against head 6e00e2e. Three blocking issues remain: active finality waits ignore funding conflicts, FFI restoration accepts inconsistent operation evidence, and the new revision-aware Swift tests use transaction bytes that Rust rejects. Current CI checks pass, including Kotlin tests and Swift schema coverage, but provide no Swift runtime validation; this verification was static and ran no builds or tests.

🔴 3 blocking | 🟡 4 suggestion(s)

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: critical by gpt-6.1-sol (effort low) — This is a large, intricate change that modifies wallet funds movement and coin-selection behavior through asset-lock funding/drain recovery, while also introducing SQLite and cross-language persistence migrations.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (lane failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — ffi-engineer (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — security-auditor (completed, effort xhigh); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `packages/rs-platform-wallet/src/wallet/asset_lock/sync/reconstruction.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/asset_lock/sync/reconstruction.rs:428-434: Make active proof waits observe the funding conflict
  A sweep now retains this lock as Conflicted, but an already-running proof wait never examines that state. After Platform rejects an InstantSend proof, fund_from_asset_lock.rs calls upgrade_to_chain_lock_proof with the caller's wait policy; the drain FFI passes None. The pinned key-wallet allows a chainlocked winner to sweep an InstantSend-locked loser and removes the losing transaction records. If that happens after wait_for_chain_lock starts, its loop continues checking transaction records and the mined-height locator indefinitely, even after the conflict is durable. The drain consequently retains shield_guard and blocks subsequent shield-class operations. Make the shared proof-wait paths stop on committed conflict evidence, without publishing an uncommitted conflict as a durable outcome, and cover a sweep arriving after the wait has started.

In `packages/rs-platform-wallet-ffi/src/persistence.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/persistence.rs:6345-6350: Validate restored operation evidence in the wallet owner
  The revision loader checks only the upper bound, and the surrounding restore path never validates the relationship between status, revision, and operation ID after reconstructing both sidecars. A successful UUID callback returning found=false followed by a revision callback returning 1 therefore accepts a Conflicted or recovered row with no UUID. Swift's loader permits the same combination, whereas SQLite's decode_row explicitly rejects it. After reopening, wallet_drain_operation_status_inner searches by UUID and misses this evidence, allowing NotSent; begin_wallet_drain also excludes the unbound row from its pending-operation gate and can build replacement funding for the original UUID. Conflicted rows at revision zero are accepted as well. Add a wallet-owned recovery-metadata invariant and invoke it after complete reconstruction in both restore paths. Invalid combinations must fail the entire load rather than become absent operation history.

In `packages/swift-sdk/SwiftTests/SwiftDashSDKTests/AssetLockOperationPersistenceTests.swift`:
- [BLOCKING] packages/swift-sdk/SwiftTests/SwiftDashSDKTests/AssetLockOperationPersistenceTests.swift:34-38: Use Rust-decodable transaction fixtures in the revision-aware Swift tests
  The new revisionAware calls enter asset_lock_operation_persistence_action through withOperationFFI, and Rust consensus-decodes both snapshots through build_unused_asset_locks. The shared snapshot fixture supplies [3, 0, 0, 0, 0, 0, 0, 0, 0, 0]. In the pinned rust-dashcore decoder, its empty input vector selects witness decoding and the following zero produces UnsupportedSegwitFlag(0). The FFI action therefore returns 0 and persistAssetLocks returns false at this assertion and the corresponding assertion in testV4OperationBindingMigratesWithLegacyRevisionAndSurvivesReopen. The stale-snapshot assertion also passes for the wrong reason, before revision acceptance runs. Replace the placeholder with consensus-encoded transaction bytes shared by the predecessor and incoming snapshots; do not weaken the production decoder.

In `packages/rs-platform-wallet-storage/src/sqlite/schema/asset_locks.rs`:
- [SUGGESTION] packages/rs-platform-wallet-storage/src/sqlite/schema/asset_locks.rs:240-253: Share the conflict projection with the wallet's live sweep path
  The replay adapter independently decides whether a swept lock is removed or retained, changes its status to Conflicted, clears its proof, and advances its operation revision. The live remove_tracked_asset_locks_for_swept path implements the same wallet-state decisions separately. They currently agree, but a lifecycle change can update live handling without updating restart repair. Extract a pure swept-lock projection into rs-platform-wallet and call it from both paths, leaving row selection and transactional writes in platform-wallet-storage.
- [SUGGESTION] packages/rs-platform-wallet-storage/src/sqlite/schema/asset_locks.rs:235-240: Filter sweep candidates before decoding lifecycle blobs
  remove_swept now calls load_unconsumed for the whole wallet and only then filters by the swept transaction IDs. That helper reads and decodes every selected lifecycle blob, transaction, and proof, including unrelated locks and UUID-bound terminal tombstones. The previous implementation inspected outpoints before selecting matching losers. On a wallet with substantial retained history, repairing a small sweep therefore performs unnecessary full-history decoding inside the repair transaction. Select candidate outpoints first and decode only matching rows before applying the wallet-owned projection.

In `packages/rs-platform-wallet/src/changeset/changeset.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/changeset/changeset.rs:1625-1632: Compare CAS redeliveries without cloning complete snapshots
  The exact-redelivery branch clones both AssetLockEntry values solely to clear expected_operation_revision before comparing them. Each clone duplicates the transaction and optional proof even though this operation only needs borrowed equality checks. SQLite persistence and the FFI owner check both reach this branch when a committed CAS is redelivered. Use a borrowed comparison helper or borrowed field tuple that excludes the precondition, preserving equality over every other field without allocating two complete snapshots.

In `packages/rs-platform-wallet-ffi/src/asset_lock_operation_persistence.rs`:
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/asset_lock_operation_persistence.rs:89-97: Retain diagnostics for malformed FFI operation snapshots
  Both decode failures discard their PersistenceError and return the same 0 used for an ordinary policy rejection. The host can only report a rejected persistence round, with no diagnostic distinguishing malformed transaction/proof bytes from a stale CAS. Preserve the stable return-code contract, but emit contextual tracing for unexpected incoming or predecessor decoding failures. Keep normal CAS rejection quiet; it is an expected outcome rather than a decoding fault.

Comment on lines +428 to +434
if entry.operation_id.is_some() {
entry.status = AssetLockStatus::Conflicted;
entry.proof = None;
let mut snapshot = AssetLockEntry::from(&*entry);
snapshot.advance_operation_revision();
entry.operation_revision = snapshot.operation_revision;
cs.asset_locks.insert(out_point, snapshot);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔴 Blocking: Make active proof waits observe the funding conflict

A sweep now retains this lock as Conflicted, but an already-running proof wait never examines that state. After Platform rejects an InstantSend proof, fund_from_asset_lock.rs calls upgrade_to_chain_lock_proof with the caller's wait policy; the drain FFI passes None. The pinned key-wallet allows a chainlocked winner to sweep an InstantSend-locked loser and removes the losing transaction records. If that happens after wait_for_chain_lock starts, its loop continues checking transaction records and the mined-height locator indefinitely, even after the conflict is durable. The drain consequently retains shield_guard and blocks subsequent shield-class operations. Make the shared proof-wait paths stop on committed conflict evidence, without publishing an uncommitted conflict as a durable outcome, and cover a sweep arriving after the wait has started.

source: gpt-6.1-sol (phase2-reviewer: general)

Comment on lines +6345 to +6350
if revision > MAX_ASSET_LOCK_OPERATION_REVISION {
return Err(PersistenceError::backend(
"asset-lock operation revision out of range",
));
}
lock.operation_revision = revision;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔴 Blocking: Validate restored operation evidence in the wallet owner

The revision loader checks only the upper bound, and the surrounding restore path never validates the relationship between status, revision, and operation ID after reconstructing both sidecars. A successful UUID callback returning found=false followed by a revision callback returning 1 therefore accepts a Conflicted or recovered row with no UUID. Swift's loader permits the same combination, whereas SQLite's decode_row explicitly rejects it. After reopening, wallet_drain_operation_status_inner searches by UUID and misses this evidence, allowing NotSent; begin_wallet_drain also excludes the unbound row from its pending-operation gate and can build replacement funding for the original UUID. Conflicted rows at revision zero are accepted as well. Add a wallet-owned recovery-metadata invariant and invoke it after complete reconstruction in both restore paths. Invalid combinations must fail the entire load rather than become absent operation history.

source: gpt-6.1-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality, security-auditor)

Comment on lines +34 to +38
var conflict = snapshot(status: 7, operationId: operationId)
conflict.operationRevision = 1
conflict.expectedOperationRevision = 0
handler.beginChangeset(walletId: walletId)
XCTAssertTrue(handler.persistAssetLocks(walletId: walletId, upserts: [conflict], removed: [], revisionAware: true))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔴 Blocking: Use Rust-decodable transaction fixtures in the revision-aware Swift tests

The new revisionAware calls enter asset_lock_operation_persistence_action through withOperationFFI, and Rust consensus-decodes both snapshots through build_unused_asset_locks. The shared snapshot fixture supplies [3, 0, 0, 0, 0, 0, 0, 0, 0, 0]. In the pinned rust-dashcore decoder, its empty input vector selects witness decoding and the following zero produces UnsupportedSegwitFlag(0). The FFI action therefore returns 0 and persistAssetLocks returns false at this assertion and the corresponding assertion in testV4OperationBindingMigratesWithLegacyRevisionAndSurvivesReopen. The stale-snapshot assertion also passes for the wrong reason, before revision acceptance runs. Replace the placeholder with consensus-encoded transaction bytes shared by the predecessor and incoming snapshots; do not weaken the production decoder.

source: gpt-6.1-sol (phase2-reviewer: ffi-engineer)

Comment on lines +240 to +253
if !txids.contains(&lock.out_point.txid)
|| lock.status.is_consumed()
|| lock.status == AssetLockStatus::Conflicted
{
continue;
}
if lock.operation_id.is_some() {
lock.status = AssetLockStatus::Conflicted;
lock.proof = None;
let mut entry = AssetLockEntry::from(&lock);
entry.advance_operation_revision();
changes.asset_locks.insert(lock.out_point, entry);
} else {
changes.removed.insert(lock.out_point);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🟡 Suggestion: Share the conflict projection with the wallet's live sweep path

The replay adapter independently decides whether a swept lock is removed or retained, changes its status to Conflicted, clears its proof, and advances its operation revision. The live remove_tracked_asset_locks_for_swept path implements the same wallet-state decisions separately. They currently agree, but a lifecycle change can update live handling without updating restart repair. Extract a pure swept-lock projection into rs-platform-wallet and call it from both paths, leaving row selection and transactional writes in platform-wallet-storage.

source: gpt-6.1-sol (phase2-reviewer: architecture-layering)

Comment on lines +1625 to +1632
if self.expected_operation_revision.is_some()
&& self.operation_revision == previous.operation_revision
{
let mut incoming = self.clone();
incoming.expected_operation_revision = None;
let mut stored = previous.clone();
stored.expected_operation_revision = None;
return incoming == stored;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🟡 Suggestion: Compare CAS redeliveries without cloning complete snapshots

The exact-redelivery branch clones both AssetLockEntry values solely to clear expected_operation_revision before comparing them. Each clone duplicates the transaction and optional proof even though this operation only needs borrowed equality checks. SQLite persistence and the FFI owner check both reach this branch when a committed CAS is redelivered. Use a borrowed comparison helper or borrowed field tuple that excludes the precondition, preserving equality over every other field without allocating two complete snapshots.

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

Comment on lines +235 to +240
let mut changes = AssetLockChangeSet::default();
for mut lock in load_unconsumed(tx, wallet_id, &LoadCtx::strict())?
.into_values()
.flat_map(BTreeMap::into_values)
{
let mut stmt = tx.prepare_cached(
"SELECT length(outpoint), outpoint FROM asset_locks WHERE wallet_id = ?1 AND status != 'consumed'",
)?;
let mut rows = stmt.query(params![wallet_id.as_slice()])?;
while let Some(row) = rows.next()? {
blob::check_size(row.get(0)?)?;
let bytes: Vec<u8> = row.get(1)?;
let outpoint = blob::decode_outpoint(&bytes)?;
if txids.contains(&outpoint.txid) {
changes.removed.insert(outpoint);
}
if !txids.contains(&lock.out_point.txid)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🟡 Suggestion: Filter sweep candidates before decoding lifecycle blobs

remove_swept now calls load_unconsumed for the whole wallet and only then filters by the swept transaction IDs. That helper reads and decodes every selected lifecycle blob, transaction, and proof, including unrelated locks and UUID-bound terminal tombstones. The previous implementation inspected outpoints before selecting matching losers. On a wallet with substantial retained history, repairing a small sweep therefore performs unnecessary full-history decoding inside the repair transaction. Select candidate outpoints first and decode only matching rows before applying the wallet-owned projection.

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

Comment on lines +89 to +97
let Some(incoming) = incoming.as_ref() else {
return 0;
};
let Ok(incoming) = incoming.decode() else {
return 0;
};
let previous = match previous.as_ref().map(|entry| entry.decode()).transpose() {
Ok(previous) => previous,
Err(_) => return 0,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🟡 Suggestion: Retain diagnostics for malformed FFI operation snapshots

Both decode failures discard their PersistenceError and return the same 0 used for an ordinary policy rejection. The host can only report a rejected persistence round, with no diagnostic distinguishing malformed transaction/proof bytes from a stale CAS. Preserve the stable return-code contract, but emit contextual tracing for unexpected incoming or predecessor decoding failures. Keep normal CAS rejection quiet; it is an expected outcome rather than a decoding fault.

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

@Claudius-Maginificent Claudius-Maginificent added the priority: low Low priority — nice to have label Nov 5, 2026
@lklimek
lklimek removed this pull request from stack #5520 November 5, 2026 12:26
@Claudius-Maginificent Claudius-Maginificent added priority: high High priority — address soon priority: medium Medium priority and removed priority: low Low priority — nice to have priority: high High priority — address soon labels Nov 5, 2026
@Claudius-Maginificent

Copy link
Copy Markdown
Collaborator

Merge-order note: #5762 lands in v5.1-dev before this stack. This PR needs the most care: most of these won't show up as textual conflicts.

lklimek and others added 2 commits November 24, 2026 11:10
…Lite

Preserve the final PR scope, including merge resolutions, on the updated native stack.

Co-Authored-By: Codex <noreply@openai.com>
…conflicts

Preserve the final PR scope, including merge resolutions, on the updated native stack.

Co-Authored-By: Codex <noreply@openai.com>
@lklimek
lklimek added this pull request to stack #6216 November 24, 2026 11:31
…sion loss

Co-Authored-By: Codex <noreply@openai.com>
@lklimek
lklimek force-pushed the fix/persist-drain-conflict-outcomes branch from 25c63bd to fcb8881 Compare November 24, 2026 11:52
…flicts

Keep the recipient bound to the outpoint while funding is conflicted and
reuse the binding when authenticated Core finality restores the funding.
Fence stale snapshots and removals across wallet state, SQLite and
SwiftData while preserving the legacy callback format.

Co-Authored-By: Codex <noreply@openai.com>
@lklimek lklimek changed the title fix(platform-wallet): retain drain operation history through funding conflicts fix(platform-wallet): retain asset-lock recovery metadata through funding conflicts Nov 24, 2026
Base automatically changed from feat/sqlite-wallet-restore to v5.2-dev December 2, 2026 18:13

This branch has not been deployed

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

Labels

priority: medium Medium priority

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants