Repository navigation
wallet: Fix ScanForWalletTransactions missing tx when look-ahead pool expands mid-block - #35901
pablomartin4btc wants to merge 3 commits into
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, 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. |
14b38b2 to
d4d4048
Compare
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
d4d4048 to
a826c73
Compare
|
This fixes a real bug. With the Two things came up when I was validating. Neither breaks anything, and both look cheap to tidy if you agree with them. The extra pass runs more often than the description suggests. What the loop tests is whether The second walk also re-runs Both go away if the re-walk covers only the prefix before the first expansion: keep the lowest vtx position where |
achow101
left a comment
There was a problem hiding this comment.
Concept ACK-ish
This does mean that every time we find a transaction with an output in our lookahead, we end up having to scan that block twice.
65cdcb0 to
60f1334
Compare
60f1334 to
278564b
Compare
|
Thanks for the thorough review and for actually running the test!
On "runs more often" — still partially valid: the re-scan fires whenever range_end moves during a block, not only in the vtx-ordering scenario. What changed from the previous version is that the re-scan is now bounded to the prefix [0,
On -walletnotify — you were testing the old version, which re-walked the full block and re-synced every already-known tx. In the current code the re-scan covers only [0,
On first vs last — I didn't take that suggestion exactly. Part 4 of the test shows the case you asked about: with vtx order |
@achow101, the re-scan is bounded at |
|
-Updates:
|
|
ACK 278564b |
There was a problem hiding this comment.
Concept ACK. The bug is valid, but I think the prefix-only rescan leaves the following case unresolved:
Scenario examined
- A parent transaction pays key
N, outside the initial look-ahead pool. - A later transaction pays key
N-1and expands the pool. - A subsequent child transaction spends the parent output to an external address.
Observed behavior
- The first pass misses the parent.
- The expander extends the pool.
- The child is not recognized because the parent has not yet been added to the wallet.
- The prefix rescan subsequently finds the parent, but it stops before the expander and therefore never revisits the child.
Consequence
The parent output can remain classified as unspent, leaving the wallet balance incorrect until another rescan.
Suggested coverage
Add a functional test case with the tx order:
- lookahead parent
- expander
- child spending the lookahead parent
Consider whether transactions after the expansion must also be reconsidered when the prefix pass discovers a previously missed wallet transaction.
Update
I was thinking about a solution... Briefly, a possible implementation is to iterate through the block and keep track of transactions for which SyncTransaction() already returned true, excluding them from later iterations (fix: walletnotify). Repeat this until an iteration causes no descriptor expansion.
This allows previously missed transactions to be retried in block order after the look-ahead pool expands.
278564b to
1d9de0e
Compare
Thanks for working through this — traced it and agree, the parent-then-child scenario is a real gap. The prefix rescan recovers the parent (its position is before the last expansion), but if the child spends it at or after that boundary, the child is never revisited, so the spend is never recorded and the parent output stays classified as unspent. Closing this properly needs a different approach — tracking per-tx Took your other three suggestions as-is, done in 1d9de0e, thanks! |
|
-Updates:
|
|
On 1d9de0e there is a second case the prefix does not reach, with no spend in it. A receive only becomes the wallet's once the prefix pass recovers an earlier one, and it sits past The casekeypool 5, pool So the documented limitation is narrower than the real one. Two channels make a transaction relevant after it has already been walked, the pool growing again and molnard's update already has the fix, and it covers this case as written. The variant I ran swaps the stopping condition for nothing new matched. The variant, and what I ran it againststd::vector<size_t> pending(block.vtx.size());
for (size_t i = 0; i < pending.size(); ++i) pending[i] = i;
while (!pending.empty()) {
std::vector<size_t> unmatched;
for (size_t pos_in_block : pending) {
if (!SyncTransaction(block.vtx[pos_in_block], TxStateConfirmed{block_hash, block_height, static_cast<int>(pos_in_block)}, /*rescanning_old_block=*/true)) {
unmatched.push_back(pos_in_block);
}
}
if (unmatched.size() == pending.size()) break; // nothing new matched
pending = std::move(unmatched);
}Both versions find the two cases with the right balance and pass your test's four parts. On the variant above, walletnotify stays at one invocation and the unit and BenchmarkRescanning 50 blocks of 401 transactions with one wallet receive each, the branch and the variant are indistinguishable, 0.146s against 0.143s with overlapping ranges. On a block where each pass reveals one more transaction, 30 of them behind 300 filler, the branch takes 0.126s and the variant 0.084s, ranges apart, because a transaction that has matched is never walked again. Medians of seven runs and five. |
Thanks @jeanpablojp for working on this. I'm analysing how your fix behaves against the current state of the PR and @molnard's pending follow-up, plus his earlier feedback that's already addressed. Will report back soon. |
1d9de0e to
7304d5f
Compare
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
7304d5f to
f63b601
Compare
|
Concept ACK I think this is a nice patch and the only re-check the pre-fix is clean and optimum. I have some generic questions. I would say this is a weird and very specific scenario to happen. And I don't think missing transactions out of the look-pool is something possible to fix at all, not at least without compromising a lot the performance of the rescan. What if the the missed transaction is just one block before? And two? And three? Which is the accepted performance-loss metric? This PR proposes the prefix of the block, why not 1 entire block? Why not N previous blocks? How slow do we rescan blocks for this to be a problem? Do we increase the look-pool many times? If not, it is worth to increase the re-check transaction list? |
|
@polespinasa, thanks for reviewing and for the questions! The PR description needs updating — the current approach goes through the entire block, not a prefix. On "1, 2, 3 blocks before" / "why not N previous blocks": real gap, not fixed by this PR — the retry loop is strictly intra-block, so a block already scanned is never revisited even if a later block's TopUp expands it. No concurrency needed, so it's distinct from the @furszy case already in the description. A fixed N doesn't really solve it either — any N can be beaten by a long enough confirmation delay, and blindly rescanning N whole blocks is expensive (full re-fetch/reprocess, not just what's relevant). I'm looking at tracking unresolved candidates directly instead — by descriptor index for receives, by txid-dependency for spends. I think it's worth its own, orthogonal follow-up, which I'm planning to open soon. On the performance-loss metric: I don't think is needed here — the retry loop is bounded by construction (at most one extra pass, bounded by the block's own size), not a tunable tradeoff. On how slow this gets: each block's retry is independent, so earlier TopUp events don't compound later cost. Worst case benchmarked — a large, mostly-foreign block with a three-level cascade ( |
|
-Updates:
|
f63b601 to
5582ecf
Compare
|
-Updates:
|
5582ecf to
2973a5e
Compare
Demonstrates that ScanForWalletTransactions misses a transaction paying
to a key just outside the look-ahead pool when the pool-expanding
transaction appears later in the same block's vtx order.
Part 1: wallet reload triggers rescan of one block; tx_lookahead is
missed on the first scan (wrong balance, no indication a
second scan is needed).
Part 2: importdescriptors with timestamp=0 triggers a full rescan;
same miss.
Part 3: a second rescanblockchain recovers tx_lookahead — the pool
was extended as a side-effect of finding tx_expand, so the
key is visible on re-scan.
TODO: Parts 1 and 2 assertions will be flipped in the fix commit.
…d-block ScanForWalletTransactions iterates over a block's transactions in vtx order. When a pool-expanding transaction appears *after* a transaction paying to a key just outside the look-ahead pool, the earlier transaction is missed: it was processed with a smaller pool (IsMine returned false), and FastWalletRescanFilter::UpdateIfNeeded() only fires at the next block boundary so there is no mechanism to re-examine it within the same scan pass. Fix: keep a list of still-unmatched vtx positions and retry it, dropping positions as they resolve, until a full pass resolves nothing new. A transaction can become resolvable only after an earlier one in the same block is processed — either because it expands the look-ahead pool (TopUp from MarkUnusedAddresses) covering a key this tx pays, or because it makes a previously-unknown parent tx known so this tx's spend of it is recognized. The unmatched set never grows, so this terminates. This is a more general fix than an earlier version of this commit, which tracked the last vtx position where the pool expanded and only re-scanned that shrinking prefix. molnard's review found that approach misses a same-block spend of a look-ahead receive recovered later in the same pass (see Part 6), and proposed the general direction: retry by each transaction's SyncTransaction() result until a full pass causes no change, rather than track a shrinking prefix. jeanpablojp found a second, independent gap in the shrinking-prefix approach — a prefix-recovered receive that triggers a further pool expansion past where the prefix had already shrunk to (see Part 5) — and wrote the retry loop below, confirming it resolves both gaps without needing two differently-shaped fixes: it doesn't matter *why* a transaction didn't match, only that it's retried once something else in the block might have changed that. Affected callers (all use ScanForWalletTransactions): rescanblockchain, importdescriptors (via RescanFromTime), restorewallet and wallet migration watchonly/solvable wallets (via AttachChain). This bug does not affect the live blockConnected path when transactions pass through the mempool first: transactionAddedToMempool(Tx_expand) pre-extends the pool before the block arrives. A single block can now take several passes to resolve instead of one, so check for an abort or shutdown request between passes (w0xlt), rather than only between blocks as before, so a long-running cascade within one block doesn't delay responding to a cancellation. A block left only partially scanned this way is reported as USER_ABORT rather than a read failure. Extend the regression test with Part 4 to cover a two-level cascade within a single pass, Part 5 to cover a receive-only cascade that a shrinking-prefix approach would miss, and Part 6 to cover a same-block spend of a look-ahead receive recovered via a separate expansion. Flip Parts 1 and 2 from the bug-demonstrating assertions in the previous commit to the fixed behavior. Add a unit test confirming an abort requested between passes within one block is honored promptly and reported correctly, rather than only an abort requested between blocks. Co-authored-by: jeanpablojp <[email protected]> Co-authored-by: w0xlt <[email protected]>
Guard the performance of ChainScanner::ScanBlock's retry-until-stable loop against regression. Build a real, consensus-valid block containing 2000 foreign (not-wallet-relevant) transactions with a three-level look-ahead pool cascade interleaved among them: a transaction E that expands the pool, which makes a later transaction A visible; A's own recognition expands the pool a second time, which makes a still-later transaction B visible. This is close to a worst case for the retry loop, since recognizing A and B each require an additional full retry pass over the block's still-unmatched transactions. Benchmark the actual production entry point, wallet.Scanner().Scan(), against a freshly imported descriptor each iteration, rather than reimplementing or comparing scan algorithms in the benchmark itself.
2973a5e to
5f62bf0
Compare
|
-Updates:
|
| std::vector<size_t> pending(block.vtx.size()); | ||
| for (size_t i = 0; i < pending.size(); ++i) pending[i] = i; | ||
| while (!pending.empty()) { | ||
| if (m_abort || m_wallet.chain().shutdownRequested()) return false; |
There was a problem hiding this comment.
You can change ScanBlock to return std::optional<bool> and return std::nullopt here to indicate cancellation, so that you don't have to repeat m_abort || m_wallet.chain().shutdownRequested() at the call site to check for cancellation.
| "tx_lookahead must be found after fix: block re-processed when pool expands mid-block" | ||
|
|
||
| # ----------------------------------------------------------------------- | ||
| # Part 3: a second rescanblockchain recovers tx_lookahead. |
There was a problem hiding this comment.
Is part 3 still necessary? With the fix applied, part 3 doesn't test anything that parts 1 and 2 don't already cover.
| "lookahead_2 must be found after fix: visible after second TopUp re-scan" | ||
|
|
||
| # ----------------------------------------------------------------------- | ||
| # Part 5: a receive-only tx recovered by the prefix pass itself triggers a |
There was a problem hiding this comment.
Is there a "prefix pass" in the code? The comments about "prefix pass" are a bit confusing. It seems that they refer to a previous approach.
|
|
||
| const int idx_e = KEYPOOL_SIZE - 1; | ||
| const int idx_a = KEYPOOL_SIZE; | ||
| const int idx_b = 2 * KEYPOOL_SIZE; |
There was a problem hiding this comment.
This triggers two KEYPOOL_SIZE TopUps; the cost of these TopUps will dominate the scan time and hide the retry cost. It also doesn't allow comparison with the pre-fix code because the pre-fix code derives only KEYPOOL_SIZE, while the post-fix code derives (2 * KEYPOOL_SIZE).
|
🐙 This pull request conflicts with the target branch and needs rebase. |

When
ScanForWalletTransactionsprocesses a block containing both a transaction to a key just outside the look-ahead pool and a pool-expanding transaction that triggersTopUp, and the former appears first in vtx order, the wallet misses the earlier transaction — leaving the balance wrong with no indication a second scan is needed. The fix retries any transaction that doesn't match on a full pass, dropping it once it does, until a pass resolves nothing new — so a transaction can be recognized once something else in the block makes it relevant, regardless of why.The first commit demonstrates the incorrect behaviour; the second contains the fix; the third adds a benchmark guarding the fix's performance on a large, mostly-foreign block with an embedded multi-level cascade.
Bug details...
ScanForWalletTransactionsiterates over a block's transactions in the order the miner placed them (vtx order). A descriptor wallet maintains a look-ahead pool of pre-derived keys so it can recognise incoming payments. When a payment arrives at a key near the pool boundary,MarkUnusedAddresses→TopUpextends the pool.
If within a single block:
N(just outside the current pool[0, N-1]), ANDN-1(last in pool — triggers TopUp, extending pool to[0, 2N-1])and Tx_lookahead appears at an earlier vtx position than Tx_expand, the scan misses Tx_lookahead:
[0, N-1]→IsMinereturns false → missedN-1found → TopUp fires → pool =[0, 2N-1]FastWalletRescanFilter::UpdateIfNeeded()fires only at the start of the next block iteration — there is no mechanism to re-examine Tx_lookahead within the same scan pass.The transaction is not permanently lost — because Tx_expand extended the pool as a side effect, a second explicit
rescanblockchaincall recovers Tx_lookahead. But the wallet shows a wrong balance with no indication a second scan is needed.This bug does not affect live
blockConnectedwhen both transactions pass through the mempool first:transactionAddedToMempool(Tx_expand)pre-extends the pool before the block arrives, so vtx ordering does not matter. It only manifests inScanForWalletTransactions(rescan paths) for descriptor wallets.Affected callers...
Callers affected (all use
ScanForWalletTransactions):rescanblockchainimportdescriptors(viaRescanFromTime)restorewalletand wallet migration watchonly/solvable wallets (viaAttachChain)Fix details and performance...
Fix: during the per-block vtx loop, keep a list of still-unmatched vtx positions. Retry it each pass, dropping positions once
SyncTransaction()returnstruefor them, until a full pass resolves nothing new. A transaction becomes resolvable once something else earlier in the same block changes its relevance — either a pool expansion (TopUpfromMarkUnusedAddresses) now covering a key it pays, or a previously-unknown parent transaction becoming known so a spend of it is recognized. The unmatched set never grows, so this terminates without a safety cap.This also covers two cases a shrinking-prefix rescan (an earlier version of this fix) did not: a prefix-recovered receive that triggers a second pool expansion past where the prefix had already shrunk to (see Part 5), and a same-block spend of a look-ahead receive only recognized later in the same pass via a parent-tx lookup rather than a pool expansion (see Part 6, molnard's finding — see Notes below).
Performance: the retry loop costs at most one extra pass for any block containing a wallet-relevant transaction during a rescan, in typical shapes. The worst case is a large, mostly-foreign block with a multi-level cascade embedded in it.
bench_bitcoin -filter=RescanCascadeInLargeBlockguards that scenario against regression.Test coverage...
Regression test:
test/functional/wallet_rescan_intrablock_ordering.pyManual reproduction (
regtest)Notes:
Originally noted by furszy in wallet: fix rescanning inconsistency #31629 (comment); his "case 2" describes a related but harder inter-block variant: new blocks arriving via
blockConnectedduring an active rescan with a not-yet-expanded pool. That problem remains a potential follow-up. This PR fixes the simpler intra-block sub-case where the miss happens entirely within a single block's vtx loop, with no concurrent block arrivals required.Perhaps the issue is related to the symptom was previously reported in wallet: Imports with pre-existing balance somtimes don't have any balance after a rescan #19808 but could not be reproduced at the time and was closed without a fix.
molnard found a related gap the shrinking-prefix rescan didn't close: if a parent tx pays a look-ahead key and a later tx in the same block spends that parent's output, and the spend sits at or after the block's last pool expansion, the prefix rescan recovers the parent but never revisits the spend. jeanpablojp separately found a second gap in the same shrinking-prefix approach — a prefix-recovered receive that triggers a further pool expansion past where the prefix had already shrunk to (Part 5) — and proposed and benchmarked the fix now in this PR: retry based on each tx's
SyncTransaction()result until a full pass causes no change, rather than tracking a shrinking prefix. Both gaps are now fixed in this PR (Parts 5 and 6).