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

Open
achow101 wants to merge 4 commits from wallet-mapwallet-multiindex into master AGit
achow101 commented 2026-07-14 00:33:37 +00:00 (Migrated from github.com)

The wallet needs to access transactions both by txid, and by insertion order into the wallet. mapWallet was the main container for the wallet transactions, and it was keyed by txid. wtxOrdered was a secondary container which was keyed by order, and held pointers to the CWalletTx objects stored in mapWallet. 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 to CWalletTx.

The wallet needs to access transactions both by txid, and by insertion order into the wallet. `mapWallet` was the main container for the wallet transactions, and it was keyed by txid. `wtxOrdered` was a secondary container which was keyed by order, and held pointers to the `CWalletTx` objects stored in `mapWallet`. 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 to `CWalletTx`.
DrahtBot commented 2026-07-14 00:33:57 +00:00 (Migrated from github.com)

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.

Type Reviewers
Concept ACK theuni, rkrux
Stale ACK pablomartin4btc

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:

  • #36918 (Witness stacks in serialized form (optimization follow-ups) by sipa)
  • #36909 (kernel: add btck_witness_stack_get_items by pzafonte)
  • #36895 (Keep witness stacks in serialized form in CScriptWitness by sipa)
  • #36859 (wallet: guard null coin control in AvailableCoins TRUC filter by brunoerg)
  • #36825 (wallet: fix migration with watch-only transactions by psychemist)
  • #36823 (wallet, migration: Skip legacy wallet records rather than erasing them, and drop unused record erase functions by achow101)
  • #36398 (wallet: only rebroadcast transactions originating from the wallet by mzumsande)
  • #35998 (wallet: Handle or explicitly ignore WalletBatch write failures by achow101)
  • #35786 (wallet: drop spent parents redundant cache invalidation and notification by furszy)
  • #35294 (wallet: Update tx chain state during loading during AttachChain instead of before by achow101)
  • #35151 (wallet, follow-up: Refactor IsSpent to use HowSpent by musaHaruna)
  • #34909 (wallet, refactor: modularise wallet by extracting out legacy wallet migration by rkrux)
  • #34872 (wallet: fix mixed-input transaction accounting in history RPCs by w0xlt)
  • #30343 (wallet, logging: Replace WalletLogPrintf() with LogInfo() by ryanofsky)
  • #27865 (wallet: Track no-longer-spendable TXOs separately 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++, and func(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

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/35716 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/35716.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/35716#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | Concept ACK | [theuni](https://github.com/bitcoin/bitcoin/pull/35716#issuecomment-4974409897), [rkrux](https://github.com/bitcoin/bitcoin/pull/35716#issuecomment-5427418382) | | Stale ACK | [pablomartin4btc](https://github.com/bitcoin/bitcoin/pull/35716#pullrequestreview-5026667636) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#36918](https://github.com/bitcoin/bitcoin/pull/36918) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36918.svg"></sub> (Witness stacks in serialized form (optimization follow-ups) by sipa) * [#36909](https://github.com/bitcoin/bitcoin/pull/36909) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36909.svg"></sub> (kernel: add btck_witness_stack_get_items by pzafonte) * [#36895](https://github.com/bitcoin/bitcoin/pull/36895) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36895.svg"></sub> (Keep witness stacks in serialized form in CScriptWitness by sipa) * [#36859](https://github.com/bitcoin/bitcoin/pull/36859) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36859.svg"></sub> (wallet: guard null coin control in AvailableCoins TRUC filter by brunoerg) * [#36825](https://github.com/bitcoin/bitcoin/pull/36825) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36825.svg"></sub> (wallet: fix migration with watch-only transactions by psychemist) * [#36823](https://github.com/bitcoin/bitcoin/pull/36823) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36823.svg"></sub> (wallet, migration: Skip legacy wallet records rather than erasing them, and drop unused record erase functions by achow101) * [#36398](https://github.com/bitcoin/bitcoin/pull/36398) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36398.svg"></sub> (wallet: only rebroadcast transactions originating from the wallet by mzumsande) * [#35998](https://github.com/bitcoin/bitcoin/pull/35998) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35998.svg"></sub> (wallet: Handle or explicitly ignore `WalletBatch` write failures by achow101) * [#35786](https://github.com/bitcoin/bitcoin/pull/35786) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35786.svg"></sub> (wallet: drop spent parents redundant cache invalidation and notification by furszy) * [#35294](https://github.com/bitcoin/bitcoin/pull/35294) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35294.svg"></sub> (wallet: Update tx chain state during loading during AttachChain instead of before by achow101) * [#35151](https://github.com/bitcoin/bitcoin/pull/35151) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35151.svg"></sub> (wallet, follow-up: Refactor IsSpent to use HowSpent by musaHaruna) * [#34909](https://github.com/bitcoin/bitcoin/pull/34909) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/34909.svg"></sub> (wallet, refactor: modularise wallet by extracting out legacy wallet migration by rkrux) * [#34872](https://github.com/bitcoin/bitcoin/pull/34872) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/34872.svg"></sub> (wallet: fix mixed-input transaction accounting in history RPCs by w0xlt) * [#30343](https://github.com/bitcoin/bitcoin/pull/30343) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/30343.svg"></sub> (wallet, logging: Replace WalletLogPrintf() with LogInfo() by ryanofsky) * [#27865](https://github.com/bitcoin/bitcoin/pull/27865) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/27865.svg"></sub> (wallet: Track no-longer-spendable TXOs separately 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. <!--5faf32d7da4f0f540f40219e4f7537a3--> ### 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++, and `func(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)` <sup>2026-11-24 20:08:38</sup>
DrahtBot commented 2026-07-14 01:26:20 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/29296252667/job/86970309393
LLM reason (✨ experimental): CI failed because the fuzz build (src/test/fuzz/spend.cpp) stopped with a Clang -Werror,-Wunused-variable error for an unused txid variable.

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.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `test ancestor commits`: https://github.com/bitcoin/bitcoin/actions/runs/29296252667/job/86970309393</sub> <sub>LLM reason (✨ experimental): CI failed because the fuzz build (src/test/fuzz/spend.cpp) stopped with a Clang `-Werror,-Wunused-variable` error for an unused `txid` variable.</sub> <details><summary>Hints</summary> 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. </details>
theuni commented 2026-07-14 22:03:13 +00:00 (Migrated from github.com)

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) use m_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:

WalletTxs m_txs;
WalletTxs::index<index_by_txid>& m_txs_by_txid;
WalletTxs::index<index_by_pos>& m_txs_by_pos;

And in the constructor:

m_txs_by_txid(m_txs.get<index_by_txid>());
m_txs_by_pos(m_txs.get<m_txs_by_pos>());

Then everywhere you would use m_txs, use m_txs_by_txid or m_txs_by_pos instead. 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/insert rather than modify. 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 existing modify calls for the same reason, so it'd be nice to not be adding more in the meantime.

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)` use `m_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: ```c++ WalletTxs m_txs; WalletTxs::index<index_by_txid>& m_txs_by_txid; WalletTxs::index<index_by_pos>& m_txs_by_pos; ``` And in the constructor: ```c++ m_txs_by_txid(m_txs.get<index_by_txid>()); m_txs_by_pos(m_txs.get<m_txs_by_pos>()); ``` Then everywhere you would use `m_txs`, use `m_txs_by_txid` or `m_txs_by_pos` instead. 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): https://github.com/theuni/bitcoin/commit/b58ab92f9d6b231967328f560701d42710e04b92 . --- Secondly, please use `extract`/`insert` rather than `modify`. 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 existing `modify` calls for the same reason, so it'd be nice to not be adding more in the meantime.
achow101 commented 2026-07-17 19:01:13 +00:00 (Migrated from github.com)

Secondly, please use extract/insert rather than modify. 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 existing modify calls for the same reason, so it'd be nice to not be adding more in the meantime.

Hmm, modify is nicer though since it doesn't require remembering to re-insert and I find it easier to read. I'm also running into trouble with extract and insert where it doesn't work well for looping over the entire multi index and modifying each item.

> Secondly, please use `extract`/`insert` rather than `modify`. 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 existing `modify` calls for the same reason, so it'd be nice to not be adding more in the meantime. Hmm, `modify` is nicer though since it doesn't require remembering to re-insert and I find it easier to read. I'm also running into trouble with `extract` and `insert` where it doesn't work well for looping over the entire multi index and modifying each item.
achow101 commented 2026-07-20 21:39:06 +00:00 (Migrated from github.com)

I've changed all of the modify to extract then insert, with some changes to the functions that iterate over everything in the wallet. These mainly involved calling CWalletTx::MarkDirty. Since that function only changes non-key mutable members of CWalletTx, I made MarkDirty const so that it can be called without needing to do the extract then insert.

I've changed all of the `modify` to `extract` then `insert`, with some changes to the functions that iterate over everything in the wallet. These mainly involved calling `CWalletTx::MarkDirty`. Since that function only changes non-key mutable members of `CWalletTx`, I made `MarkDirty` const so that it can be called without needing to do the `extract` then `insert`.
pablomartin4btc (Migrated from github.com) reviewed 2026-08-10 03:01:38 +00:00
pablomartin4btc (Migrated from github.com) left a comment

Concept ACK

Replace two containers — mapWallet (std::unordered_map<Txid, CWalletTx>) and wtxOrdered (std::multimap<int64_t, CWalletTx*> — a secondary index with raw pointers into mapWallet) — with a single boost::multi_index_container that owns the CWalletTx objects 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 MarkDirty const (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...

Concept ACK Replace two containers — `mapWallet` (`std::unordered_map<Txid, CWalletTx>`) and `wtxOrdered` (`std::multimap<int64_t, CWalletTx*>` — a secondary index with raw pointers into `mapWallet`) — with a single `boost::multi_index_container` that owns the `CWalletTx` objects 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 `MarkDirty` const (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...
pablomartin4btc (Migrated from github.com) commented 2026-08-09 23:30:41 +00:00

shouldn't be continue instead of return?

shouldn't be `continue` instead of `return`?
pablomartin4btc (Migrated from github.com) commented 2026-08-09 23:31:17 +00:00

same as above, shouldn't be continue?

same as above, shouldn't be `continue`?
pablomartin4btc (Migrated from github.com) commented 2026-08-09 23:32:35 +00:00

same as in SyncMetaData, shouldn't be continue?

same as in `SyncMetaData`, shouldn't be `continue`?
pablomartin4btc (Migrated from github.com) commented 2026-08-09 23:54:30 +00:00

I think this is redundant? The caller already holds the lock to cs_wallet... shouldn't instead define ComputeTimeSmart as EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)?

I think this is redundant? The caller already holds the lock to `cs_wallet`... shouldn't instead define `ComputeTimeSmart` as `EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)`?
pablomartin4btc (Migrated from github.com) commented 2026-08-09 23:41:12 +00:00

nit: doc is stale...

     * @return iterator to the recently added or updated wtx, or nullopt if there was a db write error.
nit: doc is stale... ```suggestion * @return iterator to the recently added or updated wtx, or nullopt if there was a db write error. ```
achow101 (Migrated from github.com) reviewed 2026-08-12 18:16:53 +00:00
achow101 (Migrated from github.com) commented 2026-08-12 18:16:53 +00:00

Fixed, leftovers from the previous approach

Fixed, leftovers from the previous approach
achow101 (Migrated from github.com) reviewed 2026-08-12 18:16:57 +00:00
achow101 (Migrated from github.com) commented 2026-08-12 18:16:57 +00:00

Fixed, leftovers from the previous approach

Fixed, leftovers from the previous approach
achow101 (Migrated from github.com) reviewed 2026-08-12 18:17:09 +00:00
achow101 (Migrated from github.com) commented 2026-08-12 18:17:09 +00:00

Fixed, leftovers from the previous approach

Fixed, leftovers from the previous approach
achow101 (Migrated from github.com) reviewed 2026-08-12 18:17:15 +00:00
achow101 (Migrated from github.com) commented 2026-08-12 18:17:15 +00:00

Done

Done
achow101 (Migrated from github.com) reviewed 2026-08-12 18:17:20 +00:00
achow101 (Migrated from github.com) commented 2026-08-12 18:17:20 +00:00

Fixed, leftovers from the previous approach

Fixed, leftovers from the previous approach
pablomartin4btc (Migrated from github.com) reviewed 2026-08-26 04:45:27 +00:00
pablomartin4btc (Migrated from github.com) left a comment

ACK c883fb08c2

While checking ReorderTransactions() specifically (it had no direct test coverage), I found this PR incidentally fixes a real bug on master: ReorderTransactions() mutates each CWalletTx::nOrderPos in place but never touches wtxOrdered, the std::multimap used for position-ordered iteration (used by listtransactions/ listsinceblock and ComputeTimeSmart). Any tx loaded with nOrderPos == -1 (a legacy/unordered record) is keyed at -1 in wtxOrdered at load time, and since -1 sorts before every real position, it stays stuck at the front of that ordering forever — regardless of the real position ReorderTransactions() later computes. So a legacy wallet needing reorder can return transactions in the wrong order from listtransactions today. (In practice this only triggers for a wallet.dat old 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 nOrderPos is the sort key of the ordered index itself — any mutation has to go through extract()+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 == -1 to simulate the legacy state, then loads the wallet and checks it ends up last when iterated in position order. Confirmed red/green — fails on master (order.back() returns the wrong tx), passes on this branch.

Also, left a nit...

ACK c883fb08c293dfc2dcaf35322dfda72e946acb98 While checking `ReorderTransactions()` specifically (it had no direct test coverage), I found this PR incidentally fixes a real bug on `master`: `ReorderTransactions()` mutates each `CWalletTx::nOrderPos` in place but never touches `wtxOrdered`, the `std::multimap` used for position-ordered iteration (used by `listtransactions`/ `listsinceblock` and `ComputeTimeSmart`). Any tx loaded with `nOrderPos == -1` (a legacy/unordered record) is keyed at `-1` in `wtxOrdered` at load time, and since `-1` sorts before every real position, it stays stuck at the front of that ordering forever — regardless of the real position `ReorderTransactions()` later computes. So a legacy wallet needing reorder can return transactions in the wrong order from listtransactions today. (In practice this only triggers for a `wallet.dat` old 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 `nOrderPos` is the sort key of the ordered index itself — any mutation has to go through `extract()`+`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 == -1` to simulate the legacy state, then loads the wallet and checks it ends up last when iterated in position order. Confirmed red/green — fails on `master` (`order.back()` returns the wrong tx), passes on this branch. Also, left a nit...
pablomartin4btc (Migrated from github.com) commented 2026-08-26 04:07:01 +00:00

nit: the AddToWallet doc 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...

     * @return iterator to the recently added or updated wtx pointer, or nullopt if there was a db write error.
nit: the `AddToWallet` doc 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... ```suggestion * @return iterator to the recently added or updated wtx pointer, or nullopt if there was a db write error. ```
rkrux commented 2026-08-26 15:19:05 +00:00 (Migrated from github.com)

Concept ACK c883fb0

This 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.

Concept ACK c883fb0 This 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.
achow101 (Migrated from github.com) reviewed 2026-08-26 18:14:53 +00:00
achow101 (Migrated from github.com) commented 2026-08-26 18:14:53 +00:00

If I retouch

If I retouch
DrahtBot commented 2026-09-12 12:02:32 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
DrahtBot commented 2026-09-14 23:02:18 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task previous releases: https://github.com/bitcoin/bitcoin/actions/runs/34901174478/job/104167227362
LLM reason (✨ experimental): CI failed due to a C++ build error in src/wallet/wallet.cpp where return nullptr; cannot be converted to the expected std::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.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `previous releases`: https://github.com/bitcoin/bitcoin/actions/runs/34901174478/job/104167227362</sub> <sub>LLM reason (✨ experimental): CI failed due to a C++ build error in `src/wallet/wallet.cpp` where `return nullptr;` cannot be converted to the expected `std::optional<...>` type (compiler error).</sub> <details><summary>Hints</summary> 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. </details>
adamczykmathew5-netizen commented 2026-09-22 08:36:18 +00:00 (Migrated from github.com)

Having issue help make the cash reward offered thank U

Having issue help make the cash reward offered thank U
DrahtBot commented 2026-09-26 01:02:08 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
First-time contributor

2 additional verified findings in the Review report.

🔴 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).

🟠 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).

🟠 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).

🟠 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 AddToWallet can report success without persisting the synchronized fields.

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

🔵 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).

Review coverage was incomplete.


Reviewed: a5c05e1484b3 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:301f8fac66b8cbe87114981d6600f15187695a2edf245458a232c3958e920add:3329223fb40bbbe44124b0523f0fa08f23650d06836368f60e45a38d2db02971 --> <!-- ralph-base:74f3ed9021e853aa14a402ed0ceef78544c5b4a7 --> <!-- ralph-head:a5c05e1484b3132b5ed7a705410277e8aaf0069f --> <!-- ralph-case:527c56cfcb02527ac9aa934d840fb572bb0fe1f857b0cd67794a4919d8d3c72f --> [2 additional verified findings in the Review report](<https://review.fish.foo/report/35716-a5c05e1484b3132b5ed7a705410277e8aaf0069f-3077-2.html>). **🔴 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`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/a5c05e1484b3132b5ed7a705410277e8aaf0069f/src/wallet/wallet.cpp#L1064>) (head). **🟠 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`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/a5c05e1484b3132b5ed7a705410277e8aaf0069f/src/wallet/wallet.cpp#L1090>) (head). **🟠 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`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/a5c05e1484b3132b5ed7a705410277e8aaf0069f/src/wallet/wallet.cpp#L2149>) (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`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/a5c05e1484b3132b5ed7a705410277e8aaf0069f/src/wallet/wallet.cpp#L1368>) (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 `AddToWallet` can report success without persisting the synchronized fields. Location: [`src/wallet/wallet.cpp:1078`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/a5c05e1484b3132b5ed7a705410277e8aaf0069f/src/wallet/wallet.cpp#L1078>) (head). **🔵 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`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/a5c05e1484b3132b5ed7a705410277e8aaf0069f/src/wallet/wallet.h#L526>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`a5c05e1484b3`](<https://git.fish.foo/bitcoin/bitcoin/commit/a5c05e1484b3132b5ed7a705410277e8aaf0069f>) · [Review report](<https://review.fish.foo/report/35716-a5c05e1484b3132b5ed7a705410277e8aaf0069f-3077-2.html>) · [Previous reports](<https://review.fish.foo/traces/35716/>) [permalink](<https://review.fish.foo/report/35716-a5c05e1484b3132b5ed7a705410277e8aaf0069f-3077-2.html>)
DrahtBot commented 2026-11-24 17:11:47 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
maflcko commented 2026-11-26 11:02:25 +00:00 (Migrated from github.com)

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

<sub>Looks like the CI unit tests failed, but it is [impossible](https://github.com/bitcoin/bitcoin/pull/35139#issuecomment-4904329044) for me to see the actual error in the 5 trillion lines of logs</sub>
l0rinc commented 2026-11-26 13:11:25 +00:00 (Migrated from github.com)

5 trillion lines of logs

It’s actually 6 trillion, your download was truncated :p

My clanker claims the job failed because coinselector_tests hit CTest’s 2,400 second timeout. The output contains roughly 357k SQLite trace lines and 100k AddToWallet lines. SelectCoins_test adds 1,000 synthetic coins to the same wallet in each of 100 iterations, and this PR changes those additions from in-memory inserts to AddToWallet calls 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.

> 5 trillion lines of logs It’s actually 6 trillion, your download was truncated :p My clanker claims the job failed because `coinselector_tests` hit CTest’s 2,400 second timeout. The output contains roughly 357k SQLite trace lines and 100k `AddToWallet` lines. `SelectCoins_test` adds 1,000 synthetic coins to the same wallet in each of 100 iterations, and this PR changes those additions from in-memory inserts to `AddToWallet` calls 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.
DrahtBot commented 2026-11-26 17:43:24 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!35716
No description provided.