Skip to content

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

Open
achow101 wants to merge 2 commits into
bitcoin:masterfrom
achow101:wallet-chain-load-inconsistency
Open

achow101 wants to merge 2 commits into
bitcoin:masterfrom
achow101:wallet-chain-load-inconsistency

Conversation

@achow101

Copy link
Copy Markdown
Member

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

DrahtBot commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

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.

@shuv-amp

Copy link
Copy Markdown
Contributor

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

@rkrux rkrux left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concept ACK 18bc686c6e97fb5522a93412240ddca99057f1b7

This is indeed quite a subtle and peculiar issue!

Comment thread src/wallet/wallet.cpp Resolved
@fanquake

Copy link
Copy Markdown
Member

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

@dergoegge

Copy link
Copy Markdown
Member

so can run through Antithesis?

Running

@dergoegge dergoegge left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tACK 4de5c3b692b6958b36451a0bd6ac368f8f605b4f

This fixes the issue.

@DrahtBot
DrahtBot requested a review from rkrux May 22, 2026 12:40

@rkrux rkrux left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM broadly 4de5c3b692b6958b36451a0bd6ac368f8f605b4f.

Few minor suggestions.


# Sync nodes, kill node 0, and restart
self.sync_all()
wallet.unloadwallet()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@DrahtBot
DrahtBot requested a review from rkrux May 25, 2026 12:43
@achow101
achow101 force-pushed the wallet-chain-load-inconsistency branch from 4de5c3b to ff48c8c Compare May 26, 2026 19:52
@achow101
achow101 force-pushed the wallet-chain-load-inconsistency branch from ff48c8c to 33a0ce8 Compare May 26, 2026 23:08
@achow101
achow101 force-pushed the wallet-chain-load-inconsistency branch from 33a0ce8 to d33afaf Compare May 28, 2026 18:34

@l0rinc l0rinc left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/wallet/wallet.cpp

// 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)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
     {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
achow101 force-pushed the wallet-chain-load-inconsistency branch from d33afaf to 3556f80 Compare June 5, 2026 18:47

@dergoegge dergoegge left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

utACK cce42a0

Updating transactions against the current chain state can only be done
in AttachChain after chain notifications have been attached. AttachChain
will guarantee that any blocks missing between the stored best block and
the current tip are rescanned, and any blocks connected during
AttachChain will be processed after loading completes.

This fixes an issue where tx states were updated with no guarantee that
any blocks connected prior to AttachChain are scanned, resulting in
incorrect tx states.
@achow101
achow101 force-pushed the wallet-chain-load-inconsistency branch from cce42a0 to fcfec4b Compare August 5, 2026 22:54

@pablomartin4btc pablomartin4btc left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/wallet/wallet.cpp
Comment on lines +3253 to +3254


Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor nit: accidental extra line here?

Suggested change

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I retouch

Comment thread src/wallet/wallet.cpp
// 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);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/wallet/wallet.cpp
// 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);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 (?).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I retouch

Comment thread src/wallet/wallet.cpp
}

// 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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/wallet/wallet.cpp
if (!ins.second) {
return false;
}
// If wallet doesn't have a chain (e.g when using bitcoin-wallet tool),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@l0rinc l0rinc left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was surprised to see that the functional test passes without the fix, so I'd suggest adding another 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.



def run_test(self):
self.test_process_all_blocks_after_unclean()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@cprkrn

cprkrn commented Nov 25, 2026

Copy link
Copy Markdown

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

luke-jr pushed a commit to BitcoinVibe/bitcoin that referenced this pull request Dec 1, 2026
Updating transactions against the current chain state can only be done
in AttachChain after chain notifications have been attached. AttachChain
will guarantee that any blocks missing between the stored best block and
the current tip are rescanned, and any blocks connected during
AttachChain will be processed after loading completes.

This fixes an issue where tx states were updated with no guarantee that
any blocks connected prior to AttachChain are scanned, resulting in
incorrect tx states.

Github-Pull: bitcoin#35294
Rebased-From: 8bd3196
luke-jr pushed a commit to BitcoinVibe/bitcoin that referenced this pull request Dec 1, 2026
luke-jr pushed a commit to BitcoinVibe-devel/bitcoin that referenced this pull request Dec 1, 2026
Updating transactions against the current chain state can only be done
in AttachChain after chain notifications have been attached. AttachChain
will guarantee that any blocks missing between the stored best block and
the current tip are rescanned, and any blocks connected during
AttachChain will be processed after loading completes.

This fixes an issue where tx states were updated with no guarantee that
any blocks connected prior to AttachChain are scanned, resulting in
incorrect tx states.

Github-Pull: bitcoin#35294
Rebased-From: 8bd3196
luke-jr pushed a commit to BitcoinVibe-devel/bitcoin that referenced this pull request Dec 1, 2026
luke-jr pushed a commit to BitcoinVibe-devel/bitcoin that referenced this pull request Dec 1, 2026
Updating transactions against the current chain state can only be done
in AttachChain after chain notifications have been attached. AttachChain
will guarantee that any blocks missing between the stored best block and
the current tip are rescanned, and any blocks connected during
AttachChain will be processed after loading completes.

This fixes an issue where tx states were updated with no guarantee that
any blocks connected prior to AttachChain are scanned, resulting in
incorrect tx states.

Github-Pull: bitcoin#35294
Rebased-From: 8bd3196
luke-jr pushed a commit to BitcoinVibe-devel/bitcoin that referenced this pull request Dec 1, 2026
luke-jr pushed a commit to BitcoinVibe-devel/bitcoin that referenced this pull request Dec 1, 2026
Updating transactions against the current chain state can only be done
in AttachChain after chain notifications have been attached. AttachChain
will guarantee that any blocks missing between the stored best block and
the current tip are rescanned, and any blocks connected during
AttachChain will be processed after loading completes.

This fixes an issue where tx states were updated with no guarantee that
any blocks connected prior to AttachChain are scanned, resulting in
incorrect tx states.

Github-Pull: bitcoin#35294
Rebased-From: 8bd3196
luke-jr pushed a commit to BitcoinVibe-devel/bitcoin that referenced this pull request Dec 1, 2026
luke-jr pushed a commit to BitcoinVibe-devel/bitcoin that referenced this pull request Dec 1, 2026
Updating transactions against the current chain state can only be done
in AttachChain after chain notifications have been attached. AttachChain
will guarantee that any blocks missing between the stored best block and
the current tip are rescanned, and any blocks connected during
AttachChain will be processed after loading completes.

This fixes an issue where tx states were updated with no guarantee that
any blocks connected prior to AttachChain are scanned, resulting in
incorrect tx states.

Github-Pull: bitcoin#35294
Rebased-From: 8bd3196
Github-Pull: BitcoinVibe#2
Rebased-From: 99f0e27
luke-jr pushed a commit to BitcoinVibe-devel/bitcoin that referenced this pull request Dec 1, 2026
luke-jr pushed a commit to BitcoinVibe/bitcoin that referenced this pull request Dec 1, 2026
Updating transactions against the current chain state can only be done
in AttachChain after chain notifications have been attached. AttachChain
will guarantee that any blocks missing between the stored best block and
the current tip are rescanned, and any blocks connected during
AttachChain will be processed after loading completes.

This fixes an issue where tx states were updated with no guarantee that
any blocks connected prior to AttachChain are scanned, resulting in
incorrect tx states.

Github-Pull: bitcoin#35294
Rebased-From: 8bd3196
Github-Pull: #2
Rebased-From: 99f0e27
luke-jr pushed a commit to BitcoinVibe/bitcoin that referenced this pull request Dec 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

wallet: Assertion !wtx.isConfirmed() failed

10 participants