Skip to content

wallet: parallel fast rescan - #34400

Open
Eunovo wants to merge 8 commits into
bitcoin:masterfrom
Eunovo:new-rescan
Open

Eunovo wants to merge 8 commits into
bitcoin:masterfrom
Eunovo:new-rescan

Conversation

@Eunovo

@Eunovo Eunovo commented Jan 24, 2026 •

Copy link
Copy Markdown
Contributor

This PR speeds up wallet fast-rescan by executing the filter checks in parallel while ensuring that the filters are updated properly so that no output scripts are missed. Benchmarks, outlined below, show considerable improvement that slows down around 8 threads.

Prerequisite PRs

Benchmarks

Prepare

  • Please tune your system with pyperf system tune.
  • Enable block filters by setting blockfilterindex=1 in your bitcoin.conf file and sync your node to the tip.
  • Parallel fast-rescan will not be used if chain.isInitialBlockDownload() is true. Ensure your node is synced before shutting down and running the mainnet benchmark commands.

Using the following command on mainnet with a wallet with no scripts and hyperfine version 1.20.0:

  • On master
hyperfine --show-output --export-markdown master.md --export-json master.json  \
--sort command \
--runs 3 \
--prepare 'cmake --build build -j 20 && build/bin/bitcoind -blockfilterindex=1 -networkactive=0 && sleep 10 && build/bin/bitcoin-cli loadwalllet <wallet-name>' \
--conclude 'build/bin/bitcoin-cli stop && sleep 10' \
'build/bin/bitcoin-cli rescanblockchain 700000 900000'
  • On this PR:
hyperfine --show-output --export-markdown results.md --export-json results.json  \
--sort command \
--runs 3 \
-L num_threads 1,2,3,4,5,6,7,8,9,16 \
--prepare 'cmake --build build -j 20 && build/bin/bitcoind -blockfilterindex=1 -networkactive=0 -walletpar={num_threads} && sleep 10 && build/bin/bitcoin-cli loadwalllet <wallet-name>' \
--conclude 'build/bin/bitcoin-cli stop && sleep 10' \
'build/bin/bitcoin-cli rescanblockchain 700000 900000'
Table 1 was obtained on a machine with the following specifications
Architecture:             x86_64
  CPU op-mode(s):         32-bit, 64-bit
  Address sizes:          46 bits physical, 48 bits virtual
  Byte Order:             Little Endian
CPU(s):                   20
  On-line CPU(s) list:    0-19
Vendor ID:                GenuineIntel
  Model name:             Intel(R) Core(TM) Ultra 7 265
    CPU family:           6
    Model:                198
    Thread(s) per core:   1
    Core(s) per socket:   1
    Socket(s):            20
    Stepping:             2
    CPU(s) scaling MHz:   41%
    CPU max MHz:          4800.0000
    CPU min MHz:          800.0000
    BogoMIPS:             4761.60
Branch Mean [s] Min [s] Max [s]
master 272.222 ± 0.183 272.064 272.423
new-rescan (num_threads = 1) 274.423 ± 0.515 273.831 274.771
new-rescan (num_threads = 2) 137.240 ± 0.210 137.111 137.483
new-rescan (num_threads = 4) 70.159 ± 0.172 69.998 70.340
new-rescan (num_threads = 6) 48.351 ± 0.051 48.319 48.411
new-rescan (num_threads = 8) 37.955 ± 0.084 37.884 38.048
new-rescan (num_threads = 10) 33.271 ± 0.028 33.240 33.295
new-rescan (num_threads = 16) 25.295 ± 0.015 25.284 25.312

Table 1. Table of results of a mainnet benchmark of scanning 200,000 blocks on a wallet with no scripts. An empty wallet is not representative of a typical wallet; the next benchmark tries to simulate more "interesting" scenarios.

This Python script patch python script creates custom chains designed with payments at specified intervals to observe the performance of parallel fast rescan.

Fig 1 shown below was produced using this patch on a machine with the following specifications
Architecture:                x86_64
  CPU op-mode(s):            32-bit, 64-bit
  Address sizes:             48 bits physical, 48 bits virtual
  Byte Order:                Little Endian
CPU(s):                      16
  On-line CPU(s) list:       0-15
Vendor ID:                   AuthenticAMD
  Model name:                AMD Ryzen 9 8945HS w/ Radeon 780M Graphics
    CPU family:              25
    Model:                   117
    Thread(s) per core:      2
    Core(s) per socket:      8
    Socket(s):               1
    Stepping:                2
    Frequency boost:         enabled
    CPU(s) scaling MHz:      63%
    CPU max MHz:             5263.0000
    CPU min MHz:             400.0000
benchmark_comparison

Fig 1. Time to scan a 2000-block chain on Regtest with payments at varying intervals, comparing parallel Fast Rescan against serial Fast Rescan (baseline). These benchmarks use the -walletpar commit as a baseline instead of master, since master lacks the -walletpar config parameter. All materials for this custom benchmark are available here.

@DrahtBot

DrahtBot commented Jan 24, 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 w0xlt, ismaelsadeeq, rkrux, polespinasa

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:

  • #36904 (log: Remove trailing and embedded newlines from log messages by maflcko)
  • #32857 (wallet: allow skipping script paths by Sjors)

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.

@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task test max 6 ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/21320629356/job/61369934184
LLM reason (✨ experimental): Compilation failed due to an unused private member (m_thread_pool) in wallet.h being treated as an error under -Werror.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

@luke-jr

luke-jr commented Jan 29, 2026

Copy link
Copy Markdown
Contributor

I would have expected rescanning to be I/O bound rather than CPU, in which case parallelization could make things worse (more random seeking). Have you benchmarked this on a non-SSD?

@Eunovo

Eunovo commented Jan 29, 2026

Copy link
Copy Markdown
Contributor Author

I would have expected rescanning to be I/O bound rather than CPU, in which case parallelization could make things worse (more random seeking). Have you benchmarked this on a non-SSD?

Fast rescan checks block filters, which involves considerable hashing. This PR parallelises the checking of block filters, and my benchmarks show considerable improvements in rescan speeds with block filters. Slow rescan, which is I/O bound, remains the same. I expect the speedup to be transferable to non-SSD machines, but I haven't benchmarked this.

Comment thread src/wallet/scan.cpp Resolved
@Eunovo

Eunovo commented Feb 11, 2026

Copy link
Copy Markdown
Contributor Author

#33689 has been merged; the cherry-picked Threadpool commit has been removed.

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

I like the PR conceptually but I think it would be nice to first improve the current scanning code structure, then land the parallelization feature. The current code mixes a lot responsibilities.
Similar to what you did in 633531614f69de49733642fd19cc9eba830fbdea, but into a separate PR so we can first land some good building blocks for this to happen.

Some quick pseudo-code structuring how I imagine it, which is similar to yours:

Scan(wallet, start_block_hash, end_block_hash, fn_filter_block, fn_process_block, interrupt) {
     it_current_hash = start_block_hash;

     while (it_current_hash != end_block_hash || interrupt) {
         // Skip block if needed (this function contains the BlockFilterIndex check if enabled)
         if (fn_filter_block(it_current_hash)) continue;
    
         // (this is more or less how we currently do it, we fetch the block and the next block hash at the same time)
         block = chain.find_block(it_current_hash).next_block(it_current_hash);
    
         // (inside this function the wallet will digest the block update the filter and save progress if needed)
         fn_process_block(block);
      }
}

@w0xlt

w0xlt commented Feb 21, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

@Eunovo

Eunovo commented Feb 26, 2026

Copy link
Copy Markdown
Contributor Author

I like the PR conceptually but I think it would be nice to first improve the current scanning code structure, then land the parallelization feature. The current code mixes a lot responsibilities. Similar to what you did in 6335316, but into a separate PR so we can first land some good building blocks for this to happen.

I moved the test change into #34667 and the ScanForWalletTransactions refactor into #34681.
I'll be putting this PR in draft while those PRs are open.

@Eunovo
Eunovo marked this pull request as draft February 26, 2026 16:22
@DrahtBot DrahtBot removed the CI failed label Nov 3, 2026
@Eunovo Eunovo changed the title wallet: parallel fast rescan (approx 8x speed up with 8 threads) wallet: parallel fast rescan Nov 4, 2026
@Eunovo
Eunovo marked this pull request as ready for review November 4, 2026 07:31
@Eunovo

Eunovo commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

We replaced the previous implementation with a much simpler sliding-window implementation. New benchmark results are in #34400 (comment).

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

reviewed 15fa337

will review the other 4 commits tomorrow :)

Comment thread src/wallet/scan.h Resolved
Comment thread src/wallet/scan.cpp Resolved
Comment thread src/wallet/scan.cpp Resolved
Comment thread src/wallet/wallet.cpp Outdated
wallet->m_wallet_par += GetNumCores();
}
// The calling thread counts towards -walletpar, as for -par.
wallet->m_wallet_par = std::clamp(wallet->m_wallet_par, 1, MAX_WALLETPAR + 1);

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.

in 15fa337 wallet: add -walletpar option

Maybe we should just throw here if m_wallet_par is negative? I think we should require -walletpar to be bigger than -GetNumCores() and smaller than GetNumCores() + 1.

Also GetIntArg returns an int64 while m_wallet_par is a normal int you can overflow the integers and trick a bit the result. This obviously is weird and not critic, but I think is worth addressing as is easy to fix:

$ git diff
diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp
index b1b9f52919..56e106afb5 100644
--- a/src/wallet/wallet.cpp
+++ b/src/wallet/wallet.cpp
@@ -2930,14 +2930,14 @@ bool CWallet::LoadWalletArgs(std::shared_ptr<CWallet> wallet, const WalletContex
     wallet->m_notify_tx_changed_script = args.GetArg("-walletnotify", "");
     wallet->SetBroadcastTransactions(args.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
 
-    wallet->m_wallet_par = args.GetIntArg("-walletpar", DEFAULT_WALLETPAR);
-    if (wallet->m_wallet_par <= 0) {
+    int64_t wallet_par = args.GetIntArg("-walletpar", DEFAULT_WALLETPAR);
+    if (wallet_par <= 0) {
         // '0' means 'autodetect'
         // '<0' means leave that many cores free
-        wallet->m_wallet_par += GetNumCores();
+        wallet_par += GetNumCores();
     }
     // The calling thread counts towards -walletpar, as for -par.
-    wallet->m_wallet_par = std::clamp(wallet->m_wallet_par, 1, MAX_WALLETPAR + 1);
+    wallet->m_wallet_par = static_cast<int>(std::clamp<int64_t>(wallet_par, 1, MAX_WALLETPAR + 1));
 
     return true;
 }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I've fixed the overflow issue, but the code still doesn't throw. I'm not convinced we need to throw here. I think silently using the maximum or minimum number of threads is good enough, rather than forcing the user to enter the correct num cores.

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

reviewed db2d769

I've just reviewed code, I've skipped tests.

There are a few ralph comments that I would say they are worth addressing. Specially in commit 5441a57 where there are some edge cases that can make the rescan skip payments.

I couldn't personally find anything else wrong in the behavior of 5441a57, and my LLM scan found the same as Ralph.

Comment thread src/wallet/scan.cpp Resolved
Comment thread src/wallet/scan.cpp Resolved
@Eunovo

Eunovo commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

CI failure seems unrelated. See #36913

Comment thread src/wallet/scan.h Resolved
Comment thread src/wallet/scan.h Resolved
Comment thread src/wallet/scan.cpp Resolved
Comment thread src/wallet/scan.cpp Resolved
Comment thread src/wallet/scan.h Resolved

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

I am close to acking it :)
reviewed cdbdfd8
There are some Ralph comments interesting to address.

For example the one regarding Reorg tests miss disconnection between lookup and transaction sync.
Maybe something like, the diff below would do the job. (The test is ai so may have some errors, but just to give an idea)
It fails in master and passes on top of commit1.

test diff
$ git diff
diff --git a/src/wallet/test/rescan_tests.cpp b/src/wallet/test/rescan_tests.cpp
index fc1b61c1e1..4df0214be0 100644
--- a/src/wallet/test/rescan_tests.cpp
+++ b/src/wallet/test/rescan_tests.cpp
@@ -6,6 +6,7 @@
 #include <chain.h>
 #include <index/blockfilterindex.h>
 #include <interfaces/chain.h>
+#include <interfaces/handler.h>
 #include <node/blockstorage.h>
 #include <node/context.h>
 #include <test/util/common.h>
@@ -261,6 +262,74 @@ BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_reorged_block, TestChain100
     StopIndex(filter_index, m_node);
 }
 
+BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_reorg_during_scan, TestChain100Setup)
+{
+    BlockFilterIndex& filter_index{*m_node.block_filter_indexes.emplace_back(
+        node::MakeIndex<BlockFilterIndex>(interfaces::MakeChain(m_node), BlockFilterType::BASIC, 1_MiB, /*f_memory=*/true))};
+    BOOST_REQUIRE(filter_index.Init());
+    filter_index.Sync();
+    BOOST_REQUIRE(filter_index.BlockUntilSyncedToCurrentChain());
+
+    CBlockIndex* stale_block = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
+    BOOST_REQUIRE_EQUAL(stale_block->nHeight, 100);
+    const uint256 stale_hash{stale_block->GetBlockHash()};
+    const CBlockIndex* start_block{stale_block->pprev};
+    const auto& coinbase{m_coinbase_txns.back()};
+    auto wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
+    {
+        LOCK(wallet->cs_wallet);
+        wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
+        wallet->SetLastBlockProcessed(stale_block->nHeight, stale_hash);
+    }
+    AddKey(*wallet, coinbaseKey);
+    WalletRescanReserver reserver(*wallet);
+    BOOST_REQUIRE(reserver.reserve());
+    const ScanResult initial_result = wallet->Scanner().Scan(stale_hash, stale_block->nHeight,
+                                                            /*max_height=*/stale_block->nHeight, reserver, /*save_progress=*/false);
+    BOOST_REQUIRE_EQUAL(initial_result.status, ScanResult::SUCCESS);
+    {
+        LOCK(wallet->cs_wallet);
+        BOOST_REQUIRE(wallet->mapWallet.at(coinbase->GetHash()).isConfirmed());
+    }
+    auto notifications = wallet->chain().handleNotifications(wallet);
+
+    // Scanning heights 99-100 emits its only intermediate progress update at
+    // height 100, after looking up its successor but before syncing its txs.
+    // Deliver the disconnect notification in that window: the earlier activity
+    // check must not allow the rescan to confirm the coinbase again afterwards.
+    bool disconnected{false};
+    auto progress_handler = wallet->ShowProgress.connect([&](const std::string&, int progress) {
+        if (progress == 0 || progress == 100 || disconnected) return;
+        disconnected = true;
+        BlockValidationState state;
+        BOOST_REQUIRE(m_node.chainman->ActiveChainstate().InvalidateBlock(state, stale_block));
+        wallet->chain().waitForNotifications();
+        LOCK(wallet->cs_wallet);
+        BOOST_REQUIRE_EQUAL(wallet->GetLastBlockHash(), start_block->GetBlockHash());
+        BOOST_REQUIRE(wallet->mapWallet.at(coinbase->GetHash()).isAbandoned());
+    });
+
+    const ScanResult result = wallet->Scanner().Scan(start_block->GetBlockHash(), start_block->nHeight,
+                                                    /*max_height=*/stale_block->nHeight, reserver, /*save_progress=*/false);
+    progress_handler.disconnect();
+    notifications->disconnect();
+    wallet->chain().waitForNotifications();
+
+    BOOST_REQUIRE(disconnected);
+    BOOST_CHECK_EQUAL(result.status, ScanResult::FAILURE);
+    BOOST_CHECK_EQUAL(result.last_failed_block, stale_hash);
+    BOOST_CHECK_EQUAL(result.last_scanned_block, start_block->GetBlockHash());
+    BOOST_REQUIRE(result.last_scanned_height);
+    BOOST_CHECK_EQUAL(*result.last_scanned_height, start_block->nHeight);
+    {
+        LOCK(wallet->cs_wallet);
+        BOOST_CHECK(!wallet->mapWallet.at(coinbase->GetHash()).isConfirmed());
+        BOOST_CHECK(wallet->mapWallet.at(coinbase->GetHash()).isAbandoned());
+    }
+
+    StopIndex(filter_index, m_node);
+}
+
 BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions_abort, TestChain100Setup)
 {
     CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());

Comment thread src/wallet/scan.h Resolved
Comment thread src/wallet/scan.cpp Resolved
Comment thread test/functional/wallet_fast_rescan.py Resolved
Checking inActiveChain before reading the block left a window where the
block could be disconnected and its blockDisconnected notification
handled before its transactions were synced as confirmed. Checking with
cs_wallet held closes it, since that notification needs cs_wallet.
Move the filtering in ShouldFetchBlock into NextBlocksSerial, which
returns the blocks to scan, and keep per-scan state in a ScanContext.
This prepares for parallel filter checks.

No behaviour change, except that if the wallet's tip moves past the
last processed block after the lookup of its successor found none,
the successor is looked up again instead of ending the scan.
Number of threads for wallet operations, to be used by parallel fast
rescan. As for -par, the calling thread counts towards it, 0
auto-detects, a negative value leaves that many cores free, and at most
MAX_WALLETPAR (15) dedicated threads are used.
With -walletpar > 1, fast rescan checks block filters on a thread pool.
Blocks are read in windows, checked in tasks of BLOCKS_PER_FILTER_TASK blocks
queued ahead of delivery, and delivered in block order, so workers keep
checking while the scan thread scans matched blocks.

On a keypool top-up, in-flight checks are drained and undelivered
NoMatch verdicts are re-checked against only the new scripts. Read-ahead
is wasted work then, so the window shrinks on every top-up and grows
while there are none.
Parallel filter checks would compete with block validation for cores.
Run the filter-dependent scan tests with -walletpar 1 and 4, and check
that the wallet loading rescan takes the parallel path.
Parallel fast rescan is now the default, so pin the existing fast
rescans to -walletpar=1 and add the same rescans with -walletpar=4.
@Eunovo

Eunovo commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Sorry for the noise.

There are some Ralph comments interesting to address.

For example the one regarding Reorg tests miss disconnection between lookup and transaction sync. Maybe something like, the diff below would do the job. (The test is ai so may have some errors, but just to give an idea) It fails in master and passes on top of commit1.

The test you suggested works; I added it and fixed the following issues raised by Ralph:

  • Skipped-block batches can suppress GUI progress and cancellation
  • -walletpar help understates the total thread limit

and I added a release note for -walletpar

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.

10 participants