mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 11:53:39 +00:00
wallet: Replace mapWallet and wtxOrdered with a boost::multi_index #35716
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!35716
Loading…
Reference in a new issue
No description provided.
Delete branch "wallet-mapwallet-multiindex"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
The wallet needs to access transactions both by txid, and by insertion order into the wallet.
mapWalletwas the main container for the wallet transactions, and it was keyed by txid.wtxOrderedwas a secondary container which was keyed by order, and held pointers to theCWalletTxobjects stored inmapWallet. These are replaced by a new boost multi index which indexes on txid and insertion order, allowing us to get rid of the 2 separate containers, and holding raw pointers toCWalletTx.The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.
External sites
Reviews
See the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste
<!--meta-tag:bot-skip-->into the comment that the bot should ignore.Conflicts
Reviewers, this pull request conflicts with the following ones:
WalletBatchwrite failures by achow101)If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.
LLM Linter (✨ experimental)
Possible typos and grammar issues:
src/wallet/migration.cpp:cannot be identified to belong→cannot be identified as belonging[the original phrasing is grammatically broken]Possible places where named args for integral literals may be used (e.g.
func(x, /*named_arg=*/0)in C++, andfunc(x, named_arg=0)in Python):src/wallet/rpc/transactions.cpp:ListTransactions(*pwallet, *it, 0, true, ret, filter_label)src/wallet/rpc/transactions.cpp:ListTransactions(wallet, tx, 0, true, transactions, filter_label, include_change)src/wallet/rpc/transactions.cpp:ListTransactions(wallet, *wtx, -100000000, true, removed, filter_label, include_change)2026-11-24 20:08:38
🚧 At least one of the CI tasks failed.
Task
test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/29296252667/job/86970309393LLM reason (✨ experimental): CI failed because the fuzz build (src/test/fuzz/spend.cpp) stopped with a Clang
-Werror,-Wunused-variableerror for an unusedtxidvariable.Hints
Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:
Possibly due to a silent merge conflict (the changes in this pull request being
incompatible with the current code in the target branch). If so, make sure to rebase on the latest
commit of the target branch.
A sanitizer issue, which can only be found by compiling with the sanitizer and running the
affected test.
An intermittent issue.
Leave a comment here, if you need help tracking down a confusing failure.
Concept ACK. multi_index seems like the right thing to use here. Since this doesn't leak into consensus/node, I don't see the harm in spreading the dependency to wallet.
Getting rid of multi_index for the kernel will require something that essentially re-implements its functionality, and I don't see anything new here that would complicate that implementation.
Note that I'm biased: I'm currently working on such a re-implementation that I hope to propose for v33.
I do have a few requests to make my life easier though.
Firstly, please specify an index for each operation, as opposed to just using
m_txs. What happens behind the scenes in that case is that the first index is used, which is not at all obvious to reviewers. In my rewrite I'm hoping to drop the implicit first index functionality and require an index for each call, as that greatly simplifies the implementation.For ex, rather than
m_txs.find(hash)usem_txs.get<index_by_txid>().find(hash). That also means adding the tag for the txid index, which is currently missing.To simplify that, in
wallet.h, you can do:And in the constructor:
Then everywhere you would use
m_txs, usem_txs_by_txidorm_txs_by_posinstead. That makes the intent much more clear.Here's an example of the mempool conversion to work that way (though I used indices rather than tags, which is uglier):
github.com/theuni/bitcoin@b58ab92f9d.Secondly, please use
extract/insertrather thanmodify. The former is compatible with the std container apis and has familiar (and much simpler) semantics wrt re-insertion failure. I was planning on removing our existingmodifycalls for the same reason, so it'd be nice to not be adding more in the meantime.Hmm,
modifyis nicer though since it doesn't require remembering to re-insert and I find it easier to read. I'm also running into trouble withextractandinsertwhere it doesn't work well for looping over the entire multi index and modifying each item.I've changed all of the
modifytoextracttheninsert, with some changes to the functions that iterate over everything in the wallet. These mainly involved callingCWalletTx::MarkDirty. Since that function only changes non-key mutable members ofCWalletTx, I madeMarkDirtyconst so that it can be called without needing to do theextracttheninsert.Concept ACK
Replace two containers —
mapWallet(std::unordered_map<Txid, CWalletTx>) andwtxOrdered(std::multimap<int64_t, CWalletTx*>— a secondary index with raw pointers intomapWallet) — with a singleboost::multi_index_containerthat owns theCWalletTxobjects and provides both lookups natively. Most importantly, eliminates the raw pointer indirection and the synchronisation burden of keeping two containers in sync.Specifying an index for each operation (rather than leaving it to the implicit first index usage that could be confusing) and the extract/insert pattern (instead of modify) were both implemented as @theuni suggested, for the latter, it required making
MarkDirtyconst (all its changes are to mutable members).PR description nit: This PR used to be dependent on already merged https://github.com/bitcoin/bitcoin/pull/35501 for the CWalletTx constructor changes that are necessary for this.
Left a few inline nits...
shouldn't be
continueinstead ofreturn?same as above, shouldn't be
continue?same as in
SyncMetaData, shouldn't becontinue?I think this is redundant? The caller already holds the lock to
cs_wallet... shouldn't instead defineComputeTimeSmartasEXCLUSIVE_LOCKS_REQUIRED(cs_wallet)?nit: doc is stale...
Fixed, leftovers from the previous approach
Fixed, leftovers from the previous approach
Fixed, leftovers from the previous approach
Done
Fixed, leftovers from the previous approach
ACK
c883fb08c2While checking
ReorderTransactions()specifically (it had no direct test coverage), I found this PR incidentally fixes a real bug onmaster:ReorderTransactions()mutates eachCWalletTx::nOrderPosin place but never toucheswtxOrdered, thestd::multimapused for position-ordered iteration (used bylisttransactions/listsinceblockandComputeTimeSmart). Any tx loaded withnOrderPos == -1(a legacy/unordered record) is keyed at-1inwtxOrderedat load time, and since-1sorts before every real position, it stays stuck at the front of that ordering forever — regardless of the real positionReorderTransactions()later computes. So a legacy wallet needing reorder can return transactions in the wrong order from listtransactions today. (In practice this only triggers for awallet.datold enough to predate order-position tracking — nOrderPos is always assigned before a normal write in every current code path — so it's a narrow, but real, latent bug.)This PR's multi_index refactor makes that bug structurally impossible, since
nOrderPosis the sort key of the ordered index itself — any mutation has to go throughextract()+insert(), which re-sorts automatically.Created a test in b27d3b9b67ae3fe2d101d567c3dc004255021af5 that reproduces this: writes 3 tx records directly to a mock DB, one of them the chronologically newest but with
nOrderPos == -1to simulate the legacy state, then loads the wallet and checks it ends up last when iterated in position order. Confirmed red/green — fails onmaster(order.back()returns the wrong tx), passes on this branch.Also, left a nit...
nit: the
AddToWalletdoc comment landed slightly garbled — "iterator to the recently added wtx pointer or nullopt..." mixes "iterator" and "pointer" and drops the "or updated" that was suggested, even though the function still handles both new and existing txs...Concept ACK
c883fb0This also scratches the itch of renaming/removing the variable name
mapWallet- it was not an intuitive name and didn't represent what the object contained within it.If I retouch
🐙 This pull request conflicts with the target branch and needs rebase.
🚧 At least one of the CI tasks failed.
Task
previous releases: https://github.com/bitcoin/bitcoin/actions/runs/34901174478/job/104167227362LLM reason (✨ experimental): CI failed due to a C++ build error in
src/wallet/wallet.cppwherereturn nullptr;cannot be converted to the expectedstd::optional<...>type (compiler error).Hints
Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:
Possibly due to a silent merge conflict (the changes in this pull request being
incompatible with the current code in the target branch). If so, make sure to rebase on the latest
commit of the target branch.
A sanitizer issue, which can only be found by compiling with the sanitizer and running the
affected test.
An intermittent issue.
Leave a comment here, if you need help tracking down a confusing failure.
Having issue help make the cash reward offered thank U
🐙 This pull request conflicts with the target branch and needs rebase.
2 additional verified findings in the Review report.
🔴 Major ·
AddToWalletdestroys an existing transaction when its update write failsA local database-write failure while updating a known transaction with wallet outputs now frees its
CWalletTx, leavingm_txosreferences that later balance reads dereference.Location:
src/wallet/wallet.cpp:1064(head).🟠 Minor ·
AddToWalletreuses iterators invalidated by extractionAddToWalletretains 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).🟠 Minor ·
CommitTransactiondereferences a missing parent instead of throwingFor a trusted caller supplying an input whose parent is absent,
CommitTransactionnow dereferencesend()instead of throwing; no current in-tree caller producing that input was found.Location:
src/wallet/wallet.cpp:2149(head).🟠 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).🔵 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
AddToWalletcan report success without persisting the synchronized fields.Location:
src/wallet/wallet.cpp:1078(head).🔵 Suggestion · The index aliases lose
cs_walletstatic lock checkingThe preferred
m_txs_by_txidandm_txs_by_posaliases bypass the container'sGUARDED_BY(cs_wallet)annotation; no unlocked access was found.Location:
src/wallet/wallet.h:526(head).Review coverage was incomplete.
Reviewed:
a5c05e1484b3· Review report · Previous reportspermalink
🐙 This pull request conflicts with the target branch and needs rebase.
Looks like the CI unit tests failed, but it is impossible for me to see the actual error in the 5 trillion lines of logs
It’s actually 6 trillion, your download was truncated :p
My clanker claims the job failed because
coinselector_testshit CTest’s 2,400 second timeout. The output contains roughly 357k SQLite trace lines and 100kAddToWalletlines.SelectCoins_testadds 1,000 synthetic coins to the same wallet in each of 100 iterations, and this PR changes those additions from in-memory inserts toAddToWalletcalls that also write to SQLite. The robot suggests reverting this test helper to adding the coins directly to the new in-memory index. That should cut the repeated logging and likely fix the timeout.🐙 This pull request conflicts with the target branch and needs rebase.