Skip to content

fix(platform-wallet)!: persist chain truncations so a stored wallet follows a reorg - #5384

Open
Claudius-Maginificent wants to merge 263 commits into
v5.2-devfrom
fix/wallet-persist-chain-truncation
Open

Claudius-Maginificent wants to merge 263 commits into
v5.2-devfrom
fix/wallet-persist-chain-truncation

Conversation

@Claudius-Maginificent

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

Copy link
Copy Markdown
Collaborator

TL;DR

When the blockchain replaces a few recent blocks, the wallet already corrects itself in memory. This PR makes the saved wallet follow, so the balance and history are still right after the app restarts.

User story

As a wallet user, I want my balance and transaction history to match the real chain after a short chain reorganization, so that I do not see coins that no longer exist, or miss coins that came back, the next time I open the app.

Scenario

Actual behavior

A payment arrives and is confirmed in a block. Shortly after, the network replaces that block with a different one. While the app stays open the wallet shows the right picture. After a restart it shows the old one: the payment from the replaced block is still listed as confirmed, coins it spent are still missing, and the wallet does not look again at the blocks that replaced the old ones.

Expected behavior

After a restart the wallet shows the same balance and history as a wallet that was never closed: transactions of replaced blocks are gone or back to unconfirmed, the coins they spent are available again, and scanning resumes from the point where the chain changed.

Detailed discussion

Issue being fixed or feature implemented

Fixes #5380. Targets v5.2-dev, which includes #5150 and the rust-dashcore revision that emits WalletEvent::ChainTruncated.

key-wallet rewinds its in-memory state on a fork (truncate_above) and reports what it did. #5307 mapped that event to an empty persistence round, because changeset merging and every backend only move heights upwards and none can delete the records of a dropped block. The stored wallet therefore stayed on the replaced branch.

What was done?

  • Changeset. CoreChangeSet gains truncations: Vec<ChainTruncation> (height, removed txids, kept unconfirmed_txids, restored_outpoints). A backend applies them before the rest of the round. Merge reduces earlier content by an incoming truncation (records, coins and heights above the fork), so one merged round stores the same wallet as one round per step.
  • Capability. PersistenceCapabilities::CORE_CHAIN_TRUNCATION (bit 17, 0x20000; bit 15 belongs to the private contact request scan state and bit 16 is reserved for CORE_HISTORY_RESTORE in fix(platform-wallet)!: replay recorded transaction history on load for every persister #5220). A persister that does not attest it is not handed the truncation; the rest of the round is stored and one error is logged. A truncation a persister rejected is offered again with the next round; a backend that keeps a failed round owns its truncations until they are applied.
  • SQLite. apply_truncation runs inside the round's write transaction: it deletes the records of dropped blocks with their coins, returns InstantSend-locked ones to unconfirmed, releases the coins the removed records spent and lowers the stored heights to the fork. No schema change. When a fatal flush makes the store drop its buffer, it keeps that buffer's truncations and applies them ahead of the next write, each once.
  • FFI. A new trailing, size-negotiated slot on_persist_wallet_changeset_truncations_fn in PersistenceCallbacksExtension, after the private contact scan-state slots, delivers ChainTruncationFFI values before the other callbacks of the round. A transaction a same-round truncation keeps is projected to the host as InstantSend-locked, so the round's ordinary callbacks do not overwrite that state.
  • JNI / Kotlin. NativePersistenceBridge.onWalletChangesetChainTruncated; the Room handler applies the truncation in the round's transaction. Kotlin declares the bit as CAPABILITY_CORE_CHAIN_TRUNCATION = 0x20000.
  • Swift. The SwiftData handler applies the truncation in the round's changeset. A removed row is set aside and deleted at the end of the round unless the same round stores the transaction again, because txid and outpoint are unique attributes and a delete followed by an insert of the same key in one save was not confirmed to be safe.
  • Shared transaction rows (Swift, Kotlin). Those stores keep one transaction row for all wallets while rounds commit per wallet, so a truncation takes only the truncating wallet's coins, spend links, pending claims and account involvement; the shared row is deleted only when nothing references it.
  • DashPay payments. A sent payment whose block was dropped returns from confirmed to pending. If the store rejected the round that carried that change, it is offered again with the wallet's next round.
  • Spend fences. A coin a truncation hands back is fenced again until the undone spend is seen again, so it is not selected for a second spend while the first may still confirm. The fence is set where the wallet is truncated, under the wallet-manager write lock, because fork recovery truncates between two runs of the SPV client, when no event handler is listening.
  • The InstantSend lock of a detected transaction is stored when the transaction is detected, so a fork after a restart keeps a locked transaction as unconfirmed instead of removing it.

Asset locks need no change: a truncation never goes below the best ChainLock, and their statuses depend on finality only.

Known limitations

  • A persister without the capability keeps the replaced branch until it rescans. A rejected truncation is retried from memory only, so a restart or a panic of the committing thread loses it. A truncation the store cannot apply is retried ahead of every later round of that wallet, so that wallet's writes fail until it applies; it is never skipped. The retry also follows a failure whose outcome the backend could not vouch for; over a partly applied round it removes only that round's content above the fork, which the next start rescans. No in-tree backend can leave a round partly applied, and this convergence is reasoned from the code, not covered by a test.
  • A payment returned to pending and not yet accepted by the store is held in memory only, so a restart before the store accepts it leaves the stored payment confirmed. It is offered to the store again after a rejected round, but given up when the round that carries it is refused a second time with a failure that is not transient; the stored payment then stays confirmed. On the Swift store every failure is reported as permanent, so such a row gets one retry.
  • When a payment reversal a round reports itself is the cause of a refusal that is not transient, it is carried once and makes the next round fail as well before it is given up.
  • A point read of a stored transaction (get_core_tx_record) returns the record as written and does not consult the stored InstantSend locks. A transaction locked after it was stored, or kept by a truncation, therefore reads as a mempool transaction there, while the loaded wallet holds it as InstantSend-locked; sent-payment history built from that read can show it as pending until it is mined. Coins and balances are not affected. This predates the PR for transactions locked after they were stored.
  • If the identity that owns such a payment is removed and added again before the retry, the row is written into the new identity's payment history, where it shows as a pending sent payment.
  • On the Swift store the pending-input lookup used when a truncation hands a coin back does not report a failed read. If that read fails while a swept-input tombstone exists for the coin, the tombstone survives and can later mark the restored coin spent in the store; the wallet itself still holds the coin. The same lookup serves the sweep path and predates the PR.
  • The Swift host's changeset-end callback reports every failed round as a failed rollback, so all of them are classified as fatal and a Swift host never receives a transient verdict for a round in which a callback failed. This predates the PR; separating the cases needs new FFI return codes.
  • A transaction row is shared by all wallets of a Swift or Kotlin store, so between two wallets' rounds its block fields can show the branch the other wallet last wrote; coins and balances are per wallet and are not affected.
  • Under FlushMode::Manual (not the default; no in-tree host sets it) a fatal flush drops the buffered round. The truncation is kept and applied with the next write, but a sent payment the fork returned to pending is not, so its stored status can stay confirmed.
  • The sent-payment reconcile pass confirms from the stored transaction record. If it reads a pre-fork record just before the truncation is stored and writes its confirmation just after, the payment the fork returned to pending is stored and shown as confirmed again; unless the transaction is mined again, nothing corrects it. After a rejected truncation round the same pass can instead leave the payment confirmed in memory and pending in the store until the next start.
  • On the Kotlin store a coin spent by an InstantSend-locked transaction that is not in a block is not marked spent, and unconfirmed sends are not replayed at load. When the mining of such a transaction and the truncation of its block reach the store in one round, the coin reloads as unspent after a restart until the transaction is mined again and scanned. The Swift store replays unconfirmed sends at load and is not affected.
  • BalanceUpdateHandler takes the post-truncation balance from the SPV event monitor (rs-platform-wallet/src/wallet/core/balance_handler.rs:76-78), which does not receive ChainTruncated during fork recovery, so the lock-free balance read by the UI is not refreshed until the next wallet event. This predates the PR.
  • A send that selects a coin handed back by a truncation fails with InputMidBroadcast until the undone spend is seen again, at the latest until the wallet restarts.
  • FFI hosts (SwiftData, Room): a fork that happens after a restart is not undone, because the FFI restore path does not replay ordinary transaction records, so key-wallet has nothing above the fork to rewind. The stored state is corrected by the next rescan. fix(platform-wallet)!: replay recorded transaction history on load for every persister #5220 adds the replay of recorded history on the FFI load path for SwiftData; the Kotlin host does not supply history yet. Hosts also store no InstantSend lock bytes (see the known limitations of fix(platform-wallet)!: replay recorded transaction history on load for every persister #5220); a kept transaction is stored in the InstantSend context without them.
  • When the detection of an unconfirmed payment and its removal by a conflicting confirmed spend reach the store in one round, SQLite can keep the coin as unspent although the running wallet has it spent. This predates the PR and does not involve a fork; it is marked TODO(sweep-of-unstored-loser).
  • After a conflict was settled and the winner's block is then dropped, key-wallet does not hand the coin back (upstream behaviour, related to dash-spv: build a reorg/disconnect pipeline so key-wallet can retract non-chainlocked observed-spent entries rust-dashcore#854); the store follows the wallet.

Out of scope

  • Sent-payment status has three writers — the adapter's verdicts, the reversals it carries after a rejected round, and the reconcile pass — and each decides on its own. They need one shared rule for freshness (a writer does not act on evidence older than the last truncation that is not yet stored) and for identity lifecycle (a row belongs to the identity it was decided for, and is dropped when that identity is removed, also if it is added again).
  • The point read of a stored transaction (get_core_tx_record) should resolve the stored InstantSend locks the way the full load does, so every reader sees a locked transaction as locked, whether it was locked after it was stored or kept by a truncation.

How Has This Been Tested?

  • Latest local run, all features: platform-wallet-ffi, rs-unified-sdk-jni and platform-wallet-storage in full, plus the platform-wallet capability, changeset and truncation tests. All pass except 4 sqlite_identity_key_restore tests, which fail on a local temp directory without the sticky bit (InsecureParentDir), not on this change. Clippy passed for wallet, storage, wallet FFI and unified JNI with --all-targets --all-features -- -D warnings.
  • The truncation checkpoint regression failed before its fix and passes afterward. The checkpoint is bounded by the observed live height and fork height, remains subject to the normal epoch checks, and cannot override a later contact-history rewind.
  • tests/sqlite_chain_truncation.rs drives a real WalletManager through the adapter into SqlitePersister, reopens the store and compares the loaded wallet with the one that never restarted, with one round per step and with one merged round: a spent coin restored when its spender is not mined again, a transaction stored once when mined again, heights lowered to the fork, an InstantSend-locked transaction kept unconfirmed (also when the fork follows a restart), and a store left untouched when a truncation cannot be applied.
  • A property test stores generated sequences of blocks, receipts, spends, syncs and forks both ways and requires the same stored wallet. It does not generate conflicting spends.
  • The new tests were shown to fail without the change; disabling the merge reduction fails every merged-round variant.
  • Tests also cover a kept transaction projected to FFI hosts as InstantSend-locked, a truncation kept across a dropped buffer and applied once, a payment returned to pending offered again after a rejected round and given up once the store refuses it for good, a restored coin fenced by a truncation of a real manager with no event delivered, and, per host, two wallets sharing a transaction (removed, kept, and the shared row's lifetime).
  • Not run locally: the Swift and Kotlin code and their tests (ChainTruncationPersistTests.swift, PlatformWalletPersistenceHandlerTest.kt). No Swift or Android toolchain was available; they run in CI only.

Breaking Changes

None for consensus, persisted data or the C layout. Rust source only: CoreChangeSet gains the public field truncations, PersistenceCallbacksExtension gains on_persist_wallet_changeset_truncations_fn, and PersistenceExtensionCallbacks gains wallet_changeset_truncations. Code that builds any of them with a full struct literal must set the new field; ..Default::default() keeps the previous behaviour for all three (PersistenceCallbacksExtension::default() leaves the new slot None). For C and Swift/Kotlin hosts the slot is trailing and size-negotiated, and the capability bit is additive.

Checklist

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

Lock state of transactions a truncation keeps

A truncation keeps only InstantSend-locked transactions. key-wallet demotes their records to Mempool and holds the lock only as a txid, so no lock payload exists to restore an InstantSend context. CoreChangeSet::rewind_to mirrors that and never fabricates a lock, because a fabricated lock would be persisted and later read back as a real one.

CoreChangeSet::is_unconfirmed_instant_send_locked decides whether such a record is unconfirmed and InstantSend-locked. The FFI changeset projection (WalletChangeSetFFI::from_changeset) only marshals that answer into the row context and the outputs' is_instantlocked flag. The SQLite store uses the same representation: a Mempool record blob plus its core_instant_locks row, which rehydration upgrades to InstantSend.

Hosts still apply the truncation's txids, unconfirmed_txids and restored_outpoints themselves. Emitting those as ordinary upserts needs upstream key-wallet (rust-dashcore) to keep the InstantSend lock payload of a record whose block a truncation drops; that is a follow-up.

🤖 Co-authored by Claudius the Magnificent AI Agent

🤖 Generated with Claude Code

https://claude.ai/code/session_01PSi8cX229kW2fmLxKW6ir4

PR Hygiene · e78edb4

  • Bots — thepastaclaw requested changes — dismiss the review or push a fix, 2 threads unresolved — resolve them
  • Self-review — not asked of a bot author
  • Build failed
  • Approvals
    • files with no dedicated owner (CHANGELOG.md, packages/rs-unified-sdk-jni/src/persistence.rs) — QuantumExplorer or shumkov
    • kotlin-sdk (packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/NativePersistenceBridge.kt, packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt, packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/DocumentDao.kt and 5 more) — HashEngineering
    • rs-platform-wallet-ffi (packages/rs-platform-wallet-ffi/src/core_wallet_types.rs, packages/rs-platform-wallet-ffi/src/manager.rs, packages/rs-platform-wallet-ffi/src/persistence.rs) — HashEngineering or ZocoLini or llbartekll or romchornyi
    • wallet-storage (packages/rs-platform-wallet-storage/src/sqlite/persister.rs, packages/rs-platform-wallet-storage/src/sqlite/schema/core_state.rs, packages/rs-platform-wallet-storage/tests/integration/main.rs and 1 more) — lklimek
    • rs-platform-wallet (packages/rs-platform-wallet/src/changeset/changeset.rs, packages/rs-platform-wallet/src/changeset/core_bridge.rs, packages/rs-platform-wallet/src/changeset/persistence_capabilities.rs and 4 more) — HashEngineering or ZocoLini or llbartekll or romchornyi
    • swift-sdk (packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift, packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift, packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ChainTruncationPersistTests.swift and 1 more) — llbartekll or romchornyi

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

lklimek and others added 30 commits September 29, 2026 16:24
…dable

Pre-fix builds persisted DashPay contact (watch-only) outputs as unspent
core_utxos rows. V019 re-labels their history as Sent but left the rows
unspent, so load routed them to the first funds account: the balance
included coins the wallet cannot sign and coin selection could pick one.

load_state now skips unspent contact-only rows. The rows are kept in
SQLite (no destructive migration step), so the exclusion is reversible.

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

loadWalletList saved or rolled back the background context
unconditionally after reconciling transaction accounting. Inside an open
begin/endChangeset round that committed half of the round or silently
discarded its staged writes while the round still reported success.

Guard the pass with !inChangeset like every other load-time writer; the
round reconciles its own dirty rows and the next load runs the full pass.

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

#5057 folded DRIVE_ABCI_QUERY_VERSIONS_V3 into V2 (identical values) and
deleted v3.rs; PV14 was updated but PV15, introduced on v4.3-dev, still
imported V3, so the v4.2-dev -> v4.3-dev merge stopped compiling.
Pure rename; the selected query versions are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The v4.2-dev -> v4.3-dev merge (704307e) left an unused import and
stray blank lines in dpns.rs, failing clippy -D warnings and rustfmt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The structure generator describes PlatformVersion::latest(), which is 15
once PLATFORM_V15 compiles. The committed JSON and a hard-coded
"@14" assertion were stale. Regenerated the JSON (version labels only)
and derive the expected fixture origin from PlatformVersion::latest().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
 review (#5208)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…, document V019

- V019 `read_record` now queries `length(record_blob)` on its own and fetches
  the blob only after `check_size` passes. SQLite evaluates every result
  column before returning a row, so the old single `SELECT length(b), b`
  loaded an oversize blob into SQLite's heap before the check could run.
- SCHEMA.md: add the V019 migration row and sections for
  `core_transaction_inputs` and `core_transaction_record_originals`, list both
  among the not-yet-diagrammed tables, and name all three writers of
  `core_utxos.spent_in_txid` (apply_sweep, runtime history repair, V019 repair).
- Tests: import `migrations` at the top of the core_state and legacy_v019 test
  modules instead of calling `crate::sqlite::migrations::run` inline.
- Swift tests: build `PersistentTransaction` fixtures with `CoreDirectionCode`
  instead of raw direction integers.

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

coalesce_account_records kept a later record's body but copied in the
earlier record's higher-ranked context, fabricating a record whose
finality came from a different observation. The higher context_rank
record now wins intact; on equal rank the later one wins.

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

The load path now runs the accounting reconcile before restoring unspent
TXOs, so the fault-injection test observes three more reads ahead of the
faulted PersistentAssetLock fetch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`upsertTransaction` writes a never-pruned pending input for every input
whose prevout has no local TXO, including every foreign input of an
ordinary incoming payment, so `netAmount(for:)` returned nil ("Amount
unavailable") for received payments and hid provider names and fees.

The stored scalar is the sole participating wallet's own accounting, so
it now answers ahead of the pending-input check; that check only makes
the TXO-computed multi-wallet amount provisional, and only for pending
inputs the queried wallet recorded. Participation includes
`involvedAccounts`, so a payload-only row recorded by one wallet keeps
its stored amount and a row recorded by two wallets never hands one of
them the other's scalar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018LN7YPS4eaKdQv5XFUBPLH
Pin `direction(for:)` and `netAmount(for:)` for an A→B transfer between
two local wallets, and when "Amount unavailable" is expected for rows
without linked TXOs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018LN7YPS4eaKdQv5XFUBPLH
… a V019 rescan

V019's corruption recovery subtracted one from the raw stored
`birth_height`, so `i64::MIN` panicked with subtract-overflow inside
`migrations::run`. Gate it through `i64_to_u32` (typed IntegerOverflow,
the whole upgrade rolls back) and use `saturating_sub(1)`. Out-of-range
heights are no longer silently clamped to a rescan from genesis.

The runtime repair in `schema::core_history` never reads `birth_height`,
so it has no equivalent to fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018LN7YPS4eaKdQv5XFUBPLH
Upstream key-wallet classifies each account on its own. For an asset
lock with no change output, the funding account says `Outgoing`, because
the OP_RETURN burn is not an owned output. The keys account says
`Internal`. The live fold kept the funding verdict, while the SQLite
repair, the frozen V019 migration and Swift all write `Internal`. As a
result, the same row flipped whenever storage repaired it.

The fold also summed the keys account's `+credit` marker net into the
wallet net. Live asset-lock rows therefore read `-fee`, while every
repair path wrote `-(credit + fee)`, with or without change (ARCH-002).
A test reproduced this before the fix (folded net -1000 = -fee).

Changes:
- Add one wallet-level accounting rule in
  `changeset::wallet_accounting`:
  - `wallet_direction` (public) is the rule the repair already used.
  - `apply_wallet_accounting` sets net to owned outputs minus owned
    inputs, and sets direction via `wallet_direction`.
- `fold_same_txid_records` now applies that rule to every record,
  folded or single, after the per-txid merge. A funding slice that never
  meets its keys marker is normalised too.
- Records with no details (keys markers only) keep upstream's net and
  direction, mirroring repair's "empty metadata is not evidence".
- The storage runtime repair calls `platform_wallet::changeset::wallet_direction`
  instead of its own copy. The Swift-shared case table stays in storage
  under the same name.
- The frozen V019 logic is untouched.
- `test_support::fold_wallet_records` exposes the live fold, so storage
  can pin repair parity against it.

No existing test pinned the old live behaviour, so none needed updating.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018LN7YPS4eaKdQv5XFUBPLH
…ansactions

The wallet-level accounting pass runs on every projected record,
including singles, so this regression table shows that the live
projection's net and direction are unchanged for every other transaction
shape.

The table covers 14 cases:
- plain receive
- send with and without change
- self-transfer within one account and between two accounts
- CoinJoin
- provider registration, with an own and with an external collateral
- asset unlock
- coinbase
- payment to a contact, with the watch-only slice present
- payment from a contact into DashPay receiving funds
- a single keys marker
- a keys-only group

The expected values were derived by running the table against the
pre-pass fold (a70ee60); all 14 pass there.

One case changes on purpose. A group made only of keys-account markers,
with no details, used to re-derive `Incoming` from its empty details. It
now keeps upstream's `Internal`, which matches a single marker and the
SQLite repair (that repair skips detail-less records).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018LN7YPS4eaKdQv5XFUBPLH
The Rust repair's local `repaired_direction` was replaced by the shared
`platform_wallet::changeset::wallet_direction`, which both the live
projection and the SQLite repair use. The comment is the only change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018LN7YPS4eaKdQv5XFUBPLH
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The v5.0-dev merge into v5.1-dev added the contract_with_team_actions
fixture, recorded at protocol 14. Regenerate so its origin labels follow
the latest protocol version (15) like the rest of the snapshot.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…r a known txid

The body-conflict check compared whole `Transaction` values, including
`TxIn::witness`, which the txid does not commit to. dashcore still decodes
BIP144-style witnesses, so a peer could serve a known txid with an extra
witness and the resulting non-transient conflict wiped the whole flush
buffer. Compare the bodies' computed txids instead and keep the stored
body, so a witness-only variant neither fails the flush nor replaces it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018LN7YPS4eaKdQv5XFUBPLH
…te repair

The storage repair re-implemented the owned-output net, the has_ours and
has_external scans and the Received|Change ownership predicate that the
live fold already applies. Expose `wallet_accounting` (net as i128 plus
direction) and `is_owned` from `platform_wallet::changeset` and call them
from both paths; each keeps its own i64 overflow policy (live saturates,
repair errors). The module doc now states what is shared and that the
frozen V019 migration keeps its own copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018LN7YPS4eaKdQv5XFUBPLH
…ounting reconcile

The reconcile pass read `account.wallet` directly in the network
fallback, the unlinked-output owner check and the load-time filter. That
relationship is fault-loaded, and the rest of the handler reads it through
an Optional cast so that a store inconsistency cannot trap. The load
filter runs before wallets restore, where a trap would get past the
surrounding do/catch. Read it through the cast everywhere, and build the
load filter from `walletOwnsTransaction` so there is a single ownership
predicate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018LN7YPS4eaKdQv5XFUBPLH
… protocol 15

The v5.1-dev merge brought the team-action layers recorded at protocol 14.
The base relabel to 15 did not cover them, so the structure check failed.
The tree layout is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018LN7YPS4eaKdQv5XFUBPLH
The external-output check rescanned output_details for every transaction
output, so large self-splits cost O(N^2) on both the live fold and the
SQLite runtime repair. Collect the owned/unspendable output indices into
a set first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018LN7YPS4eaKdQv5XFUBPLH
…ding on load

A spender whose funding output persists only as a height-only row replayed
with no owned input: load excludes spent outputs, so the checker saw an
irrelevant transaction and rebuilt no account spent mark. Once a chain lock
pruned the observed spend (or for any unconfirmed spend), a redelivered
funding transaction re-credited the consumed output as selectable.

Before replay, stage every owned input named by a stored record's
input_details whose funding no replayed record credits. Replaying the
spender then removes it and records the spent mark; the retention pass
drops anything left, since staged coins are never part of the persisted
unspent set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018LN7YPS4eaKdQv5XFUBPLH
… of replay order

Unconfirmed siblings replay by txid, so an InstantSend winner replayed before
its conflicting mempool loser swept nothing: the loser was not installed yet,
and on its own replay its wallet-owned change was credited and survived the
retention pass as selectable. The opposite order swept it.

Collect every record replayed in InstantSend context and run its conflict
sweep once more after the full replay, so the outcome no longer depends on
sibling order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018LN7YPS4eaKdQv5XFUBPLH
lklimek and others added 5 commits November 5, 2026 11:02
Keep wallet-level accounting and late ownership repair independent of spend
claims. Make V020 additive, backfill existing mined and pending records,
and preserve original record bytes before repairs. Load each wallet from
one coherent read snapshot.

Move replay, authorization, conflict settlement and destructive rescan out
of the accounting root for consolidation in the dependent replay PR.
Retain established base sweep behavior and its regression coverage.

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

Co-Authored-By: OpenAI Codex <noreply@openai.com>
Project completed accounting slices and their output verdicts under one
wallet read guard. Preserve observed-spent withholding across buffered
merges while allowing genuine current credit to clear the earlier verdict.

Validation: projection-to-merge regression RED then GREEN; 18 scoped tests
and wallet/storage all-targets all-features CI clippy pass.

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>
Propagate retryable SQLite errors before the corrupt-row recovery path.
Exercise SQLITE_BUSY through a safe test-only scalar function, preserving
the savepoint, and verify schema rollback plus complete successful retry.

Validation: swallowed-error regression RED then GREEN; scoped migration
tests and wallet/storage all-targets all-features CI clippy pass.

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>
Recognize the pre-stable full-payload transaction hash only for historical
AssetUnlock payloads version 2 or later. Preserve their stored identifiers,
transaction bodies and indexed outpoints. Require current canonical IDs on
new writes; leave consensus hashing and bulk-load behavior unchanged.

Add immutable records generated by the d631aaca writer and its real serde
codec. Verify strict upgrade/read, key consistency, tamper rejection and
modern-write binding. Regression RED then GREEN; 39 scoped storage tests
and wallet/storage all-targets all-features CI clippy pass.

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>
Check body, input/output details, fee, label and direction for lower,
equal and higher context ranks.

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>
Keep one transaction body and its computed identifier while varying the
snapshot metadata checked by the whole-record selection regression.

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>
@Claudius-Maginificent Claudius-Maginificent added priority: high High priority — address soon and removed priority: low Low priority — nice to have labels Nov 5, 2026
lklimek and others added 3 commits November 6, 2026 10:25
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ashcore bump

The rust-dashcore update merged from v5.1-dev makes the byte-array
constructors and accessors inherent on the hash newtypes, so the
`dashcore::hashes::Hash` imports added on this branch are unused and
fail clippy with -D warnings.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Claudius-Maginificent Claudius-Maginificent added priority: medium Medium priority and removed priority: high High priority — address soon labels Nov 6, 2026
@Claudius-Maginificent

Copy link
Copy Markdown
Collaborator Author

Merge-order note: #5762 lands in v5.1-dev before this stack.

When this branch next merges its base:

lklimek and others added 7 commits November 9, 2026 15:55
A new variant must break every downstream match that has not classified
it. #[non_exhaustive] forced a panicking wildcard arm into the external
classification test, which silently absorbed later variants. Restore the
wildcard-free match there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WunYYijwZNbw3EjHtdMAHC
Add a coding-conventions rule, mirrored in AGENTS.md: the workspace's own
error enums are not #[non_exhaustive], and per-variant matches over them
list every variant, so a new variant breaks the build at each caller.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WunYYijwZNbw3EjHtdMAHC
Brings in #5762, which takes migration V020 for the asset-lock shielded
recipient. The core transaction accounting migration moves to V021:
file, module, typed-hook version, test rewind and version asserts,
SCHEMA.md rows and schema pinning fingerprints.

Upstream bumps rusqlite to 0.41; the rusqlite dev-dependency used for
migration fault injection follows it.

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

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>
…ack5150-5384-20261110

# Conflicts:
#	packages/rs-platform-wallet-ffi/src/manager.rs
#	packages/rs-platform-wallet-ffi/src/persistence.rs
#	packages/rs-platform-wallet-storage/src/sqlite/persister.rs
#	packages/rs-platform-wallet-storage/src/sqlite/schema/core_state.rs
#	packages/rs-platform-wallet/src/changeset/persistence_capabilities.rs
#	packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift
#	packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift
#	packages/swift-sdk/SwiftTests/SwiftDashSDKTests/InvitationPersistenceTests.swift
…rged base

The base no longer signs spends in the storage test helpers (spend
authorization moved out of the accounting root), so the truncation
scenario builds its payment unsigned. The rust-dashcore bump makes
`from_byte_array` inherent, so the `hashes::Hash` imports are unused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ases until #5220

The merged base loads a wallet without replaying its transaction records
and its SQLite store does not apply `utxo_credit_verdicts`; #5220 restores
both. Until then:

- The restart cases keep every balance, coin and height assertion on the
  rehydrated wallet, and read the restored history from the stored
  `core_transactions` rows, which is what this store owns.
- The relaunch-then-truncate case needs the records in memory, so it is
  ignored with a TODO(#5220).
- A deterministic repro pins the shape the store cannot follow yet: a
  reorged transaction re-enters (mined or relayed) while the wallet holds
  a relayed spend of its output, and the store credits that output as
  unspent. Ignored with a TODO(#5220).
- The differential proptest rejects exactly that shape (tracked by the
  test miner) so it stays deterministic in CI; TODO(#5220) drops the
  filter.

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

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

At ee089b3, the merged-base adjustments disable two replay/credit-dependent regressions and exclude related property-test histories; static inspection confirms that the SQLite retained-descendant sequence can restore an already-spent output. Current-head Kotlin CI passes, but the available checks provide no Rust or Swift validation; no local builds or tests were run.

🔴 3 blocking | 🟡 6 suggestion(s)

1 finding(s) not shown inline (the lines are not part of this PR's diff)

🟡 Suggestion: Make truncation persistence work after FFI wallet restoration
packages/rs-platform-wallet-ffi/src/persistence.rs:6154-6159

The replay prerequisite is only partly tracked. Ordinary restored transactions remain absent from the account maps that pinned key-wallet's truncate_above enumerates, so a post-restart fork cannot report the removals needed by these callbacks. #5220 tracks shared Rust replay for Swift, but explicitly excludes Android and leaves SQLite unchanged; this head also disables SQLite's restart-then-truncate regression. This existing prerequisite can be deferred rather than implemented in the binding, but extend the linked tracking to the uncovered backends or link separate follow-ups before treating the restore gap as fully deferred. Restoration decisions belong in the shared Rust wallet owner, not separate host implementations.

source: muse-spark-1.3-contributor (phase1-reviewer: general); gpt-6.1-sol (phase2-reviewer: general)

Still open from earlier rounds (7)

  • 🔴 Blocking: Persist retained transaction input debits in merged truncation rounds — packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt:1352-1356 (thread)
  • 🔴 Blocking: Coordinate retried payment reversals with confirmation reconciliation — packages/rs-platform-wallet/src/changeset/core_bridge.rs:2114-2117 (thread)
  • 🟡 Suggestion: Do not globally demote a shared transaction row from one wallet's truncation — packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt:1355-1356 (thread)
  • 🟡 Suggestion: Propagate pending-input lookup failures through the truncation callback — packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:1823-1825 (thread)
  • 🟡 Suggestion: Cancel retained payment reversals when their owning identity is removed — packages/rs-platform-wallet/src/changeset/core_bridge.rs:1193-1197 (thread)
  • 🟡 Suggestion: Retain payment reversals with backend-owned truncations — packages/rs-platform-wallet-storage/src/sqlite/persister.rs:1192-1201 (thread)
  • 🟡 Suggestion: Resolve retained InstantSend finality for every storage reader — packages/rs-platform-wallet-storage/src/sqlite/schema/core_state.rs:458-465 (thread)
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); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)

  • Triage: normal by gpt-6.1-sol (effort low) — This is a large, intricate cross-language wallet-persistence change affecting truncation, coin restoration, and stored transaction state, but it does not itself change consensus, cryptography, coin-selection logic, or a storage schema migration.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity quota lookup failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort high); agent phase2-reviewer
🤖 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 are optional: fix them forward in a later PR rather than pushing another round just for them.
- Address every current finding in one push: self-review the full diff first, and don't push piecemeal.
- 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-storage/src/sqlite/schema/core_state.rs`:
- [BLOCKING] packages/rs-platform-wallet-storage/src/sqlite/schema/core_state.rs:85-88: Apply credit verdicts when re-mining a truncated parent
  A parent transaction removed by a fork can be mined again while its retained InstantSend-locked descendants already consume its outputs. The bridge supplies utxo_credit_verdicts for outputs the running wallet withholds, but SQLite never consumes those verdicts: this truncation deletes the parent's coins, and the later new_utxos loop inserts derived outputs with spent=false. Re-emitting a retained descendant need not provide fresh owned-input details to debit that output. Because the current SQLite loader also does not replay ordinary transaction history, the output becomes spendable after restart despite being absent from the running wallet. The ignored should_not_restore_an_output_a_kept_descendant_spends_when_its_parent_is_mined_again regression and the property-test rejection filter identify this exact sequence. Apply the Rust-owned credit/debit evidence in SQLite and enable the regression. Linking #5220 does not presently cover this correction: that PR's description explicitly leaves SQLite restoration unchanged.
- [SUGGESTION] packages/rs-platform-wallet-storage/src/sqlite/schema/core_state.rs:458-465: Resolve retained InstantSend finality for every storage reader
  (carried; thread: https://github.com/dashpay/platform/pull/5384#discussion_r4252965583)

In `packages/rs-platform-wallet-ffi/src/persistence.rs`:
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/persistence.rs:6154-6159: Make truncation persistence work after FFI wallet restoration
  The replay prerequisite is only partly tracked. Ordinary restored transactions remain absent from the account maps that pinned key-wallet's truncate_above enumerates, so a post-restart fork cannot report the removals needed by these callbacks. #5220 tracks shared Rust replay for Swift, but explicitly excludes Android and leaves SQLite unchanged; this head also disables SQLite's restart-then-truncate regression. This existing prerequisite can be deferred rather than implemented in the binding, but extend the linked tracking to the uncovered backends or link separate follow-ups before treating the restore gap as fully deferred. Restoration decisions belong in the shared Rust wallet owner, not separate host implementations.

In `packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt`:
- [BLOCKING] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt:1352-1356: Persist retained transaction input debits in merged truncation rounds
  (carried; thread: https://github.com/dashpay/platform/pull/5384#discussion_r4251865317)
- [SUGGESTION] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt:1355-1356: Do not globally demote a shared transaction row from one wallet's truncation
  (carried; thread: https://github.com/dashpay/platform/pull/5384#discussion_r4411730848)

In `packages/rs-platform-wallet/src/changeset/core_bridge.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/changeset/core_bridge.rs:2114-2117: Coordinate retried payment reversals with confirmation reconciliation
  (carried; thread: https://github.com/dashpay/platform/pull/5384#discussion_r4251865308)
- [SUGGESTION] packages/rs-platform-wallet/src/changeset/core_bridge.rs:1193-1197: Cancel retained payment reversals when their owning identity is removed
  (carried; thread: https://github.com/dashpay/platform/pull/5384#discussion_r4252358882)

In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:1823-1825: Propagate pending-input lookup failures through the truncation callback
  (carried; thread: https://github.com/dashpay/platform/pull/5384#discussion_r4252358886)

In `packages/rs-platform-wallet-storage/src/sqlite/persister.rs`:
- [SUGGESTION] packages/rs-platform-wallet-storage/src/sqlite/persister.rs:1192-1201: Retain payment reversals with backend-owned truncations
  (carried; thread: https://github.com/dashpay/platform/pull/5384#discussion_r4251865297)

Comment on lines +85 to +88
// First: the rest of the changeset is the wallet after its last
// truncation, so its rows must land on a store already cut back.
for truncation in &cs.truncations {
apply_truncation(tx, wallet_id, truncation)?;

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: Apply credit verdicts when re-mining a truncated parent

A parent transaction removed by a fork can be mined again while its retained InstantSend-locked descendants already consume its outputs. The bridge supplies utxo_credit_verdicts for outputs the running wallet withholds, but SQLite never consumes those verdicts: this truncation deletes the parent's coins, and the later new_utxos loop inserts derived outputs with spent=false. Re-emitting a retained descendant need not provide fresh owned-input details to debit that output. Because the current SQLite loader also does not replay ordinary transaction history, the output becomes spendable after restart despite being absent from the running wallet. The ignored should_not_restore_an_output_a_kept_descendant_spends_when_its_parent_is_mined_again regression and the property-test rejection filter identify this exact sequence. Apply the Rust-owned credit/debit evidence in SQLite and enable the regression. Linking #5220 does not presently cover this correction: that PR's description explicitly leaves SQLite restoration unchanged.

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

Base automatically changed from fix/pr-5126 to v5.2-dev November 17, 2026 06:42
@github-actions github-actions Bot added this to the v5.2.0 milestone Nov 17, 2026
@github-actions github-actions Bot added the waiting-self-review Waiting for the author to post /self-reviewed label Nov 17, 2026
lklimek and others added 2 commits November 17, 2026 08:05
Merges 8e85aa7. This branch already contains #5150's final head
(2d025ae), which v5.2-dev carries squashed as c9e5cd4, so a file whose
v5.2-dev content equals 2d025ae keeps this branch's version, and files
v5.2-dev changed again after #5150 were merged three-way against 2d025ae.

Capability bit renumbering: v5.2-dev declares
PRIVATE_CONTACT_REQUEST_SCAN_STATE at bit 15, which this branch used for
CORE_CHAIN_TRUNCATION. CORE_CHAIN_TRUNCATION moves to bit 17 (0x2_0000);
bit 16 stays reserved for CORE_HISTORY_RESTORE (#5220). Updated in Rust,
the FFI constant, Swift, Kotlin and their tests.

Conflicted files and resolution:
- rs-platform-wallet-storage sqlite/schema/core_state.rs: ours (the v5.2-dev
  side is #5150 as already merged here).
- rs-platform-wallet changeset/changeset.rs, core_bridge.rs: three-way against
  2d025ae, which applies only v5.2-dev's later changes.
- changeset/persistence_capabilities.rs: both bits, both names in KNOWN,
  HIGHEST_DECLARED_BIT 17 with bit 16 reserved, both value assertions.
- rs-platform-wallet-ffi persistence.rs: v5.2-dev's private contact scan
  state constant, extension slots, defaults, parsed slots and layout
  assertions placed before this branch's truncations slot (v5.2-dev's ABI
  order is kept); both constant assertions.
- rs-platform-wallet-ffi manager.rs: union of imports, slot reads and tests.
- rs-unified-sdk-jni persistence.rs: union of imports and tests; each side's
  BridgeOverrides literals gain the other side's field.
- kotlin-sdk NativePersistenceBridge.kt, PlatformWalletManager.kt,
  PlatformWalletPersistenceHandler.kt: both capabilities declared;
  PlatformWalletPersistenceHandlerTest.kt expects 0x28bbf and both names.
- swift-sdk PlatformWalletManager.swift, PlatformWalletPersistenceHandler.swift,
  InvitationPersistenceTests.swift: both capabilities and both sets of
  extension callbacks.

Swift and Kotlin were resolved by reading; not built.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WunYYijwZNbw3EjHtdMAHC
Merges 6e113dc (#5780). No conflicts.

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

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

The truncation transport, capability negotiation, and atomic callback ordering are implemented coherently, and the available Rust, Swift, and Kotlin CI checks pass. The current head still contains blocking restart and persisted-state correctness defects in SQLite, FFI restoration, Kotlin retained-spend handling, shared transaction demotion, and payment reconciliation.

🔴 5 blocking | 🟡 5 suggestion(s)

1 finding(s) not shown inline (the lines are not part of this PR's diff)

🔴 Blocking: Make truncation persistence work after FFI wallet restoration
packages/rs-platform-wallet-ffi/src/persistence.rs:6668-6685

The FFI restore path decodes only the host's unconfirmed outgoing transactions; it does not replay ordinary confirmed Core transaction records into key-wallet. After restart, a subsequent fork therefore leaves key-wallet with no in-memory records above the fork, so truncate_above cannot emit the removed and retained transaction identities needed by the new persistence callbacks. The host can retain old-branch transaction and coin rows until a later rescan, which fails the PR's stated restart-equivalence goal. #5220 is a relevant follow-up for part of this work, but the current PR is responsible for the advertised reorg-after-restart behavior and the Kotlin path remains uncovered.

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality); gpt-6.1-sol (phase2-reviewer: general)

Still open from earlier rounds (9)

  • 🔴 Blocking: Apply credit verdicts when re-mining a truncated parent — packages/rs-platform-wallet-storage/src/sqlite/schema/core_state.rs:85-88 (thread)
  • 🔴 Blocking: Do not globally demote a shared transaction row from one wallet's truncation — packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt:1411-1415 (thread)
  • 🔴 Blocking: Persist retained transaction input debits in merged truncation rounds — packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt:1295-1305 (thread)
  • 🔴 Blocking: Coordinate retried payment reversals with confirmation reconciliation — packages/rs-platform-wallet/src/changeset/core_bridge.rs:1193-1197 (thread)
  • 🟡 Suggestion: Resolve retained InstantSend finality for every storage reader — packages/rs-platform-wallet-storage/src/sqlite/schema/core_state.rs:1335-1372 (thread)
  • 🟡 Suggestion: Propagate pending-input lookup failures through the truncation callback — packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:1816-1826 (thread)
  • 🟡 Suggestion: Cancel retained payment reversals when their owning identity is removed — packages/rs-platform-wallet/src/changeset/core_bridge.rs:1193-1200 (thread)
  • 🟡 Suggestion: Retain payment reversals with backend-owned truncations — packages/rs-platform-wallet-storage/src/sqlite/persister.rs:1193-1203 (thread)
  • 🟡 Suggestion: Mark the public Rust struct additions as breaking changes — CHANGELOG.md:100-113 (thread)
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: critical by gpt-6.1-sol (effort low) — This is a large, intricate cross-language change to wallet persistence and coin state that restores or removes spendable outputs across chain reorganizations, directly affecting funds movement and coin availability.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity quota lookup failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — 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 (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `packages/rs-platform-wallet-ffi/src/persistence.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/persistence.rs:6668-6685: Make truncation persistence work after FFI wallet restoration
  The FFI restore path decodes only the host's unconfirmed outgoing transactions; it does not replay ordinary confirmed Core transaction records into key-wallet. After restart, a subsequent fork therefore leaves key-wallet with no in-memory records above the fork, so `truncate_above` cannot emit the removed and retained transaction identities needed by the new persistence callbacks. The host can retain old-branch transaction and coin rows until a later rescan, which fails the PR's stated restart-equivalence goal. #5220 is a relevant follow-up for part of this work, but the current PR is responsible for the advertised reorg-after-restart behavior and the Kotlin path remains uncovered.

In `packages/rs-platform-wallet-storage/src/sqlite/schema/core_state.rs`:
- [BLOCKING] packages/rs-platform-wallet-storage/src/sqlite/schema/core_state.rs:85-88: Apply credit verdicts when re-mining a truncated parent
  (carried; thread: https://github.com/dashpay/platform/pull/5384#discussion_r4526400427)
- [SUGGESTION] packages/rs-platform-wallet-storage/src/sqlite/schema/core_state.rs:1335-1372: Resolve retained InstantSend finality for every storage reader
  (carried; thread: https://github.com/dashpay/platform/pull/5384#discussion_r4252965583)

In `packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt`:
- [BLOCKING] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt:1411-1415: Do not globally demote a shared transaction row from one wallet's truncation
  (carried; thread: https://github.com/dashpay/platform/pull/5384#discussion_r4411730848)
- [BLOCKING] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt:1295-1305: Persist retained transaction input debits in merged truncation rounds
  (carried; thread: https://github.com/dashpay/platform/pull/5384#discussion_r4251865317)

In `packages/rs-platform-wallet/src/changeset/core_bridge.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/changeset/core_bridge.rs:1193-1197: Coordinate retried payment reversals with confirmation reconciliation
  (carried; thread: https://github.com/dashpay/platform/pull/5384#discussion_r4251865308)
- [SUGGESTION] packages/rs-platform-wallet/src/changeset/core_bridge.rs:1193-1200: Cancel retained payment reversals when their owning identity is removed
  (carried; thread: https://github.com/dashpay/platform/pull/5384#discussion_r4252358882)

In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift:1816-1826: Propagate pending-input lookup failures through the truncation callback
  (carried; thread: https://github.com/dashpay/platform/pull/5384#discussion_r4252358886)

In `packages/rs-platform-wallet-storage/src/sqlite/persister.rs`:
- [SUGGESTION] packages/rs-platform-wallet-storage/src/sqlite/persister.rs:1193-1203: Retain payment reversals with backend-owned truncations
  (carried; thread: https://github.com/dashpay/platform/pull/5384#discussion_r4251865297)

In `CHANGELOG.md`:
- [SUGGESTION] CHANGELOG.md:100-113: Mark the public Rust struct additions as breaking changes
  (carried; thread: https://github.com/dashpay/platform/pull/5384#discussion_r4258098852)

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

postponed priority: medium Medium priority waiting-self-review Waiting for the author to post /self-reviewed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants