wallet: Replace mapWallet and wtxOrdered with a boost::multi_index

bitcoin/bitcoin: PR #35716

Provider refusals

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

1 major finding · 3 minor findings · 4 suggestions

Findings

Link

[major] · AddToWallet destroys an existing transaction when its update write fails

A local database-write failure while updating a known transaction with wallet outputs now frees its CWalletTx, leaving m_txos references that later balance reads dereference.

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

Details and suggested fix

CWalletTx::Update throws when WriteWtxVariant or WriteTxMetadata fails. The catch returns std::nullopt before reinserting wtx_nh, so its destructor frees the existing transaction. Unlike the base, this leaves WalletTXO references pointing to a destroyed object and leaves its txid in mapTxSpends. RefreshTXOsFromTx does not replace existing outpoints, so adding the transaction again does not reliably repair those references.

For example, if importprunedfunds confirms an already-known unconfirmed transaction and the metadata write fails, the RPC reports an error while the wallet remains loaded. A following getbalance can access the freed object. Reinsert the node before reporting the error, preferably through an exception-safe ownership guard, and add a fault-injection test covering an existing transaction with wallet outputs.


Link

[minor] · AddToWallet reuses iterators invalidated by extraction

AddToWallet retains invalidated iterators during coinbase abandonment and metadata synchronization, which can assert in Boost safe-mode builds; no current production caller committing a new malleated variant was found.

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

Details and suggested fix

The inactive-coinbase walk queues a spender once for each matching outpoint, without deduplication. A descendant spending two outputs of a visited transaction is queued twice. Its first visit extracts and reinserts the node; the second calls extract(desc_it) through an invalidated iterator. This needs a disconnected coinbase with descendants, readily constructed on regtest but rare on mainnet because of coinbase maturity. The root iterator is also invalidated by the walk and later returned.

Separately, SyncMalleatedTxMetadata extracts each non-donor variant, including a newly added variant with the latest order position. AddToWallet still returns its saved iterator, which CommitTransaction subsequently uses for extraction. Reinsertion does not restore either iterator's validity. The safe-mode assertion is inferred from source, not observed in an experiment. Queue txids with a done set, look them up immediately before extraction, and obtain a fresh return iterator after all helpers finish.


Link

[minor] · CommitTransaction dereferences a missing parent instead of throwing

For a trusted caller supplying an input whose parent is absent, CommitTransaction now dereferences end() instead of throwing; no current in-tree caller producing that input was found.

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

Details and suggested fix

interfaces::Wallet::commitTransaction forwards its transaction directly to this function. When an input's parent is absent, m_txs_by_txid.find() returns end(), but parent_it->MarkDirty() immediately dereferences it and writes cache fields. The base's mapWallet.at() raised an exception instead. Both versions add the transaction before this loop, so this is a regression in failure handling, not a claim that the base could successfully commit such inputs. Check the lookup and raise an explicit exception before dereferencing it.


Link

[minor] · Non-key mutation unnecessarily removes transactions from both indices

Non-key updates repeatedly unlink wallet transactions and impose extra iterator and lifetime obligations, although no affected synchronous observer was found.

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

Details and suggested fix

RecursiveUpdateTxState extracts the transaction before changing its state and emits NotifyTransactionChanged before reinsertion. The interface forwards this signal synchronously, so a listener looking up the signalled txid would find no transaction, unlike the base. The Qt listener queues its read and is not affected. Similar extraction around submission and metadata updates also requires callers to preserve ownership and refresh invalidated iterators. Prefer linked mutation for non-key changes, such as modify() with a non-throwing modifier, and perform fallible writes and notifications afterward. An exception must not escape the modifier because modify() erases the element in that case.


Optional improvements

Link

[suggestion] · Synced variant metadata no longer reaches the checked full write

A new malleated variant's shared metadata now depends on a subsequent unchecked write, so AddToWallet can report success without persisting the synchronized fields.

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

Details and suggested fix

The base called SyncMalleatedTxMetadata before WriteFullTx, so the checked full write included donor fields such as comments, nTimeSmart and m_replaced_by_txid. The head writes the unsynchronized record first, then copies those fields and ignores the result of WriteTxMetadata. If that write fails, the synchronized fields exist only in memory, and loading the wallet does not synchronize them again. For example, a missing replacement marker after restart no longer supplies the corresponding bumpfee rejection. Reinsert the node and run AddToSpends and metadata synchronization before the checked WriteFullTx, preserving the base's ordering.


Link

[suggestion] · The index aliases lose cs_wallet static lock checking

The preferred m_txs_by_txid and m_txs_by_pos aliases bypass the container's GUARDED_BY(cs_wallet) annotation; no unlocked access was found.

Location: src/wallet/wallet.h:526 (head).

Details and suggested fix

The base annotated mapWallet, but the replacement annotates only m_txs while directing callers to use two unannotated reference members. Clang's thread-safety analysis does not infer the underlying container's guard through these aliases. Annotate both references with GUARDED_BY(cs_wallet), or expose them through accessors marked EXCLUSIVE_LOCKS_REQUIRED(cs_wallet), to retain checking at the actual access sites.


Link

[suggestion] · wallet_create_transaction now persists synthetic funding records

Using AddToWallet adds SQLite writes and retains distinct funding records across fuzz inputs until the 1,000-input rebuild; the throughput and memory effects are unmeasured.

Location: src/wallet/test/fuzz/spend.cpp:88 (head).

Details and suggested fix

The funding loop can insert up to 10,000 transactions per input. Each AddToWallet call now writes the order counter, witness variant and transaction metadata. FuzzedWallet::Reset clears the transaction containers but leaves its in-memory SQLite database intact until Build replaces the wallet, so distinct records accumulate between rebuilds. Use LoadToWallet for these synthetic funding transactions instead. It avoids persisting them while still populating spend tracking and wallet outputs needed by CreateTransaction.


Link

[suggestion] · ResubmitWalletTransactions allocates staging for confirmed history

ResubmitWalletTransactions reserves one node-handle slot per wallet transaction even when few or none pass the rebroadcast filters.

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

Details and suggested fix

With wallet broadcasting enabled, to_submit.reserve(m_txs_by_pos.size()) requests capacity proportional to the entire history at startup and on periodic rebroadcast. Confirmed transactions and, unless forcing, recently received transactions are then excluded. Count eligible transactions first and reserve that count before extracting nodes. This preserves position-ordered submission and avoids allocations during extraction without allocating staging space for confirmed history.


Coverage details

Background

Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.

Documented decisions

Transaction reordering exists for compatibility with old wallets, not merely as a convenient presentation sort. In the historical discussion, participants explicitly opposed removing the conversion at the expense of old-wallet compatibility and argued that an upgraded wallet should subsequently behave like a new wallet.

The pinned base retains the warning that changing ReorderTransactions output is probably a bad idea. Its algorithm assigns positions to previously unordered transactions and offsets existing positions rather than simply renumbering everything by time. These are compatibility-sensitive persisted values affected by the refactor's extraction and reindexing.

Source 1 · Source 2 · Source 3

Wallet insertion order is used for transaction resubmission to avoid submitting children before their unconfirmed parents. The original startup-ordering proposal explains that out-of-order children appear to have missing inputs; the later rebroadcast proposal applies the same ordering to periodic resubmission. The earlier discussion also cautions that nOrderPos is not necessarily a universal dependency order.

The pinned base first collects pointers to eligible wallet transactions, sorts them by wallet order, and then submits them while they remain in the wallet. The refactor changes both this staging mechanism and transaction residency during submission. The historical requirement concerns successful resubmission of transaction chains, not merely matching listtransactions presentation order.

Source 1 · Source 2 · Source 3

An AddToWallet database-write failure is intended to be reported as an error rather than treated as successful transaction commitment. The historical CommitTransaction change also explicitly relies on AddToWallet returning the actual inserted CWalletTx pointer, eliminating another lookup.

This establishes that AddToWallet's return value represents both access to the canonical wallet transaction and persistence success. It does not establish that failure rolls back memory: the pinned base returns failure without removing the entry. Error reporting and in-memory rollback are therefore separate questions.

Source 1

Ralph's inferences

The base's update callback operates on the canonical, discoverable wallet entry, not on an unindexed temporary. AddToWallet inserts or finds the entry before invoking update_wtx and retains that same object through later bookkeeping and notifications.

The head invokes update_wtx after extracting the transaction from the indices. Canonical object identity and discoverability by txid are distinct properties: retaining the object alone does not reproduce the base's lookup visibility during the callback. The inspected history did not establish whether every callback is entitled to perform such a lookup.

State-change notifications in the base occur while the changed transaction remains indexed. RecursiveUpdateTxState continues using its CWalletTx reference after notification, and the wallet interface forwards the transaction-change signal directly to the registered client function with a txid and change type rather than a transaction snapshot.

These call paths make both transaction discoverability to observers and continued usability of the caller's reference relevant compatibility assumptions. The evidence supports this concrete execution pattern, not a blanket guarantee that arbitrary callbacks may erase transactions or that every wallet iterator remains valid across every operation.

The base's rebroadcast staging preserves resident wallet objects: it collects CWalletTx pointers and subsequently submits those objects without removing them from the wallet. Thus the selected transactions remain discoverable throughout the submission loop, and the selected pointers are used across successive submissions.

This is the existing lifetime and visibility behavior against which extraction-based staging must be understood. The inspected record establishes the ordering motivation, but does not establish a separate historical promise about all references, iterators, or reentrant callbacks during broadcast.

Source 1

Persisted order positions are not treated as a uniqueness constraint by the base's ordered container: AddToWallet and LoadToWallet populate a multimap, and reordering adjusts existing values rather than enforcing unique consecutive positions. Malleated-variant metadata selection separately chooses the smallest nOrderPos and intentionally excludes nTimeReceived, nOrderPos, and cached members from copying.

Compatibility includes accepting legacy ordering data and preserving the distinction between variant-specific arrival/order information and shared metadata. The base synchronizes the selected metadata after computing the new transaction's smart time and before its full database write; the head moves that synchronization after the full write. No inspected source specifies which variant must win an equal-position tie.

A failed new-transaction write in the base does not undo the insertion or all preceding bookkeeping. At that return point, the transaction remains in mapWallet and wtxOrdered; its receive time, order position and smart time have been assigned; spend indexing, malleated-metadata synchronization, and the birth-time update have already run. The order counter has also advanced. Output-cache refresh and the normal transaction notification occur later and are not reached on that failure path.

This precisely bounds the existing non-atomic failure behavior affected by reordered bookkeeping and node ownership. It should not be interpreted as proof that every retained side effect was deliberately designed or that database and memory remain fully consistent after failure.

Other base mutation paths likewise retain memory changes despite persistence failure: MarkReplaced keeps replacement markers and refreshed mempool status, continues updating variants, and notifies even when a metadata write fails; ReorderTransactions returns LOAD_FAIL without reverting positions and counter changes already made; RecursiveUpdateTxState does not condition its state changes or notifications on metadata-write success.

The affected subsystem does not have a uniform 'failed write means unchanged memory' contract. Transaction residency, already-applied metadata, and cache/notification progress must be considered separately when interpreting the refactor's failure paths. Historical intent for these retention choices remains unverified.