Review report

bitcoin/bitcoin: PR #27865

Provider refusals

write_verifier: Provider declined the request because of a cybersecurity restriction. Experiments remain incomplete; static verification can continue.

2 major findings · 5 minor findings · 6 suggestions

Findings

Link

[major] · Rebuilt conflicted outputs reach a fatal balance assertion

Rebuilding the TXO maps or discovering ownership of a retained block-conflicted output puts it in m_txos, so a subsequent balance query aborts the node.

Location: src/wallet/wallet.cpp:4629 (head).

Details and suggested fix

Consider a retained block-conflicted transaction with an owned output and no confirmed spender, such as change from a transaction whose replacement confirmed. An authenticated removeprunedfunds call on another transaction, enabled with -deprecatedrpc=removeprunedfunds, clears both maps and rebuilds them through RefreshAllTXOs. Importdescriptors or keypoolrefill can reach the same insertion when an output of a conflicted transaction becomes newly owned. RefreshTXOsFromTx checks only IsSpent(outpoint, 1), so it inserts that output into m_txos. GetBalance then encounters its negative depth and aborts at Assert(tx_depth >= 0), before balance filtering can exclude it. Reloading rebuilds and prunes the maps, but rescanning the already-recorded conflict does not move the entry because MarkConflicted reports no state change. Use the same definite-unusability predicate for insertion, pruning and restoration: a block-conflicted creator or a confirmed spender. Add balance assertions after removal rebuilding and ownership discovery while a conflicted transaction remains in the wallet.


Link

[major] · Disconnected spends leave valid inputs outside the usable TXO set

After a confirmed spender is disconnected and then abandoned or conflicted through another input, its still-valid inputs can remain missing from balances and automatic coin selection.

Location: src/wallet/wallet.cpp:4702 (head).

Details and suggested fix

When transaction A confirms, AddToWallet moves its input X to m_unusable_txos. Disconnection changes A to non-abandoned TxStateInactive and calls MaybeMarkTXOUsable(X), but the default IsSpent(X) still counts A's depth-zero spend and refuses restoration. Reverse block traversal cannot avoid this self-blocking check. If A subsequently leaves the mempool and is abandoned, or becomes block-conflicted through a different input Y, X becomes genuinely unspent. Those recursive updates move only A's and its descendants' outputs; MarkInputsDirty does not restore X. Balance and available-coin iteration therefore omit X until a wallet reload or RemoveTxs rebuild repairs membership. Base restoration on definite unusability, checking IsSpent(outpoint, 1) and the creating transaction's block-conflicted state rather than unconfirmed spending. Add a no-reload regression that confirms and disconnects a spend, removes it from the mempool, abandons it, and checks the original input in balances and listunspent.


Link

[minor] · Migrated watch-only transactions retain the main wallet's from-me flag

A migrated main-wallet payment to a watched address inherits m_from_me=true in the watch-only wallet, causing gettransaction to report the entire output value as a fee.

Location: src/wallet/wallet.cpp:4048 (head).

Details and suggested fix

ApplyMigrationData sets the source transaction's m_from_me for the main wallet, then serializes that value into copy_wtx. It computes watchonly_from_me only for the inclusion check. For a payment funded solely by main-wallet inputs, the watch-only copy consequently has a true flag and zero debit, so PushTxAmountAndFee reports fee = GetValueOut() and amount = credit - GetValueOut(). In the reverse case, a watch-only spend returning an output to the main wallet can inherit false and omit its fee; its copied TXO coin-eligibility classification is also wrong. The flag is persisted and survives an ordinary synchronized reload, although re-syncing the transaction or refreshing all TXOs can repair it. Set copy_wtx.m_from_me = watchonly_from_me before LoadToWallet, and check both wallets' amount and fee reporting after migration and reload.


Link

[minor] · Migration loses spenders recorded before their parents

For a legacy history with a child recorded before its parent, migration can delete the main wallet's only record of a confirmed spend, causing an already-spent parent output to appear available.

Location: src/wallet/wallet.cpp:4038 (head).

Details and suggested fix

Suppose child C spends a private-key-owned output of P, pays only a watched script, and has a lower nOrderPos than P. Legacy imports and rescans, including child-first importprunedfunds, can create this ordering. After clearing both TXO maps, migration processes C before indexing P's outputs. IsMine(C) and IsFromMe(C) are therefore false for the main wallet, and the watch-only branch queues C for deletion. RemoveTxs also removes C's mapTxSpends entry, so rebuilding the main wallet's inventory makes P's spent output appear unspent. The balance is overstated and automatic selection can choose that already-spent coin. Populate all main-wallet-owned outputs in a separate pass before classifying transactions, as the base's preliminary refresh did. Add a watched-child-before-private-parent migration case. The prevalence of such legacy histories was not measured; a full rescan repairs the main wallet.


Link

[minor] · The from-me upgrade persists flags from an incomplete TXO index

A child recorded before its parent can be upgraded to m_from_me=false and retain that value across reloads, causing gettransaction to omit its fee and include the fee in its reported amount.

Location: src/wallet/walletdb.cpp:1090 (head).

Details and suggested fix

Old records without m_from_me skip TXO caching in LoadToWallet. The upgrade then computes IsFromMe and caches outputs one transaction at a time in wtxOrdered order. If a child precedes its parent, the parent's owned output is not indexed when the child is checked, so false is immediately persisted. Child-first importprunedfunds or a later earlier-start rescan can produce this order. RefreshAllTXOs has the same problem after RemoveTxs clears the maps, and adding a parent at runtime does not recompute already-recorded children. Besides incorrect fee and amount reporting, the copied TXO from-me value used for coin eligibility and address balances is wrong. Populate all owned outputs first, then compute and persist flags and update their TXO copies; also recompute affected spenders when new parent outputs become known. Cover child-first history and a second reload. No affected real-world wallet was examined, so prevalence remains unconfirmed.


Link

[minor] · Failed wallet loads can rewrite transaction records

With a corrupt record and old-format or unordered transactions, LoadTxRecords can durably rewrite readable records before LoadWallet rejects the load.

Location: src/wallet/walletdb.cpp:1088 (head).

Details and suggested fix

LoadRecords keeps processing readable records after a per-record error. LoadTxRecords then upgrades m_from_me and runs ReorderTransactions without checking its accumulated result, while errors from earlier loading stages are also only checked afterwards. For example, a corrupt parent record can leave readable old-format children upgraded and written as not-from-me using an incomplete inventory, even though loading ultimately fails. These writes are not enclosed in a transaction that rolls back on the failed load. This crosses the existing explicit boundary against rewriting or upgrading a corrupt wallet; base reordering ran after that boundary. Keep necessary in-memory initialization during loading, but defer durable flag rewrites and transaction reordering until the aggregate result is LOAD_OK. Add a failure-path test that compares records before and after a rejected load.


Link

[minor] · Chain-connected test wallets retain a shared ownership cycle

CreateSyncedWallet now registers notifications with shared ownership, but its callers only release their external pointers, leaking the test wallets and handlers.

Location: src/wallet/test/util.cpp:26 (head).

Details and suggested fix

CreateNew calls AttachChain, which stores a notifications handler in the wallet. That handler owns a proxy whose m_notifications shared_ptr points back to the wallet, forming wallet → handler → proxy → wallet. ListCoinsTestingSetup only calls wallet.reset(), and SubtractFee and wallet_duplicated_preset_inputs_test let their local pointers expire, so the wallet deleter cannot run. Tear these wallets down with TestUnloadWallet before their chain fixtures are destroyed. Scope the wallet locks so that the helper's notification-queue drain occurs outside cs_wallet, especially in wallet_duplicated_preset_inputs_test.


Optional improvements

Link

[suggestion] · The from-me trust shortcut tests optional engagement

An initialized false m_from_me no longer triggers the early trust rejection, so incoming mempool transactions perform unnecessary parent lookups before the later checks reject them.

Location: src/wallet/receive.cpp:213 (head).

Details and suggested fix

When spending zero-confirmation change is enabled, !wtx->m_from_me tests whether the optional is empty rather than whether its stored value is false. Loading and AddToWallet initialize the optional, making this half of the gate ineffective. The input-ownership loop still rejects incoming transactions, so this is a lost shortcut rather than a trust bypass. Read the contained value, for example with !*Assert(wtx->m_from_me). Land that change together with the stale from-me flag fixes, because the corrected gate will depend on those stored values.


Link

[suggestion] · The upgrade fixture never checks from-me accounting

The new compatibility fixture only receives payments and checks restoration, so it does not distinguish a correct m_from_me upgrade from one that assigns every flag false.

Location: test/functional/wallet_backwards_compatibility.py:291 (head).

Details and suggested fix

Both transactions in test_txs_out_of_order are incoming payments to a newly created wallet, and no amount or fee assertion follows restoration. There is also no child-before-parent dependency despite the helper's name. Have the old wallet create a spend and construct a child-first imported history, then assert gettransaction amount and fee after restoring on master and again after reloading. Also correct the node selection or its label: with eleven nodes, nodes[num_nodes - 5] is index 6, version 240001, while v25 is index 5.


Link

[suggestion] · The coin-listing fixture overwrites the notification state it tests

AddTx manually replaces both transaction and TXO confirmation states immediately before checking them, masking incorrect confirmation metadata delivered through chain notifications.

Location: src/wallet/test/wallet_tests.cpp:500 (head).

Details and suggested fix

CreateSyncedWallet now attaches the wallet to chain notifications, and AddTx drains the validation queue after processing its block. The subsequent SetState call nevertheless replaces the confirmation hash, height and index, and propagates that replacement to the cached TXOs before AvailableCoins or ListCoins observes them. Drop this manual assignment and assert that the notification-produced TxStateConfirmed matches the current tip hash and height with index 1. Keep the downstream coin assertions so they exercise the TXO states delivered by the same notification path.


Link

[suggestion] · Migration writes retained transaction metadata twice

Each retained main-wallet transaction incurs two identical metadata writes during migration.

Location: src/wallet/wallet.cpp:4044 (head).

Details and suggested fix

The new is_mine block writes metadata after setting m_from_me and refreshing TXOs. Every successful iteration retaining that transaction also reaches the existing end-of-iteration WriteTxMetadata, with no intervening change to the source transaction. Remove the earlier write and its comment, retaining RefreshTXOsFromTx, and let the existing final write persist the updated flag.


Link

[suggestion] · TXO move helpers return unused and inconsistently ordered iterators

The helpers maintain unused iterator returns, and MaybeMarkTXOUsable reverses the pair's meaning between its early and normal returns.

Location: src/wallet/wallet.cpp:4708 (head).

Details and suggested fix

Neither caller uses MaybeMarkTXOUsable's result, yet the helper calculates successor and destination iterators solely to return them. Its early return orders the maps differently from its normal return. Make that helper return void and remove the return-only bookkeeping. MarkTXOUnusable only needs to return the next m_txos iterator consumed by PruneSpentTXOs, not a pair. Keep the extract/insert operations, insertion assertions and the source successor needed for safe pruning traversal.


Link

[suggestion] · RefreshAllTXOs carries an unused caller-batch branch

Every caller uses the default null batch, leaving the newly added caller-supplied persistence branch unused.

Location: src/wallet/wallet.cpp:4645 (head).

Details and suggested fix

No caller passes a WalletBatch to RefreshAllTXOs. Remove the defaulted WalletBatch* parameter and the batch->WriteTxMetadata branch, keeping WalletBatch(GetDatabase()).WriteTxMetadata(*wtx) when m_from_me changes. This removes an unused interface and branch without changing current caller behavior.


Coverage details