wallet: Update tx chain state during loading during AttachChain instead of before #35294

Open
achow101 wants to merge 2 commits from wallet-chain-load-inconsistency into master AGit
achow101 commented 2026-05-15 00:15:10 +00:00 (Migrated from github.com)

When loading a wallet, updating the state based on the chain data prior to AttachChain results in some blocks being missed, which leads to inconsistent state information that can cause assertion failures. Moving the state updating inside of AttachChain after the chain notifications handler has been attached ensures that the state will always be up to date with the tip that the wallet is tracking.

Fixes #34599

When loading a wallet, updating the state based on the chain data prior to `AttachChain` results in some blocks being missed, which leads to inconsistent state information that can cause assertion failures. Moving the state updating inside of `AttachChain` after the chain notifications handler has been attached ensures that the state will always be up to date with the tip that the wallet is tracking. Fixes #34599
DrahtBot commented 2026-05-15 00:15:20 +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 rkrux, pablomartin4btc
Stale ACK shuv-amp, dergoegge

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:

  • #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.

<!--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/35294 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/35294.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/35294#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 | [rkrux](https://github.com/bitcoin/bitcoin/pull/35294#pullrequestreview-4319186215), [pablomartin4btc](https://github.com/bitcoin/bitcoin/pull/35294#pullrequestreview-4876826921) | | Stale ACK | [shuv-amp](https://github.com/bitcoin/bitcoin/pull/35294#issuecomment-4485703303), [dergoegge](https://github.com/bitcoin/bitcoin/pull/35294#pullrequestreview-4772211961) | 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: * [#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-->
shuv-amp commented 2026-05-19 08:08:59 +00:00 (Migrated from github.com)

ACK 18bc686c6e97fb5522a93412240ddca99057f1b7

Reviewed the change and tested locally.

Moving the tx state update out of LoadToWallet() makes sense to me. During DB
load, the wallet may already have a chain pointer, but it is not yet registered
for chain notifications. In AttachChain(), notifications are registered before
the state update and any needed rescan, so the wallet no longer updates tx
states against a chain tip that can move without the wallet seeing the
intervening block connections.

The new test fails on the pre-fix parent (ddb94fd3e1) with a wallet transaction
still reporting 0 confirmations after restart, and passes on this PR head:

test/functional/wallet_chain_reprocess.py --configfile=$PWD/build/test/config.ini --timeout-factor=4
ACK 18bc686c6e97fb5522a93412240ddca99057f1b7 Reviewed the change and tested locally. Moving the tx state update out of `LoadToWallet()` makes sense to me. During DB load, the wallet may already have a chain pointer, but it is not yet registered for chain notifications. In `AttachChain()`, notifications are registered before the state update and any needed rescan, so the wallet no longer updates tx states against a chain tip that can move without the wallet seeing the intervening block connections. The new test fails on the pre-fix parent (`ddb94fd3e1`) with a wallet transaction still reporting 0 confirmations after restart, and passes on this PR head: ```bash test/functional/wallet_chain_reprocess.py --configfile=$PWD/build/test/config.ini --timeout-factor=4
rkrux (Migrated from github.com) reviewed 2026-05-19 13:12:43 +00:00
rkrux (Migrated from github.com) left a comment

Concept ACK 18bc686c6e97fb5522a93412240ddca99057f1b7

This is indeed quite a subtle and peculiar issue!

Concept ACK 18bc686c6e97fb5522a93412240ddca99057f1b7 This is indeed quite a subtle and peculiar issue!
rkrux (Migrated from github.com) commented 2026-05-19 13:06:32 +00:00
-        #self.extra_args = [["-checkblockindex=0"]]
```diff - #self.extra_args = [["-checkblockindex=0"]] ```
rkrux (Migrated from github.com) commented 2026-05-19 13:08:25 +00:00
-        self.nodes[0].createwallet("target", load_on_startup=False)
+        self.nodes[0].createwallet("target")

This argument doesn't seem necessary.

```diff - self.nodes[0].createwallet("target", load_on_startup=False) + self.nodes[0].createwallet("target") ``` This argument doesn't seem necessary.
rkrux (Migrated from github.com) commented 2026-05-19 13:08:42 +00:00

Is there a particular reason to mine 1000 blocks?

Is there a particular reason to mine 1000 blocks?
rkrux (Migrated from github.com) reviewed 2026-05-19 14:11:30 +00:00
rkrux (Migrated from github.com) commented 2026-05-19 14:11:30 +00:00

After loading updating the state of all txs

This doesn't seem entirely correct now because the state of all transactions are not updated due to the following abandon call being present in the same loop that also updates the transaction state.

> After loading updating the state of all txs This doesn't seem entirely correct now because the state of all transactions are not updated due to the following abandon call being present in the same loop that also updates the transaction state.
rkrux (Migrated from github.com) reviewed 2026-05-19 14:31:44 +00:00
rkrux (Migrated from github.com) commented 2026-05-19 14:31:44 +00:00

updating the state based on the chain data prior to AttachChain results in some blocks being missed

I believe the broad reason is to make the processing of few blocks by the wallet to be missed (on master without the fix here). Ultimately, this can happen as long as there are enough blocks for the node to process (post an unclean shutdown) so that block processing keeps on happening even after the loading of wallet (for the sync_all to come into effect).

For which I think a lower number can also be sufficient - 100 works on my system. I checked it by comparing the node's chain height right before the sync_all call on line 56 and the node's chain height before the unclean shutdown - it showed a more than 50 block difference.

Either way, it would be very helpful to mention the reason as a comment in the test here for review and future reference.

> updating the state based on the chain data prior to AttachChain results in some blocks being missed I believe the broad reason is to make the processing of few blocks by the wallet to be missed (on master without the fix here). Ultimately, this can happen as long as there are enough blocks for the node to process (post an unclean shutdown) so that block processing keeps on happening even after the loading of wallet (for the sync_all to come into effect). For which I think a lower number can also be sufficient - 100 works on my system. I checked it by comparing the node's chain height right before the sync_all call on line 56 and the node's chain height before the unclean shutdown - it showed a more than 50 block difference. Either way, it would be very helpful to mention the reason as a comment in the test here for review and future reference.
achow101 (Migrated from github.com) reviewed 2026-05-19 19:01:01 +00:00
achow101 (Migrated from github.com) commented 2026-05-19 19:01:01 +00:00

Removed

Removed
achow101 (Migrated from github.com) reviewed 2026-05-19 19:01:06 +00:00
achow101 (Migrated from github.com) commented 2026-05-19 19:01:06 +00:00

Removed

Removed
achow101 (Migrated from github.com) reviewed 2026-05-19 19:02:22 +00:00
achow101 (Migrated from github.com) commented 2026-05-19 19:02:22 +00:00

Yes, it's so that there's enough blocks that on the restart, the node is still processing blocks while and after the wallet is loading. I chose 1000 because that was a number very likely to trigger the problem.

Added a comment and reduced to 100.

Yes, it's so that there's enough blocks that on the restart, the node is still processing blocks while and after the wallet is loading. I chose 1000 because that was a number very likely to trigger the problem. Added a comment and reduced to 100.
achow101 (Migrated from github.com) reviewed 2026-05-19 19:02:29 +00:00
achow101 (Migrated from github.com) commented 2026-05-19 19:02:29 +00:00

Updated

Updated
fanquake commented 2026-05-21 10:10:17 +00:00 (Migrated from github.com)

@dergoegge CI is passing now, so can run through Antithesis?

@dergoegge CI is passing now, so can run through Antithesis?
dergoegge commented 2026-05-21 10:27:04 +00:00 (Migrated from github.com)

so can run through Antithesis?

Running

> so can run through Antithesis? Running
dergoegge (Migrated from github.com) approved these changes 2026-05-22 12:40:26 +00:00
dergoegge (Migrated from github.com) left a comment

tACK 4de5c3b692b6958b36451a0bd6ac368f8f605b4f

This fixes the issue.

tACK 4de5c3b692b6958b36451a0bd6ac368f8f605b4f This fixes the issue.
rkrux (Migrated from github.com) reviewed 2026-05-25 12:43:35 +00:00
rkrux (Migrated from github.com) left a comment

LGTM broadly 4de5c3b692b6958b36451a0bd6ac368f8f605b4f.

Few minor suggestions.

LGTM broadly 4de5c3b692b6958b36451a0bd6ac368f8f605b4f. Few minor suggestions.
rkrux (Migrated from github.com) commented 2026-05-25 11:23:51 +00:00

In 4de5c3b692b6958b36451a0bd6ac368f8f605b4f "test: Check all wallet tx states are correct after unclean shutdown"

s/1000/100
s/sufficiednt/sufficient

In 4de5c3b692b6958b36451a0bd6ac368f8f605b4f "test: Check all wallet tx states are correct after unclean shutdown" s/1000/100 s/sufficiednt/sufficient
rkrux (Migrated from github.com) commented 2026-05-25 12:34:44 +00:00

In 4de5c3b "test: Check all wallet tx states are correct after unclean shutdown"

Nit: I don't believe unloading the wallet is necessary because all the blocks contain wallet transaction so the best block will be written to disk on every block connected notification just like unloading the wallet would do.

-        wallet.unloadwallet()
In 4de5c3b "test: Check all wallet tx states are correct after unclean shutdown" Nit: I don't believe unloading the wallet is necessary because all the blocks contain wallet transaction so the best block will be written to disk on every block connected notification just like unloading the wallet would do. ```diff - wallet.unloadwallet() ```
rkrux (Migrated from github.com) commented 2026-05-25 12:37:25 +00:00

Considering the subtleness of the issue, can we add few assertions here to make it explicit for the reader regarding node/wallet height states? Maybe the following diff:

diff --git a/test/functional/wallet_chain_reprocess.py b/test/functional/wallet_chain_reprocess.py
index be4c748fca..1158fa964c 100755
--- a/test/functional/wallet_chain_reprocess.py
+++ b/test/functional/wallet_chain_reprocess.py
@@ -45,13 +45,20 @@ class WalletChainReprocess(BitcoinTestFramework):
 
         # Sync nodes, kill node 0, and restart
         self.sync_all()
+        node_chain_height_before_kill = self.nodes[0].getblockchaininfo()["blocks"]
+        wallet_scan_height_before_kill = wallet.getwalletinfo()["lastprocessedblock"]["height"]
+        assert_equal(wallet_scan_height_before_kill, node_chain_height_before_kill)
         self.nodes[0].kill_process()
         self.start_node(0)
         self.connect_nodes(0, 1)
+        node_chain_height_after_kill = self.nodes[0].getblockchaininfo()["blocks"]
+        assert_greater_than(node_chain_height_before_kill, node_chain_height_after_kill)
+        assert_greater_than(wallet_scan_height_before_kill, node_chain_height_after_kill)
 
         self.nodes[0].loadwallet("target")
         wallet = self.nodes[0].get_wallet_rpc("target")
+        wallet_scan_height_after_kill = wallet.getwalletinfo()["lastprocessedblock"]["height"]
+        assert_greater_than(wallet_scan_height_before_kill, wallet_scan_height_after_kill)
 
         # Wait for node0 to be synced
         self.sync_all()
Considering the subtleness of the issue, can we add few assertions here to make it explicit for the reader regarding node/wallet height states? Maybe the following diff: ```diff diff --git a/test/functional/wallet_chain_reprocess.py b/test/functional/wallet_chain_reprocess.py index be4c748fca..1158fa964c 100755 --- a/test/functional/wallet_chain_reprocess.py +++ b/test/functional/wallet_chain_reprocess.py @@ -45,13 +45,20 @@ class WalletChainReprocess(BitcoinTestFramework): # Sync nodes, kill node 0, and restart self.sync_all() + node_chain_height_before_kill = self.nodes[0].getblockchaininfo()["blocks"] + wallet_scan_height_before_kill = wallet.getwalletinfo()["lastprocessedblock"]["height"] + assert_equal(wallet_scan_height_before_kill, node_chain_height_before_kill) self.nodes[0].kill_process() self.start_node(0) self.connect_nodes(0, 1) + node_chain_height_after_kill = self.nodes[0].getblockchaininfo()["blocks"] + assert_greater_than(node_chain_height_before_kill, node_chain_height_after_kill) + assert_greater_than(wallet_scan_height_before_kill, node_chain_height_after_kill) self.nodes[0].loadwallet("target") wallet = self.nodes[0].get_wallet_rpc("target") + wallet_scan_height_after_kill = wallet.getwalletinfo()["lastprocessedblock"]["height"] + assert_greater_than(wallet_scan_height_before_kill, wallet_scan_height_after_kill) # Wait for node0 to be synced self.sync_all() ```
achow101 (Migrated from github.com) reviewed 2026-05-26 19:35:20 +00:00
achow101 (Migrated from github.com) commented 2026-05-26 19:35:20 +00:00

Since the tests run with -unsafesqlitesync, not all data will be flushed at any given time. While we don't currently fsync everything on a wallet close (we probably should though), unloading the wallet at least calls sqlite3_close which should help to guarantee that all of the wallet data is persisted. My main concern is that killing the process while the wallet is loaded might result in data loss which could cause the test to fail intermittently or behave unexepctedly. Unloading the wallet should help mitigate such issues.

Since the tests run with `-unsafesqlitesync`, not all data will be flushed at any given time. While we don't currently `fsync` everything on a wallet close (we probably should though), unloading the wallet at least calls `sqlite3_close` which should help to guarantee that all of the wallet data is persisted. My main concern is that killing the process while the wallet is loaded might result in data loss which could cause the test to fail intermittently or behave unexepctedly. Unloading the wallet should help mitigate such issues.
achow101 (Migrated from github.com) reviewed 2026-05-26 19:52:59 +00:00
achow101 (Migrated from github.com) commented 2026-05-26 19:52:59 +00:00

Done

Done
achow101 (Migrated from github.com) reviewed 2026-05-26 19:53:04 +00:00
achow101 (Migrated from github.com) commented 2026-05-26 19:53:04 +00:00

Done

Done
maflcko (Migrated from github.com) reviewed 2026-05-28 08:30:30 +00:00
maflcko (Migrated from github.com) commented 2026-05-28 08:30:30 +00:00

https://github.com/bitcoin/bitcoin/actions/runs/26480361555/job/77976026440?pr=35294#step:9:3403:

216/469 - wallet_chain_reprocess.py failed, Duration: 3 s

stdout:
2026-05-26T23:34:49.429029Z TestFramework (INFO): PRNG seed is: 2150906247185331291
2026-05-26T23:34:49.429675Z TestFramework (INFO): Initializing test directory /Users/runner/work/bitcoin/bitcoin/repo_archive/ci/scratch_ ₿🧪_/test_runner/test_runner_₿_🏃_20260526_232554/wallet_chain_reprocess_251
2026-05-26T23:34:49.962081Z TestFramework (INFO): Testing that all blocks are reprocessed by the wallet after an unclean shutdown
2026-05-26T23:34:52.293951Z TestFramework (ERROR): Unexpected exception:
Traceback (most recent call last):
  File "/Users/runner/work/bitcoin/bitcoin/repo_archive/test/functional/test_framework/test_framework.py", line 143, in main
    self.run_test()
    ~~~~~~~~~~~~~^^
  File "/Users/runner/work/bitcoin/bitcoin/repo_archive/ci/scratch_ ₿🧪_/build-aarch64-apple-darwin24.6.0/test/functional/wallet_chain_reprocess.py", line 76, in run_test
    self.test_process_all_blocks_after_unclean()
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^
  File "/Users/runner/work/bitcoin/bitcoin/repo_archive/ci/scratch_ ₿🧪_/build-aarch64-apple-darwin24.6.0/test/functional/wallet_chain_reprocess.py", line 56, in test_process_all_blocks_after_unclean
    assert_greater_than(tip_height, restart_tip_height)
    ~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/runner/work/bitcoin/bitcoin/repo_archive/test/functional/test_framework/util.py", line 96, in assert_greater_than
    raise AssertionError("%s <= %s" % (str(thing1), str(thing2)))
AssertionError: 302 <= 302
https://github.com/bitcoin/bitcoin/actions/runs/26480361555/job/77976026440?pr=35294#step:9:3403: ``` 216/469 - wallet_chain_reprocess.py failed, Duration: 3 s stdout: 2026-05-26T23:34:49.429029Z TestFramework (INFO): PRNG seed is: 2150906247185331291 2026-05-26T23:34:49.429675Z TestFramework (INFO): Initializing test directory /Users/runner/work/bitcoin/bitcoin/repo_archive/ci/scratch_ ₿🧪_/test_runner/test_runner_₿_🏃_20260526_232554/wallet_chain_reprocess_251 2026-05-26T23:34:49.962081Z TestFramework (INFO): Testing that all blocks are reprocessed by the wallet after an unclean shutdown 2026-05-26T23:34:52.293951Z TestFramework (ERROR): Unexpected exception: Traceback (most recent call last): File "/Users/runner/work/bitcoin/bitcoin/repo_archive/test/functional/test_framework/test_framework.py", line 143, in main self.run_test() ~~~~~~~~~~~~~^^ File "/Users/runner/work/bitcoin/bitcoin/repo_archive/ci/scratch_ ₿🧪_/build-aarch64-apple-darwin24.6.0/test/functional/wallet_chain_reprocess.py", line 76, in run_test self.test_process_all_blocks_after_unclean() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^ File "/Users/runner/work/bitcoin/bitcoin/repo_archive/ci/scratch_ ₿🧪_/build-aarch64-apple-darwin24.6.0/test/functional/wallet_chain_reprocess.py", line 56, in test_process_all_blocks_after_unclean assert_greater_than(tip_height, restart_tip_height) ~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/runner/work/bitcoin/bitcoin/repo_archive/test/functional/test_framework/util.py", line 96, in assert_greater_than raise AssertionError("%s <= %s" % (str(thing1), str(thing2))) AssertionError: 302 <= 302
achow101 (Migrated from github.com) reviewed 2026-05-28 18:43:31 +00:00
achow101 (Migrated from github.com) commented 2026-05-28 18:43:31 +00:00

Hopefully fixed

Hopefully fixed
l0rinc (Migrated from github.com) approved these changes 2026-06-05 16:07:41 +00:00
l0rinc (Migrated from github.com) left a comment

I just jumped here for a different reason, the change makes high-level sense, but I'm not well-versed enough with the details to provide a more meaningful review, left two nits.

I just jumped here for a different reason, the change makes high-level sense, but I'm not well-versed enough with the details to provide a more meaningful review, left two nits.
l0rinc (Migrated from github.com) commented 2026-06-05 15:48:18 +00:00

1a35042 wallet: Update tx chain state after chain notifications are attached:

Do we need the reverse traversal here, or could we do the state updates and abandonments in separate passes instead? It seems simpler to first update every transaction state, then run the inactive coinbase abandonment pass afterward.

diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp
--- a/src/wallet/wallet.cpp	(revision d33afaf84e54c0262f3b6f1e93ac2edf877747de)
+++ b/src/wallet/wallet.cpp	(revision 866e54d2e3f0851256950ad6c737c6032f67527d)
@@ -76,7 +76,6 @@
 #include <condition_variable>
 #include <exception>
 #include <optional>
-#include <ranges>
 #include <stdexcept>
 #include <thread>
 #include <tuple>
@@ -3254,17 +3253,18 @@
         walletInstance->SetLastBlockProcessedInMem(-1, uint256());
     }
 
-    // Update the state of every transaction now that we are connected to the chain
-    // Do this in reverse order to ensure that any abandoning will work recursively
-    for (auto& [_, wtx] : std::ranges::reverse_view(walletInstance->wtxOrdered)) {
-        wtx->updateState(chain);
-        // After updating the state of the tx, abandon if it is a coinbase that is no longer in the active chain.
-        // This could happen during an external wallet load, or if the user replaced the chain data.
-        if (wtx->IsCoinBase() && wtx->isInactive()) {
-            walletInstance->AbandonTransaction(*wtx);
+    // Update the state of every transaction now that we are connected to the chain.
+    for (auto& [_, wtx] : walletInstance->mapWallet) {
+        wtx.updateState(chain);
+    }
+
+    // After updating all tx records, abandon any coinbase that is no longer in the active chain.
+    // This could happen during an external wallet load, or if the user replaced the chain data.
+    for (auto& [_, wtx] : walletInstance->mapWallet) {
+        if (wtx.IsCoinBase() && wtx.isInactive()) {
+            walletInstance->AbandonTransaction(wtx);
         }
     }
-
 
     if (tip_height && *tip_height != rescan_height)
     {
> [1a35042](https://github.com/bitcoin/bitcoin/pull/35294/changes/1a35042f5a31550631be63fb3a0a70fcb6899840) _wallet: Update tx chain state after chain notifications are attached_: Do we need the reverse traversal here, or could we do the state updates and abandonments in separate passes instead? It seems simpler to first update every transaction state, then run the inactive coinbase abandonment pass afterward. ```patch diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp --- a/src/wallet/wallet.cpp (revision d33afaf84e54c0262f3b6f1e93ac2edf877747de) +++ b/src/wallet/wallet.cpp (revision 866e54d2e3f0851256950ad6c737c6032f67527d) @@ -76,7 +76,6 @@ #include <condition_variable> #include <exception> #include <optional> -#include <ranges> #include <stdexcept> #include <thread> #include <tuple> @@ -3254,17 +3253,18 @@ walletInstance->SetLastBlockProcessedInMem(-1, uint256()); } - // Update the state of every transaction now that we are connected to the chain - // Do this in reverse order to ensure that any abandoning will work recursively - for (auto& [_, wtx] : std::ranges::reverse_view(walletInstance->wtxOrdered)) { - wtx->updateState(chain); - // After updating the state of the tx, abandon if it is a coinbase that is no longer in the active chain. - // This could happen during an external wallet load, or if the user replaced the chain data. - if (wtx->IsCoinBase() && wtx->isInactive()) { - walletInstance->AbandonTransaction(*wtx); + // Update the state of every transaction now that we are connected to the chain. + for (auto& [_, wtx] : walletInstance->mapWallet) { + wtx.updateState(chain); + } + + // After updating all tx records, abandon any coinbase that is no longer in the active chain. + // This could happen during an external wallet load, or if the user replaced the chain data. + for (auto& [_, wtx] : walletInstance->mapWallet) { + if (wtx.IsCoinBase() && wtx.isInactive()) { + walletInstance->AbandonTransaction(wtx); } } - if (tip_height && *tip_height != rescan_height) { ```
l0rinc (Migrated from github.com) commented 2026-06-05 15:58:31 +00:00

Can we also check that the wallet's processed block has caught back up to the node tip after the restart catch-up path?

diff --git a/test/functional/wallet_chain_reprocess.py b/test/functional/wallet_chain_reprocess.py
--- a/test/functional/wallet_chain_reprocess.py	(revision 866e54d2e3f0851256950ad6c737c6032f67527d)
+++ b/test/functional/wallet_chain_reprocess.py	(revision 6c6e9e004a4c698a4a1a691d1fb09863271d173f)
@@ -62,6 +62,7 @@
 
         # Wait for node0 to be synced
         self.sync_all()
+        assert_equal(wallet.getwalletinfo()["lastprocessedblock"]["height"], self.nodes[0].getblockchaininfo()["blocks"])
 
         # Check every transaction is confirmed
         for txid in txids:
Can we also check that the wallet's processed block has caught back up to the node tip after the restart catch-up path? ```patch diff --git a/test/functional/wallet_chain_reprocess.py b/test/functional/wallet_chain_reprocess.py --- a/test/functional/wallet_chain_reprocess.py (revision 866e54d2e3f0851256950ad6c737c6032f67527d) +++ b/test/functional/wallet_chain_reprocess.py (revision 6c6e9e004a4c698a4a1a691d1fb09863271d173f) @@ -62,6 +62,7 @@ # Wait for node0 to be synced self.sync_all() + assert_equal(wallet.getwalletinfo()["lastprocessedblock"]["height"], self.nodes[0].getblockchaininfo()["blocks"]) # Check every transaction is confirmed for txid in txids: ```
achow101 (Migrated from github.com) reviewed 2026-06-05 18:45:36 +00:00
achow101 (Migrated from github.com) commented 2026-06-05 18:45:36 +00:00

We want to minimize iterating the entire set of transactions since there can be a lot of them, and be very slow. Iterating in reverse order allows us to do both at the same time.

We want to minimize iterating the entire set of transactions since there can be a lot of them, and be very slow. Iterating in reverse order allows us to do both at the same time.
achow101 (Migrated from github.com) reviewed 2026-06-05 18:47:16 +00:00
achow101 (Migrated from github.com) commented 2026-06-05 18:47:16 +00:00

Done

Done
DrahtBot (Migrated from github.com) reviewed 2026-06-10 15:08:14 +00:00
DrahtBot (Migrated from github.com) commented 2026-06-10 15:08:14 +00:00
Unexpected exception:
Traceback (most recent call last):
  File "/Users/runner/work/bitcoin/bitcoin/repo_archive/test/functional/test_framework/test_framework.py", line 144, in main
    self.run_test()
    ~~~~~~~~~~~~~^^
  File "/Users/runner/work/bitcoin/bitcoin/repo_archive/ci/scratch_ ₿🧪_/build-aarch64-apple-darwin24.6.0/test/functional/wallet_chain_reprocess.py", line 77, in run_test
    self.test_process_all_blocks_after_unclean()
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^
  File "/Users/runner/work/bitcoin/bitcoin/repo_archive/ci/scratch_ ₿🧪_/build-aarch64-apple-darwin24.6.0/test/functional/wallet_chain_reprocess.py", line 61, in test_process_all_blocks_after_unclean
    assert_greater_than(wallet_height, wallet.getwalletinfo()["lastprocessedblock"]["height"])
    ~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

https://github.com/bitcoin/bitcoin/actions/runs/27033707370/job/79792231964?pr=35294#step:9:3388

``` Unexpected exception: Traceback (most recent call last): File "/Users/runner/work/bitcoin/bitcoin/repo_archive/test/functional/test_framework/test_framework.py", line 144, in main self.run_test() ~~~~~~~~~~~~~^^ File "/Users/runner/work/bitcoin/bitcoin/repo_archive/ci/scratch_ ₿🧪_/build-aarch64-apple-darwin24.6.0/test/functional/wallet_chain_reprocess.py", line 77, in run_test self.test_process_all_blocks_after_unclean() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^ File "/Users/runner/work/bitcoin/bitcoin/repo_archive/ci/scratch_ ₿🧪_/build-aarch64-apple-darwin24.6.0/test/functional/wallet_chain_reprocess.py", line 61, in test_process_all_blocks_after_unclean assert_greater_than(wallet_height, wallet.getwalletinfo()["lastprocessedblock"]["height"]) ~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ``` https://github.com/bitcoin/bitcoin/actions/runs/27033707370/job/79792231964?pr=35294#step:9:3388
dergoegge (Migrated from github.com) approved these changes 2026-07-24 10:06:00 +00:00
dergoegge (Migrated from github.com) left a comment

utACK cce42a0db67c100f786ae5b8b03c6f6336bed945

utACK cce42a0db67c100f786ae5b8b03c6f6336bed945
pablomartin4btc (Migrated from github.com) reviewed 2026-08-06 19:32:11 +00:00
pablomartin4btc (Migrated from github.com) left a comment

Concept ACK

Moving updateState and coinbase abandonment from inside LoadTxRecords/LoadToWallet (during PopulateWalletFromDB, before the chain is attached) to AttachChain (after handleNotifications is registered) closes a real race: previously, as each tx was loaded, updateState queried the live chainstate — which could advance between loading tx A and tx B. This left a parent coinbase as Inactive while a descendant appeared Confirmed (its block just arrived), causing AbandonTransaction's internal try_updating_state to hit assert(!wtx.isConfirmed()).

FWIW, I made some plain ASCII draw to show the code move and help me understand the flow.

BEFORE change


LoadExisting()
  ├─ PopulateWalletFromDB()              [cs_wallet held]
  │    └─ WalletBatch::LoadWallet()
  │         └─ LoadTxRecords()
  │              ├─ Loop 1: LoadToWallet() × N txs
  │              │           └─ updateState() per tx   ← ⚠ chain can move between txs
  │              └─ Loop 2: AbandonTransaction()       ← ⚠ assert crash window for inactive coinbases
  ├─ TopUpKeyPool()
  └─ AttachChain()
       ├─ handleNotifications()          ← register (too late)
       ├─ SetLastBlockProcessedInMem
       └─ ScanForWalletTransactions

AFTER change


LoadExisting()
  ├─ PopulateWalletFromDB()              [cs_wallet held]
  │    └─ WalletBatch::LoadWallet()
  │         └─ LoadTxRecords()
  │              └─ Loop 1: LoadToWallet() × N txs   (no updateState)
  ├─ TopUpKeyPool()
  └─ AttachChain()                       [cs_wallet held]
       ├─ handleNotifications()          ← register FIRST
       ├─ SetLastBlockProcessedInMem
       ├─ Loop (reverse): updateState() + AbandonTransaction()  ← consistent snapshot
       └─ ScanForWalletTransactions
Concept ACK Moving `updateState` and coinbase abandonment from inside `LoadTxRecords`/`LoadToWallet` (during `PopulateWalletFromDB`, before the chain is attached) to `AttachChain` (after `handleNotifications` is registered) closes a real race: previously, as each tx was loaded, `updateState` queried the live chainstate — which could advance between loading tx A and tx B. This left a parent coinbase as `Inactive` while a descendant appeared `Confirmed` (its block just arrived), causing `AbandonTransaction`'s internal `try_updating_state` to hit `assert(!wtx.isConfirmed())`. <details> <summary>FWIW, I made some plain ASCII draw to show the code move and help me understand the flow.</summary> <br> BEFORE change --- ``` LoadExisting() ├─ PopulateWalletFromDB() [cs_wallet held] │ └─ WalletBatch::LoadWallet() │ └─ LoadTxRecords() │ ├─ Loop 1: LoadToWallet() × N txs │ │ └─ updateState() per tx ← ⚠ chain can move between txs │ └─ Loop 2: AbandonTransaction() ← ⚠ assert crash window for inactive coinbases ├─ TopUpKeyPool() └─ AttachChain() ├─ handleNotifications() ← register (too late) ├─ SetLastBlockProcessedInMem └─ ScanForWalletTransactions ``` AFTER change --- ``` LoadExisting() ├─ PopulateWalletFromDB() [cs_wallet held] │ └─ WalletBatch::LoadWallet() │ └─ LoadTxRecords() │ └─ Loop 1: LoadToWallet() × N txs (no updateState) ├─ TopUpKeyPool() └─ AttachChain() [cs_wallet held] ├─ handleNotifications() ← register FIRST ├─ SetLastBlockProcessedInMem ├─ Loop (reverse): updateState() + AbandonTransaction() ← consistent snapshot └─ ScanForWalletTransactions ``` </details>
pablomartin4btc (Migrated from github.com) commented 2026-08-06 19:14:08 +00:00

this might be obvious... change is safe for bitcoin-wallet tool, since it won't call AttachChain either (where updateState's call is being moved)...

this might be obvious... change is safe for `bitcoin-wallet` tool, since it won't call `AttachChain` either (where `updateState`'s call is being moved)...
pablomartin4btc (Migrated from github.com) commented 2026-08-06 17:44:14 +00:00

iterating children before parents ensures that descendants have updateState called before the parent coinbase's AbandonTransaction cascade reaches them — if it didn't, the chain could have advanced between processing parent and child, leaving the child Confirmed and triggering the assert.

iterating children before parents ensures that descendants have `updateState` called before the parent coinbase's `AbandonTransaction` cascade reaches them — if it didn't, the chain could have advanced between processing parent and child, leaving the child Confirmed and triggering the [assert](https://github.com/bitcoin/bitcoin/blob/c36ffd870e8b0b9933f991dc6eda661a943f3819/src/wallet/wallet.cpp#L1317).
pablomartin4btc (Migrated from github.com) commented 2026-08-06 16:59:28 +00:00

updateState runs before the rescan: after an unclean shutdown, txs in blocks above the restart tip get temporarily demoted to Inactive, then the rescan/blockConnected re-confirms them. I think a comment explaining this ordering dependency perhaps would help future readers (?).

`updateState` runs before the rescan: after an unclean shutdown, txs in blocks above the restart tip get temporarily demoted to Inactive, then the rescan/blockConnected re-confirms them. I think a comment explaining this ordering dependency perhaps would help future readers (?).
pablomartin4btc (Migrated from github.com) commented 2026-08-06 16:56:53 +00:00

just noticed that there's no AssertLockHeld in AbandonTransaction(CWalletTx&): this new call site in AttachChain relies on cs_wallet being held (which it is), but the overload doesn't assert it; this is pre-existing to this PR but I think worth noting...

just noticed that there's no `AssertLockHeld` in `AbandonTransaction(CWalletTx&)`: this new call site in `AttachChain` relies on `cs_wallet` being held (which it is), but the overload doesn't assert it; this is pre-existing to this PR but I think worth noting...
Lines 3254-3255
pablomartin4btc (Migrated from github.com) commented 2026-08-06 16:47:37 +00:00

minor nit: accidental extra line here?


minor nit: accidental extra line here? ```suggestion ```
achow101 (Migrated from github.com) reviewed 2026-08-26 18:17:51 +00:00
Lines 3254-3255
achow101 (Migrated from github.com) commented 2026-08-26 18:17:51 +00:00

If I retouch

If I retouch
achow101 (Migrated from github.com) reviewed 2026-08-26 18:18:08 +00:00
achow101 (Migrated from github.com) commented 2026-08-26 18:18:08 +00:00

Leaving this as is. There is also an EXCLUSIVE_LOCKS_HELD annotation.

Leaving this as is. There is also an `EXCLUSIVE_LOCKS_HELD` annotation.
achow101 (Migrated from github.com) reviewed 2026-09-08 20:20:54 +00:00
achow101 (Migrated from github.com) commented 2026-09-08 20:20:54 +00:00

If I retouch

If I retouch
l0rinc (Migrated from github.com) requested changes 2026-09-22 05:33:32 +00:00
l0rinc (Migrated from github.com) left a comment

I was surprised to see that the functional test passes without the fix, so I'd suggest adding a test that guides reviewers through the transition from the current behavior to the fixed behavior and demonstrates what actually changes. I put together a demo with a characterization test whose expectations change alongside the fix, while keeping the functional test as general coverage.

The fix looks mostly correct to me, but I'm not yet fully convinced that reverse iteration always visits children before their parents, since wallet insertion order doesn't necessarily reflect dependency order as far as I can tell.

I was surprised to see that the functional test passes without the fix, so I'd suggest adding a test that guides reviewers through the transition from the current behavior to the fixed behavior and demonstrates what actually changes. I put together [a demo](https://github.com/l0rinc/bitcoin/pull/298/commits) with a characterization test whose expectations change alongside the fix, while keeping the functional test as general coverage. The fix looks mostly correct to me, but I'm not yet fully convinced that reverse iteration always visits children before their parents, since wallet insertion order doesn't necessarily reflect dependency order as far as I can tell.
l0rinc (Migrated from github.com) commented 2026-09-22 01:55:02 +00:00

The bug requires the chain to advance between transaction loading and notification registration.
Here, loadwallet() finishes before connect_nodes(), and the test still passes with the fix reverted.
It's a useful test that covers wallet catch-up, but doesn't distinguish the broken behavior from the fixed behavior, so passing it doesn't increase my confidence in the fix itself.

Could we also cover that ordering in a unit test as well? A test database overriding ReadKey can reconnect the block when AttachChain first reads the saved best block, after loading transaction records and before registering notifications. This could characterize both the current and fixed behavior without sleeps, fabricated transaction states, or catching a process crash - it's why the gods have gifted us unit tests and mocks in the first place.

The bug requires the chain to advance between transaction loading and notification registration. Here, `loadwallet()` finishes before `connect_nodes()`, and the test still passes with the fix reverted. It's a useful test that covers wallet catch-up, but doesn't distinguish the broken behavior from the fixed behavior, so passing it doesn't increase my confidence in the fix itself. Could we also cover that ordering in a unit test as well? A test database overriding `ReadKey` can reconnect the block when `AttachChain` first reads the saved best block, after loading transaction records and before registering notifications. This could characterize both the current and fixed behavior without sleeps, fabricated transaction states, or catching a process crash - it's why the gods have gifted us unit tests and mocks in the first place.
First-time contributor

🔴 Major · Loading child-first coinbase records can abort the node

If a confirmed spender was inserted before its coinbase parent, loading against chain data without those confirmations reaches the spender before refreshing it and aborts the node during recursive abandonment.

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

🟠 Minor · Live-chain refresh can leave coinbases above the tracked tip

During runtime wallet loading, a stored coinbase activated at least two blocks above the tip snapshot can acquire negative depth, allowing a GUI read to abort the node before queued notifications catch up.

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

🔵 Suggestion · Regression test does not advance the chain during wallet loading

The test loads the wallet on a stationary chain and reconnects the missing-block peer afterwards, so its final state checks do not exercise the missed-block race described by the comment.

Location: test/functional/wallet_chain_reprocess.py:58 (head).

Review coverage was incomplete.


Reviewed: fcfec4b7a95a · Full review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:055d1cd96b176486294e0a3d052a7e506a00c1f0c7c35fbf579b09cfe6d615cd:237cc81563f53f26a84ba90acce49f0597b0e28b0a77aa425401db6e90431c0b --> <!-- ralph-base:5bf3bc5e263407a252c14a17afe04fc3bf24a889 --> <!-- ralph-head:fcfec4b7a95aab934002104cb8789652a8172a88 --> <!-- ralph-case:2d26285c5ef46fdcc41f9a01acb3b1137edc197d22e416bbb0e6fc576e58db23 --> **🔴 Major · Loading child-first coinbase records can abort the node** If a confirmed spender was inserted before its coinbase parent, loading against chain data without those confirmations reaches the spender before refreshing it and aborts the node during recursive abandonment. Location: [`src/wallet/wallet.cpp:3245`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/fcfec4b7a95aab934002104cb8789652a8172a88/src/wallet/wallet.cpp#L3245>) (head). **🟠 Minor · Live-chain refresh can leave coinbases above the tracked tip** During runtime wallet loading, a stored coinbase activated at least two blocks above the tip snapshot can acquire negative depth, allowing a GUI read to abort the node before queued notifications catch up. Location: [`src/wallet/wallet.cpp:3246`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/fcfec4b7a95aab934002104cb8789652a8172a88/src/wallet/wallet.cpp#L3246>) (head). **🔵 Suggestion · Regression test does not advance the chain during wallet loading** The test loads the wallet on a stationary chain and reconnects the missing-block peer afterwards, so its final state checks do not exercise the missed-block race described by the comment. Location: [`test/functional/wallet_chain_reprocess.py:58`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/fcfec4b7a95aab934002104cb8789652a8172a88/test/functional/wallet_chain_reprocess.py#L58>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`fcfec4b7a95a`](<https://git.fish.foo/bitcoin/bitcoin/commit/fcfec4b7a95aab934002104cb8789652a8172a88>) · [Full review report](<https://review.fish.foo/traces/35294-fcfec4b7a95aab934002104cb8789652a8172a88-2358-1.html>) · [Previous reports](<https://review.fish.foo/traces/35294/>) [permalink](<https://review.fish.foo/traces/35294-fcfec4b7a95aab934002104cb8789652a8172a88-2358-1.html>)
cprkrn commented 2026-11-25 19:50:44 +00:00 (Migrated from github.com)

The node aborts on loadwallet when a coinbase was added to the wallet after a tx already spent it, and both blocks reorged out while the wallet was unloaded.

The fix is to refresh every transaction, then mark the inactive coinbases as abandoned. If doing this, wallet tests pass + the crash is stopped.

Used AI to test + find this fix.

https://gist.github.com/cprkrn/6cbeee983899e9e6b2632e95c8fec7c4

The node aborts on loadwallet when a coinbase was added to the wallet after a tx already spent it, and both blocks reorged out while the wallet was unloaded. The fix is to refresh every transaction, then mark the inactive coinbases as abandoned. If doing this, wallet tests pass + the crash is stopped. Used AI to test + find this fix. https://gist.github.com/cprkrn/6cbeee983899e9e6b2632e95c8fec7c4
Sign in to join this conversation.
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!35294
No description provided.