mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 09:11:37 +00:00
wallet: Update tx chain state during loading during AttachChain instead of before #35294
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!35294
Loading…
Reference in a new issue
No description provided.
Delete branch "wallet-chain-load-inconsistency"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
When loading a wallet, updating the state based on the chain data prior to
AttachChainresults in some blocks being missed, which leads to inconsistent state information that can cause assertion failures. Moving the state updating inside ofAttachChainafter 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
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.
External sites
Reviews
See the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste
<!--meta-tag:bot-skip-->into the comment that the bot should ignore.Conflicts
Reviewers, this pull request conflicts with the following ones:
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.
ACK 18bc686c6e97fb5522a93412240ddca99057f1b7
Reviewed the change and tested locally.
Moving the tx state update out of
LoadToWallet()makes sense to me. During DBload, the wallet may already have a chain pointer, but it is not yet registered
for chain notifications. In
AttachChain(), notifications are registered beforethe 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 transactionstill reporting 0 confirmations after restart, and passes on this PR head:
Concept ACK 18bc686c6e97fb5522a93412240ddca99057f1b7
This is indeed quite a subtle and peculiar issue!
This argument doesn't seem necessary.
Is there a particular reason to mine 1000 blocks?
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.
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.
Removed
Removed
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.
Updated
@dergoegge CI is passing now, so can run through Antithesis?
Running
tACK 4de5c3b692b6958b36451a0bd6ac368f8f605b4f
This fixes the issue.
LGTM broadly 4de5c3b692b6958b36451a0bd6ac368f8f605b4f.
Few minor suggestions.
In 4de5c3b692b6958b36451a0bd6ac368f8f605b4f "test: Check all wallet tx states are correct after unclean shutdown"
s/1000/100
s/sufficiednt/sufficient
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.
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:
Since the tests run with
-unsafesqlitesync, not all data will be flushed at any given time. While we don't currentlyfsynceverything on a wallet close (we probably should though), unloading the wallet at least callssqlite3_closewhich 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.Done
Done
https://github.com/bitcoin/bitcoin/actions/runs/26480361555/job/77976026440?pr=35294#step:9:3403:
Hopefully fixed
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.
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.
Can we also check that the wallet's processed block has caught back up to the node tip after the restart catch-up path?
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.
Done
https://github.com/bitcoin/bitcoin/actions/runs/27033707370/job/79792231964?pr=35294#step:9:3388
utACK cce42a0db67c100f786ae5b8b03c6f6336bed945
Concept ACK
Moving
updateStateand coinbase abandonment from insideLoadTxRecords/LoadToWallet(duringPopulateWalletFromDB, before the chain is attached) toAttachChain(afterhandleNotificationsis registered) closes a real race: previously, as each tx was loaded,updateStatequeried the live chainstate — which could advance between loading tx A and tx B. This left a parent coinbase asInactivewhile a descendant appearedConfirmed(its block just arrived), causingAbandonTransaction's internaltry_updating_stateto hitassert(!wtx.isConfirmed()).FWIW, I made some plain ASCII draw to show the code move and help me understand the flow.
BEFORE change
AFTER change
this might be obvious... change is safe for
bitcoin-wallettool, since it won't callAttachChaineither (whereupdateState's call is being moved)...iterating children before parents ensures that descendants have
updateStatecalled before the parent coinbase'sAbandonTransactioncascade reaches them — if it didn't, the chain could have advanced between processing parent and child, leaving the child Confirmed and triggering the assert.updateStateruns 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 (?).just noticed that there's no
AssertLockHeldinAbandonTransaction(CWalletTx&): this new call site inAttachChainrelies oncs_walletbeing held (which it is), but the overload doesn't assert it; this is pre-existing to this PR but I think worth noting...minor nit: accidental extra line here?
If I retouch
Leaving this as is. There is also an
EXCLUSIVE_LOCKS_HELDannotation.If I retouch
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.
The bug requires the chain to advance between transaction loading and notification registration.
Here,
loadwallet()finishes beforeconnect_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
ReadKeycan reconnect the block whenAttachChainfirst 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.🔴 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 reportspermalink
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