wallet: parallel fast rescan #34400

Open
Eunovo wants to merge 8 commits from new-rescan into master AGit
Eunovo commented 2026-01-24 19:46:16 +00:00 (Migrated from github.com)

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.

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 - [x] https://github.com/bitcoin/bitcoin/pull/34667 - modify the fast-rescan test to ensure that it fails when the filter is not updated properly. - [x] https://github.com/bitcoin/bitcoin/pull/34681 - refactor `CWallet::ScanForWalletTransactions` to prepare for the work in this PR. ### 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' ``` <details> <summary>Table 1 was obtained on a machine with the following specifications</summary> ``` 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 ``` </details> | 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](https://github.com/Eunovo/rescan-benchmark/blob/main/rescan_benchmark.patch) creates custom chains designed with payments at specified intervals to observe the performance of parallel fast rescan. <details> <summary> Fig 1 shown below was produced using this patch on a machine with the following specifications</summary> ``` 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 ``` </details> <img width="2840" height="1639" alt="benchmark_comparison" src="https://git.fish.foo/attachments/a9e6dbd9-15c8-4a7c-b9b3-8761b75ebdcb" /> _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](https://github.com/bitcoin/bitcoin/pull/34400/commits/15fa33740799875801707e6c8e06ff5ed480dbf1) as a baseline instead of master, since master lacks the `-walletpar` config parameter. All materials for this custom benchmark are available [here](https://github.com/Eunovo/rescan-benchmark)._
DrahtBot commented 2026-01-24 19:46:27 +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
ACK polespinasa
Concept ACK w0xlt, ismaelsadeeq, rkrux

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.

<!--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/34400 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/34400.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/34400#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 | | ---- | --------- | | ACK | [polespinasa](https://github.com/bitcoin/bitcoin/pull/34400#pullrequestreview-6188546914) | | Concept ACK | [w0xlt](https://github.com/bitcoin/bitcoin/pull/34400#issuecomment-3938433282), [ismaelsadeeq](https://github.com/bitcoin/bitcoin/pull/34400#pullrequestreview-3944480721), [rkrux](https://github.com/bitcoin/bitcoin/pull/34400#issuecomment-5427024289) | 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: * [#36904](https://github.com/bitcoin/bitcoin/pull/36904) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36904.svg"></sub> (log: Remove trailing and embedded newlines from log messages by maflcko) * [#32857](https://github.com/bitcoin/bitcoin/pull/32857) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/32857.svg"></sub> (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. <!--5faf32d7da4f0f540f40219e4f7537a3-->
DrahtBot commented 2026-01-24 20:44:47 +00:00 (Migrated from github.com)

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

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `test max 6 ancestor commits`: https://github.com/bitcoin/bitcoin/actions/runs/21320629356/job/61369934184</sub> <sub>LLM reason (✨ experimental): Compilation failed due to an unused private member (m_thread_pool) in wallet.h being treated as an error under -Werror.</sub> <details><summary>Hints</summary> 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. </details>
luke-jr commented 2026-01-29 04:50:41 +00:00 (Migrated from github.com)

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?

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 commented 2026-01-29 08:42:30 +00:00 (Migrated from github.com)

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.

> 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.
bvbfan (Migrated from github.com) reviewed 2026-02-08 08:59:21 +00:00
bvbfan (Migrated from github.com) commented 2026-02-08 08:59:21 +00:00

This slows down the scanning no? All workers already process submit task in its own WorkThread just randomly trying to acquire mutex from scanning thread is non sense to me.

This slows down the scanning no? All workers already process submit task in its own `WorkThread` just randomly trying to acquire mutex from scanning thread is non sense to me.
Eunovo (Migrated from github.com) reviewed 2026-02-08 11:40:53 +00:00
Eunovo (Migrated from github.com) commented 2026-02-08 11:40:53 +00:00

Are you referring to the ThreadPool::m_mutex? This mutex is not held during task processing. It is only briefly held to access the work queue. Calling ProcessTask() from the main thread does not slow down scanning; it gives the main thread work to do instead of wasting cycles waiting for results.

Are you referring to the `ThreadPool::m_mutex`? This mutex is not held during task processing. It is only briefly held to access the work queue. Calling `ProcessTask()` from the main thread does not slow down scanning; it gives the main thread work to do instead of wasting cycles waiting for results.
bvbfan (Migrated from github.com) reviewed 2026-02-09 18:29:24 +00:00
bvbfan (Migrated from github.com) commented 2026-02-09 18:29:24 +00:00

Yep it's not held during task execution, but if main thread do a task, it cannot put new tasks to queue i.e. workers "fight" itself to read something and do nothing. The idea is main thread submit tasks faster than workers could finish to keep all of them busy otherwise there is no difference between 3 and 16 thread (~13 threads do nothing).

Yep it's not held during task execution, but if main thread do a task, it cannot put new tasks to queue i.e. workers "fight" itself to read something and do nothing. The idea is main thread submit tasks faster than workers could finish to keep all of them busy otherwise there is no difference between 3 and 16 thread (~13 threads do nothing).
Eunovo (Migrated from github.com) reviewed 2026-02-10 09:34:04 +00:00
Eunovo (Migrated from github.com) commented 2026-02-10 09:34:04 +00:00

The main thread intentionally submits only up to WORKERS_COUNT tasks before waiting, rather than continuously submitting. This allows it to pause and update filters whenever a payment is found, preventing unnecessary work on wallets with many transactions packed into a short block range.

The main thread intentionally submits only up to `WORKERS_COUNT` tasks before waiting, rather than continuously submitting. This allows it to pause and update filters whenever a payment is found, preventing unnecessary work on wallets with many transactions packed into a short block range.
Eunovo commented 2026-02-11 17:20:49 +00:00 (Migrated from github.com)
https://github.com/bitcoin/bitcoin/pull/33689 has been merged; the cherry-picked Threadpool commit has been removed.
furszy (Migrated from github.com) reviewed 2026-02-11 20:43:14 +00:00
furszy (Migrated from github.com) left a comment

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);
      }
}
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 commented 2026-02-21 08:12:16 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
Eunovo commented 2026-02-26 16:21:49 +00:00 (Migrated from github.com)

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 https://github.com/bitcoin/bitcoin/pull/34667 and the ScanForWalletTransactions refactor into https://github.com/bitcoin/bitcoin/pull/34681.
I'll be putting this PR in draft while those PRs are open.

> 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](https://github.com/bitcoin/bitcoin/commit/633531614f69de49733642fd19cc9eba830fbdea), but into a separate PR so we can first land some good building blocks for this to happen. I moved the test change into https://github.com/bitcoin/bitcoin/pull/34667 and the `ScanForWalletTransactions` refactor into https://github.com/bitcoin/bitcoin/pull/34681. I'll be putting this PR in draft while those PRs are open.
ismaelsadeeq (Migrated from github.com) reviewed 2026-03-13 14:34:53 +00:00
ismaelsadeeq (Migrated from github.com) left a comment

Concept ACK

I attempted to reproduce the benchmarks for this
But I did not use hyperfine, I used time

System: AMD Ryzen 7 7700, 16 cores, 64GB RAM, mainnet, blocks 500000–900000, 3 runs averaged.

Baseline (881ebc4730ad15bd26e3e32ee3c9ba9d6e05552d): single-threaded fast rescan, -walletpar has no effect — consistently ~283s regardless of thread count.

Parallel scan (48154b87e2fb303ca0f3d46da29a3fbbf8758a06): fast rescan with threadpool parallelism enabled via -walletpar.

num_threads baseline parallel speedup
1 282.618s 288.214s 0.98x (slight overhead)
2 282.618s 187.485s 1.51x
4 282.618s 119.575s 2.37x
8 282.618s 81.565s 3.47x
16 282.618s 62.965s 4.53x
  • Speedup scales well up to 16 threads, going from ~283s down to ~63s — a 4.5x improvement.
  • Results are very consistent across runs (low variance), because the machine is bare metal and no other running processes apart from bitcoind are present during the benchmark runs.

Steps to reproduce

  1. Restart bitcoind with -blockfilterindex=1 till it's done.
  2. create a new wallet test
  3. Stop the node
  4. Save the script below as bench_script.sh
script
#!/usr/bin/env bash
set -euo pipefail

COMMITS=(881ebc4730ad15bd26e3e32ee3c9ba9d6e05552d 48154b87e2fb303ca0f3d46da29a3fbbf8758a06)
THREADS=(1 2 4 8 16)
RUNS=3
WALLET_NAME="test"
DATADIR="$HOME/.bitcoin"
RESULTS_CSV="results.csv"
RESULTS_MD="results.md"

echo "commit,num_threads,run,seconds" > "$RESULTS_CSV"

for commit in "${COMMITS[@]}"; do
  short="${commit:0:7}"
  git checkout "$commit"
  cmake --build build -j 20

  for num_threads in "${THREADS[@]}"; do
    echo "=== commit=$short num_threads=$num_threads ==="

    for run in $(seq 1 $RUNS); do
      echo "  run $run/$RUNS"

      # start node
      build/bin/bitcoind -blockfilterindex=1 -walletpar="$num_threads" -daemonwait
      build/bin/bitcoin-cli loadwallet "$WALLET_NAME"

      build/bin/bitcoin-cli rescanblockchain 500000 900000

      # parse timing from debug log: "Rescan completed in 284737ms"
      ms=$(grep "Rescan completed in" "$DATADIR/debug.log" | tail -1 | grep -oP '\d+(?=ms)')
      seconds=$(python3 -c "print(f'{$ms / 1000:.3f}')")

      echo "$short,$num_threads,$run,$seconds" >> "$RESULTS_CSV"
      echo "  -> ${seconds}s"

      build/bin/bitcoin-cli stop
      # wait for clean shutdown
      while build/bin/bitcoin-cli ping 2>/dev/null; do sleep 1; done
      sleep 5
    done
  done
done

# markdown table with averages
python3 - "$RESULTS_CSV" "$RESULTS_MD" <<'EOF'
import sys, csv
from collections import defaultdict

infile, outfile = sys.argv[1], sys.argv[2]

rows = list(csv.DictReader(open(infile)))
groups = defaultdict(list)
for r in rows:
    groups[(r['commit'], r['num_threads'])].append(float(r['seconds']))

with open(outfile, 'w') as f:
    f.write("| commit | num_threads | run1 | run2 | run3 | mean |\n")
    f.write("|--------|-------------|------|------|------|------|\n")
    for (commit, threads), times in sorted(groups.items()):
        mean = sum(times) / len(times)
        runs = " | ".join(f"{t:.3f}" for t in times)
        f.write(f"| {commit} | {threads} | {runs} | {mean:.3f} |\n")

print(f"Written {outfile}")
EOF

echo "Done. Results in $RESULTS_CSV and $RESULTS_MD"
  1. Make the script executable chmod +x bench_script.sh
  2. Execute the script ./bench_script.sh
  3. You can go a step further by using a top like btop https://github.com/aristocratos/btop to monitor the resource usage and how it will be well utilized when rescanning in parallel.

The current steps to reproduce in the description are stale because the commit hashes have changed since your force pushes.

Concept ACK I attempted to reproduce the benchmarks for this But I did not use hyperfine, I used time System: AMD Ryzen 7 7700, 16 cores, 64GB RAM, mainnet, blocks 500000–900000, 3 runs averaged. Baseline (881ebc4730ad15bd26e3e32ee3c9ba9d6e05552d): single-threaded fast rescan, `-walletpar` has no effect — consistently ~283s regardless of thread count. Parallel scan (48154b87e2fb303ca0f3d46da29a3fbbf8758a06): fast rescan with threadpool parallelism enabled via `-walletpar`. | num_threads | baseline | parallel | speedup | |-------------|----------|----------|---------| | 1 | 282.618s | 288.214s | 0.98x (slight overhead) | | 2 | 282.618s | 187.485s | 1.51x | | 4 | 282.618s | 119.575s | 2.37x | | 8 | 282.618s | 81.565s | 3.47x | | 16 | 282.618s | 62.965s | 4.53x | - Speedup scales well up to 16 threads, going from ~283s down to ~63s — a 4.5x improvement. - Results are very consistent across runs (low variance), because the machine is bare metal and no other running processes apart from bitcoind are present during the benchmark runs. Steps to reproduce 1. Restart bitcoind with `-blockfilterindex=1 ` till it's done. 2. create a new wallet `test` 3. Stop the node 4. Save the script below as `bench_script.sh` <details> <summary>script</summary> ```sh #!/usr/bin/env bash set -euo pipefail COMMITS=(881ebc4730ad15bd26e3e32ee3c9ba9d6e05552d 48154b87e2fb303ca0f3d46da29a3fbbf8758a06) THREADS=(1 2 4 8 16) RUNS=3 WALLET_NAME="test" DATADIR="$HOME/.bitcoin" RESULTS_CSV="results.csv" RESULTS_MD="results.md" echo "commit,num_threads,run,seconds" > "$RESULTS_CSV" for commit in "${COMMITS[@]}"; do short="${commit:0:7}" git checkout "$commit" cmake --build build -j 20 for num_threads in "${THREADS[@]}"; do echo "=== commit=$short num_threads=$num_threads ===" for run in $(seq 1 $RUNS); do echo " run $run/$RUNS" # start node build/bin/bitcoind -blockfilterindex=1 -walletpar="$num_threads" -daemonwait build/bin/bitcoin-cli loadwallet "$WALLET_NAME" build/bin/bitcoin-cli rescanblockchain 500000 900000 # parse timing from debug log: "Rescan completed in 284737ms" ms=$(grep "Rescan completed in" "$DATADIR/debug.log" | tail -1 | grep -oP '\d+(?=ms)') seconds=$(python3 -c "print(f'{$ms / 1000:.3f}')") echo "$short,$num_threads,$run,$seconds" >> "$RESULTS_CSV" echo " -> ${seconds}s" build/bin/bitcoin-cli stop # wait for clean shutdown while build/bin/bitcoin-cli ping 2>/dev/null; do sleep 1; done sleep 5 done done done # markdown table with averages python3 - "$RESULTS_CSV" "$RESULTS_MD" <<'EOF' import sys, csv from collections import defaultdict infile, outfile = sys.argv[1], sys.argv[2] rows = list(csv.DictReader(open(infile))) groups = defaultdict(list) for r in rows: groups[(r['commit'], r['num_threads'])].append(float(r['seconds'])) with open(outfile, 'w') as f: f.write("| commit | num_threads | run1 | run2 | run3 | mean |\n") f.write("|--------|-------------|------|------|------|------|\n") for (commit, threads), times in sorted(groups.items()): mean = sum(times) / len(times) runs = " | ".join(f"{t:.3f}" for t in times) f.write(f"| {commit} | {threads} | {runs} | {mean:.3f} |\n") print(f"Written {outfile}") EOF echo "Done. Results in $RESULTS_CSV and $RESULTS_MD" ``` </details> 6. Make the script executable `chmod +x bench_script.sh` 7. Execute the script `./bench_script.sh` 8. You can go a step further by using a top like btop https://github.com/aristocratos/btop to monitor the resource usage and how it will be well utilized when rescanning in parallel. The current steps to reproduce in the description are stale because the commit hashes have changed since your force pushes.
rkrux (Migrated from github.com) reviewed 2026-03-16 15:05:58 +00:00
rkrux (Migrated from github.com) left a comment

I've looked only at the 48154b8 "wallet: check blockfilters in parallel" commit partially.

I've looked only at the 48154b8 "wallet: check blockfilters in parallel" commit partially.
Lines 183-184
rkrux (Migrated from github.com) commented 2026-03-16 14:57:14 +00:00

In 48154b8 "wallet: check blockfilters in parallel"

It appears that current_block_index + 1 is equal to completed due to a int current_block_index = completed - 1; above.

In 48154b8 "wallet: check blockfilters in parallel" It appears that `current_block_index + 1` is equal to `completed` due to a `int current_block_index = completed - 1;` above.
rkrux (Migrated from github.com) commented 2026-03-16 14:03:17 +00:00

In 48154b87e2fb303ca0f3d46da29a3fbbf8758a06 "wallet: check blockfilters in parallel"

These two conditions in this check seem redundant with the same two conditions in the following for loop.

In 48154b87e2fb303ca0f3d46da29a3fbbf8758a06 "wallet: check blockfilters in parallel" These two conditions in this check seem redundant with the same two conditions in the following for loop.
Lines 194-196
rkrux (Migrated from github.com) commented 2026-03-16 14:08:54 +00:00

In 48154b87e2fb303ca0f3d46da29a3fbbf8758a06 "wallet: check blockfilters in parallel"

So it appears this is a flow where multiple tasks can be submitted in one go. There is an overload method of Submit that accepts a range of tasks & pushes all of them in the queue within one acquisition of queue lock, while notifying all the waiting workers. I think this workflow can be benefitted with this method, an untested code snippet is below because this branch is not rebased over master that contains the ranged overload.

github.com/bitcoin/bitcoin@ff7cdf633e/src/util/threadpool.h (L199-L220)

diff --git a/src/wallet/scan.cpp b/src/wallet/scan.cpp
index 6b776930f1..2295a242a1 100644
--- a/src/wallet/scan.cpp
+++ b/src/wallet/scan.cpp
@@ -147,6 +147,20 @@ std::optional<std::pair<size_t, size_t>> ChainScanner::ReadNextBlocks(const std:
         return std::make_pair<size_t, size_t>(0, m_blocks.size());
     }
     filter->UpdateIfNeeded();
+
+    auto block_matcher = [&filter](uint256 block_hash) {
+        const auto matches_block{filter->MatchesBlock(block_hash)};
+        if (matches_block.has_value()) {
+            if (*matches_block) {
+                return FilterRes::FILTER_MATCH;
+            } else {
+                return FilterRes::FILTER_NO_MATCH;
+            }
+        } else {
+            return FilterRes::FILTER_NO_FILTER;
+        }
+    }
+
     auto* thread_pool = m_wallet.m_thread_pool;
     // ThreadPool pointer should never be null here
     // during normal operation because it should
@@ -187,23 +201,13 @@ std::optional<std::pair<size_t, size_t>> ChainScanner::ReadNextBlocks(const std:
         // This prevents over-submission: if we queued all jobs upfront and the filtered
         // block range is smaller than expected, worker threads would process blocks
         // that get discarded, wasting CPU cycles.
-        const size_t job_gap = workers_count - futures.size();
-        if (job_gap > 0 && i < m_blocks.size()) {
-            for (size_t j = 0; j < job_gap && i < m_blocks.size(); ++j, ++i) {
-                auto block = m_blocks[i];
-                futures.emplace_back(*thread_pool->Submit([&filter, block = std::move(block)]() {
-                    const auto matches_block{filter->MatchesBlock(block.first)};
-                    if (matches_block.has_value()) {
-                        if (*matches_block) {
-                            return FilterRes::FILTER_MATCH;
-                        } else {
-                            return FilterRes::FILTER_NO_MATCH;
-                        }
-                    } else {
-                        return FilterRes::FILTER_NO_FILTER;
-                    }
-                }));
+        auto to_submit_jobs_count = std::min(workers_count - futures.size(), m_blocks - i);
+        if (to_submit_jobs_count) {
+            std::vector<std::function<FilterRes(uint256)>> block_matchers;
+            for (; i < to_submit_jobs_count; ++i) {
+                block_matchers.emplace_back(block_matcher(m_blocks[i].first));
             }
+            futures.emplace_back(*thread_pool->Submit(std::move(block_matchers)));
         }
 
         // If m_max_blockqueue_size blocks have been filtered,

In 48154b87e2fb303ca0f3d46da29a3fbbf8758a06 "wallet: check blockfilters in parallel" So it appears this is a flow where multiple tasks can be submitted in one go. There is an overload method of `Submit` that accepts a range of tasks & pushes all of them in the queue within one acquisition of queue lock, while notifying all the waiting workers. I think this workflow can be benefitted with this method, an untested code snippet is below because this branch is not rebased over master that contains the ranged overload. https://github.com/bitcoin/bitcoin/blob/ff7cdf633e375f151cccbcc78c7add161b3d29b8/src/util/threadpool.h#L199-L220 ```diff diff --git a/src/wallet/scan.cpp b/src/wallet/scan.cpp index 6b776930f1..2295a242a1 100644 --- a/src/wallet/scan.cpp +++ b/src/wallet/scan.cpp @@ -147,6 +147,20 @@ std::optional<std::pair<size_t, size_t>> ChainScanner::ReadNextBlocks(const std: return std::make_pair<size_t, size_t>(0, m_blocks.size()); } filter->UpdateIfNeeded(); + + auto block_matcher = [&filter](uint256 block_hash) { + const auto matches_block{filter->MatchesBlock(block_hash)}; + if (matches_block.has_value()) { + if (*matches_block) { + return FilterRes::FILTER_MATCH; + } else { + return FilterRes::FILTER_NO_MATCH; + } + } else { + return FilterRes::FILTER_NO_FILTER; + } + } + auto* thread_pool = m_wallet.m_thread_pool; // ThreadPool pointer should never be null here // during normal operation because it should @@ -187,23 +201,13 @@ std::optional<std::pair<size_t, size_t>> ChainScanner::ReadNextBlocks(const std: // This prevents over-submission: if we queued all jobs upfront and the filtered // block range is smaller than expected, worker threads would process blocks // that get discarded, wasting CPU cycles. - const size_t job_gap = workers_count - futures.size(); - if (job_gap > 0 && i < m_blocks.size()) { - for (size_t j = 0; j < job_gap && i < m_blocks.size(); ++j, ++i) { - auto block = m_blocks[i]; - futures.emplace_back(*thread_pool->Submit([&filter, block = std::move(block)]() { - const auto matches_block{filter->MatchesBlock(block.first)}; - if (matches_block.has_value()) { - if (*matches_block) { - return FilterRes::FILTER_MATCH; - } else { - return FilterRes::FILTER_NO_MATCH; - } - } else { - return FilterRes::FILTER_NO_FILTER; - } - })); + auto to_submit_jobs_count = std::min(workers_count - futures.size(), m_blocks - i); + if (to_submit_jobs_count) { + std::vector<std::function<FilterRes(uint256)>> block_matchers; + for (; i < to_submit_jobs_count; ++i) { + block_matchers.emplace_back(block_matcher(m_blocks[i].first)); } + futures.emplace_back(*thread_pool->Submit(std::move(block_matchers))); } // If m_max_blockqueue_size blocks have been filtered, ```
Lines 220-223
rkrux (Migrated from github.com) commented 2026-03-16 14:19:14 +00:00

In 48154b8 "wallet: check blockfilters in parallel"

I'm doubtful that putting the controller (non-worker) thread to process the threadpool tasks is helpful.

This threadpool is shared across wallets. It could be the case that multiple RPCs of different wallets could be called simultaneously. ProcessTask picks the first item from a shared queue in the threadpool. Can't it happen that this controller thread picks up the task of another RPC of another wallet, thereby distorting results (from a RPC latency point of view) of this one?

In 48154b8 "wallet: check blockfilters in parallel" I'm doubtful that putting the controller (non-worker) thread to process the threadpool tasks is helpful. This threadpool is shared across wallets. It could be the case that multiple RPCs of different wallets could be called simultaneously. ProcessTask picks the first item from a shared queue in the threadpool. Can't it happen that this controller thread picks up the task of another RPC of another wallet, thereby distorting results (from a RPC latency point of view) of this one?
Eunovo (Migrated from github.com) reviewed 2026-03-18 12:05:32 +00:00
Lines 220-223
Eunovo (Migrated from github.com) commented 2026-03-18 12:05:32 +00:00

I'm doubtful that putting the controller (non-worker) thread to process the threadpool tasks is helpful.

It is helpful. I had better results when I put the thread to work vs when I didn't.

Can't it happen that this controller thread picks up the task of another RPC of another wallet, thereby distorting results (from a RPC latency point of view) of this one?

True, this creates an argument to ditch the shared threadpool and create one at the begining of the scan process; the same way we initialise script threads in ConnectBlock

> I'm doubtful that putting the controller (non-worker) thread to process the threadpool tasks is helpful. It is helpful. I had better results when I put the thread to work vs when I didn't. > Can't it happen that this controller thread picks up the task of another RPC of another wallet, thereby distorting results (from a RPC latency point of view) of this one? True, this creates an argument to ditch the shared threadpool and create one at the begining of the scan process; the same way we initialise script threads in `ConnectBlock`
rkrux (Migrated from github.com) reviewed 2026-03-18 12:16:27 +00:00
Lines 220-223
rkrux (Migrated from github.com) commented 2026-03-18 12:16:27 +00:00

I was doubtful of the helpfulness of using processtask because of this cross-wallet/rpc operation.

this creates an argument to ditch the shared threadpool and create one at the begining of the scan process

Interesting, I had thought of not using the processtask function in the current thread pool setup as a way.
But an intra-wallet scan operation specific threadpool seems like a good alternative to consider.
I wll think of its implications.

I was doubtful of the helpfulness of using processtask because of this cross-wallet/rpc operation. > this creates an argument to ditch the shared threadpool and create one at the begining of the scan process Interesting, I had thought of not using the processtask function in the current thread pool setup as a way. But an intra-wallet scan operation specific threadpool seems like a good alternative to consider. I wll think of its implications.
Eunovo (Migrated from github.com) reviewed 2026-03-18 12:18:18 +00:00
Lines 194-196
Eunovo (Migrated from github.com) commented 2026-03-18 12:18:18 +00:00

I will check this when I rebase on master.

I will check this when I rebase on master.
Eunovo (Migrated from github.com) reviewed 2026-03-18 13:43:12 +00:00
Eunovo (Migrated from github.com) commented 2026-03-18 13:43:12 +00:00

Fixed.

Fixed.
Eunovo (Migrated from github.com) reviewed 2026-03-18 13:43:45 +00:00
Lines 183-184
Eunovo (Migrated from github.com) commented 2026-03-18 13:43:45 +00:00

Fixed.

Fixed.
Eunovo (Migrated from github.com) reviewed 2026-04-14 12:50:47 +00:00
Lines 194-196
Eunovo (Migrated from github.com) commented 2026-04-14 12:50:47 +00:00

Done.

Done.
Eunovo (Migrated from github.com) reviewed 2026-04-14 12:54:59 +00:00
Lines 220-223
Eunovo (Migrated from github.com) commented 2026-04-14 12:54:59 +00:00

I have changed the implementation substantially. I have moved away from a shared ThreadPool to one that is initialized before scanning and discarded after.

ProcessTask() is now only used when the main thread needs to complete the queued up jobs before the processing the selected blocks.

I have changed the implementation substantially. I have moved away from a shared ThreadPool to one that is initialized before scanning and discarded after. `ProcessTask()` is now only used when the main thread needs to complete the queued up jobs before the processing the selected blocks.
Eunovo (Migrated from github.com) reviewed 2026-04-14 12:59:29 +00:00
Eunovo (Migrated from github.com) commented 2026-04-14 12:59:29 +00:00

I have changed the implementation so that the main thread only joins task processing when it needs to clear the work queue (after a range of blocks to fetch and scan has been determined) before processing blocks. The number of blocks that can be submitted at once has been raised to 2 * WORKERS_COUNT, it is still kept low intentionally to reduce wasted work.

I have changed the implementation so that the main thread only joins task processing when it needs to clear the work queue (after a range of blocks to fetch and scan has been determined) before processing blocks. The number of blocks that can be submitted at once has been raised to `2 * WORKERS_COUNT`, it is still kept low intentionally to reduce wasted work.
l0rinc commented 2026-04-20 15:38:50 +00:00 (Migrated from github.com)

I have measured it on an Intel(R) Core(TM) i7-7700 CPU with 8 cores, 64Gi RAM and a HDD:

hyperfine --show-output \     
--export-markdown pr34400-results.md \     
--export-json pr34400-results.json \     
--sort command \      
--runs 3 \     
-L commit 68f030eef7b14d5ac6372a12864a813317ae0f4f,b62e9e739113fe58a86d23a00f8e9b1b561cd29f \     
-L num_threads 1,2,3,4,5,6,7,8,9,16 \     
--prepare 'git checkout -q {commit} && cmake -S . -B build && cmake --build build --parallel "$(nproc)" && build/bin/bitcoind -daemonwait -datadir=/mnt/my_storage/BitcoinData -connect=0 -listen=0 -dnsseed=0 -blockfilterindex=1 -wallet=bench_pr34400_20260416 -walletpar={num_threads} && build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 getwalletinfo > /dev/null' \     
--conclude 'build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData stop && sleep 10' \
'rescanblockchain 500000 900000'
image
Command Mean [s] Min [s] Max [s] Relative
rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 1) 572.300 ± 64.726 534.060 647.032 3.42 ± 0.39
rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 1) 545.611 ± 14.138 536.478 561.897 3.26 ± 0.10
rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 2) 534.545 ± 0.569 534.055 535.168 3.20 ± 0.05
rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 2) 303.284 ± 6.724 299.207 311.045 1.81 ± 0.05
rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 3) 534.895 ± 0.740 534.298 535.723 3.20 ± 0.05
rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 3) 222.130 ± 4.551 216.878 224.899 1.33 ± 0.03
rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 4) 534.069 ± 0.546 533.447 534.473 3.19 ± 0.05
rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 4) 200.326 ± 2.305 197.771 202.248 1.20 ± 0.02
rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 5) 534.699 ± 0.582 534.047 535.167 3.20 ± 0.05
rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 5) 186.884 ± 4.476 182.887 191.720 1.12 ± 0.03
rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 6) 535.054 ± 0.270 534.819 535.349 3.20 ± 0.05
rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 6) 175.091 ± 0.531 174.640 175.677 1.05 ± 0.02
rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 7) 534.670 ± 1.045 533.600 535.688 3.20 ± 0.05
rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 7) 167.224 ± 2.574 165.724 170.196 1.00
rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 8) 535.010 ± 0.121 534.875 535.105 3.20 ± 0.05
rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 8) 172.263 ± 1.808 171.188 174.350 1.03 ± 0.02
rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 9) 535.058 ± 0.383 534.660 535.425 3.20 ± 0.05
rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 9) 171.178 ± 0.138 171.053 171.326 1.02 ± 0.02
rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 16) 535.238 ± 0.204 535.013 535.412 3.20 ± 0.05
rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 16) 172.619 ± 2.656 171.043 175.685 1.03 ± 0.02
Hyperfine relative speed comparison
3.42 ±  0.39  build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 1)
3.26 ±  0.10  build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 1)
3.20 ±  0.05  build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 2)
1.81 ±  0.05  build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 2)
3.20 ±  0.05  build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 3)
1.33 ±  0.03  build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 3)
3.19 ±  0.05  build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 4)
1.20 ±  0.02  build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 4)
3.20 ±  0.05  build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 5)
1.12 ±  0.03  build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 5)
3.20 ±  0.05  build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 6)
1.05 ±  0.02  build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 6)
3.20 ±  0.05  build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 7)
1.00          build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 7)
3.20 ±  0.05  build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 8)
1.03 ±  0.02  build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 8)
3.20 ±  0.05  build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 9)
1.02 ±  0.02  build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 9)
3.20 ±  0.05  build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 16)
1.03 ±  0.02  build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 16)
I have measured it on an `Intel(R) Core(TM) i7-7700 CPU` with 8 cores, 64Gi RAM and a HDD: ```bash hyperfine --show-output \ --export-markdown pr34400-results.md \ --export-json pr34400-results.json \ --sort command \ --runs 3 \ -L commit 68f030eef7b14d5ac6372a12864a813317ae0f4f,b62e9e739113fe58a86d23a00f8e9b1b561cd29f \ -L num_threads 1,2,3,4,5,6,7,8,9,16 \ --prepare 'git checkout -q {commit} && cmake -S . -B build && cmake --build build --parallel "$(nproc)" && build/bin/bitcoind -daemonwait -datadir=/mnt/my_storage/BitcoinData -connect=0 -listen=0 -dnsseed=0 -blockfilterindex=1 -wallet=bench_pr34400_20260416 -walletpar={num_threads} && build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 getwalletinfo > /dev/null' \ --conclude 'build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData stop && sleep 10' \ 'rescanblockchain 500000 900000' ``` <img width="2084" height="740" alt="image" src="/attachments/d536a531-6f41-4268-9967-b6f6b28d7047" /> | Command | Mean [s] | Min [s] | Max [s] | Relative | |:---|---:|---:|---:|---:| | `rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 1)` | 572.300 ± 64.726 | 534.060 | 647.032 | 3.42 ± 0.39 | | `rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 1)` | 545.611 ± 14.138 | 536.478 | 561.897 | 3.26 ± 0.10 | | `rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 2)` | 534.545 ± 0.569 | 534.055 | 535.168 | 3.20 ± 0.05 | | `rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 2)` | 303.284 ± 6.724 | 299.207 | 311.045 | 1.81 ± 0.05 | | `rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 3)` | 534.895 ± 0.740 | 534.298 | 535.723 | 3.20 ± 0.05 | | `rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 3)` | 222.130 ± 4.551 | 216.878 | 224.899 | 1.33 ± 0.03 | | `rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 4)` | 534.069 ± 0.546 | 533.447 | 534.473 | 3.19 ± 0.05 | | `rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 4)` | 200.326 ± 2.305 | 197.771 | 202.248 | 1.20 ± 0.02 | | `rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 5)` | 534.699 ± 0.582 | 534.047 | 535.167 | 3.20 ± 0.05 | | `rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 5)` | 186.884 ± 4.476 | 182.887 | 191.720 | 1.12 ± 0.03 | | `rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 6)` | 535.054 ± 0.270 | 534.819 | 535.349 | 3.20 ± 0.05 | | `rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 6)` | 175.091 ± 0.531 | 174.640 | 175.677 | 1.05 ± 0.02 | | `rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 7)` | 534.670 ± 1.045 | 533.600 | 535.688 | 3.20 ± 0.05 | | `rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 7)` | 167.224 ± 2.574 | 165.724 | 170.196 | 1.00 | | `rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 8)` | 535.010 ± 0.121 | 534.875 | 535.105 | 3.20 ± 0.05 | | `rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 8)` | 172.263 ± 1.808 | 171.188 | 174.350 | 1.03 ± 0.02 | | `rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 9)` | 535.058 ± 0.383 | 534.660 | 535.425 | 3.20 ± 0.05 | | `rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 9)` | 171.178 ± 0.138 | 171.053 | 171.326 | 1.02 ± 0.02 | | `rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 16)` | 535.238 ± 0.204 | 535.013 | 535.412 | 3.20 ± 0.05 | | `rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 16)` | 172.619 ± 2.656 | 171.043 | 175.685 | 1.03 ± 0.02 | <details><summary>Hyperfine relative speed comparison</summary> ```bash 3.42 ± 0.39 build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 1) 3.26 ± 0.10 build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 1) 3.20 ± 0.05 build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 2) 1.81 ± 0.05 build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 2) 3.20 ± 0.05 build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 3) 1.33 ± 0.03 build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 3) 3.19 ± 0.05 build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 4) 1.20 ± 0.02 build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 4) 3.20 ± 0.05 build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 5) 1.12 ± 0.03 build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 5) 3.20 ± 0.05 build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 6) 1.05 ± 0.02 build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 6) 3.20 ± 0.05 build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 7) 1.00 build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 7) 3.20 ± 0.05 build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 8) 1.03 ± 0.02 build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 8) 3.20 ± 0.05 build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 9) 1.02 ± 0.02 build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 9) 3.20 ± 0.05 build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = 68f030eef7b14d5ac6372a12864a813317ae0f4f, num_threads = 16) 1.03 ± 0.02 build/bin/bitcoin-cli -rpcwait -datadir=/mnt/my_storage/BitcoinData -rpcwallet=bench_pr34400_20260416 rescanblockchain 500000 900000 (commit = b62e9e739113fe58a86d23a00f8e9b1b561cd29f, num_threads = 16) ``` </details>
DrahtBot commented 2026-05-13 21:43:52 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
Eunovo commented 2026-07-15 18:43:56 +00:00 (Migrated from github.com)

I've made some improvements which have increased the speedup from 5x at 8 threads to 8x at 8 threads. 8x speedup seems to be the peak for now. The results have been updated in the PR description, https://github.com/bitcoin/bitcoin/pull/34400#issue-3851923967

I've made some improvements which have increased the speedup from 5x at 8 threads to 8x at 8 threads. 8x speedup seems to be the peak for now. The results have been updated in the PR description, https://github.com/bitcoin/bitcoin/pull/34400#issue-3851923967
ismaelsadeeq commented 2026-07-22 12:53:20 +00:00 (Migrated from github.com)

I re-ran my script with the recent changes.

Rescan of blocks 500000-900000 (mean of 3 runs).

commit threads run1 run2 run3 mean (s) speedup
b36c2d7 (master) 1 282.488 279.832 280.120 280.813 1.00×
bf45a67 1 282.495 280.959 280.725 281.393 1.00×
bf45a67 2 139.017 138.740 137.590 138.449 2.03×
bf45a67 4 73.558 72.770 73.283 73.204 3.84×
bf45a67 8 42.863 43.172 42.746 42.927 6.54×
bf45a67 16 42.481 42.943 42.425 42.616 6.59×

I got a 6× speedup relative to master.

I re-ran my script with the recent changes. Rescan of blocks 500000-900000 (mean of 3 runs). | commit | threads | run1 | run2 | run3 | mean (s) | speedup | |--------|--------:|-----:|-----:|-----:|---------:|--------:| | b36c2d7 (master) | 1 | 282.488 | 279.832 | 280.120 | 280.813 | 1.00× | | bf45a67 | 1 | 282.495 | 280.959 | 280.725 | 281.393 | 1.00× | | bf45a67 | 2 | 139.017 | 138.740 | 137.590 | 138.449 | 2.03× | | bf45a67 | 4 | 73.558 | 72.770 | 73.283 | 73.204 | 3.84× | | bf45a67 | 8 | 42.863 | 43.172 | 42.746 | 42.927 | 6.54× | | bf45a67 | 16 | 42.481 | 42.943 | 42.425 | 42.616 | 6.59× | I got a 6× speedup relative to master.
DrahtBot commented 2026-08-14 17:53:56 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
rkrux commented 2026-08-26 14:44:34 +00:00 (Migrated from github.com)

Strong Concept ACK ae888e0, forgot to share it in the prior review.

I will get around to re-reviewing the prerequisite #34681 so that this can be moved forward.

Strong Concept ACK ae888e0, forgot to share it in the prior review. I will get around to re-reviewing the prerequisite #34681 so that this can be moved forward.
First-time contributor

4 additional verified findings in the Review report.

Earlier concerns neither republished nor resolved: 3 suggestions. See the Run archive linked from the Review report for their assessments.

🟠 Minor · Read-ahead retains stale successors after a reorg

A reorg within parallel read-ahead can turn a previously successful fast rescan into a rescan error or failed wallet load; retrying after the reorg recovers.

Location: src/wallet/scan.cpp:432 (head).

🟠 Minor · Cached NoMatch delivery misses concurrent descriptor growth

A notification-driven top-up during an unlocked parallel rescan can leave later cached NoMatch results stale, widening the pre-existing race and allowing a successful scan to omit a transaction.

Location: src/wallet/scan.cpp:450 (head).

🔵 Suggestion · The -walletpar thread limit is ambiguous for concurrent rescans

Concurrent rescans of different wallets each receive up to 16 threads, but the release note does not make the per-rescan scope explicit.

Location: src/wallet/scan.cpp:557 (head).

🔵 Suggestion · Cancellation still drains queued read-ahead filter checks

After an abort or shutdown request, parallel rescan teardown still executes every outstanding filter lookup, bounded by two read-ahead windows.

Location: src/wallet/scan.cpp:218 (head).

🔵 Suggestion · Parallel tests do not distinguish the wallet tip from the node tip

The parallel tests do not exercise stopping at the wallet's processed tip while read-ahead can still obtain newer active-chain blocks.

Location: src/wallet/test/rescan_tests.cpp:839 (head).

🔵 Suggestion · Abort coverage never tears down an active parallel scan

No rescan test aborts with parallel filter checks in flight, leaving the script-set lifetime and worker-join integration unexercised.

Location: src/wallet/scan.cpp:180 (head).

Review coverage was incomplete.


Reviewed: 67940dc7573b · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:e1a29e5e677c47d383756f0fcf8f3760725c91d1104dd3ccb2f333b6217eba26:47880f5569fd2047d249266f337c4f2a509adf7d96c3ccb1c7644c2c2a650bff --> <!-- ralph-base:2f3f6397bb92beccaccce16742f0574d1617fb3e --> <!-- ralph-head:67940dc7573b9cbc83fdc83f086590672370ae74 --> <!-- ralph-case:90b18b1feaebdfa4eb052674c317a7909a387b602d8c66d4a37f210744f03a07 --> [4 additional verified findings in the Review report](<https://review.fish.foo/report/34400-67940dc7573b9cbc83fdc83f086590672370ae74-3513-14.html>). Earlier concerns neither republished nor resolved: 3 suggestions. See the Run archive linked from the Review report for their assessments. **🟠 Minor · Read-ahead retains stale successors after a reorg** A reorg within parallel read-ahead can turn a previously successful fast rescan into a rescan error or failed wallet load; retrying after the reorg recovers. Location: [`src/wallet/scan.cpp:432`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/67940dc7573b9cbc83fdc83f086590672370ae74/src/wallet/scan.cpp#L432>) (head). **🟠 Minor · Cached `NoMatch` delivery misses concurrent descriptor growth** A notification-driven top-up during an unlocked parallel rescan can leave later cached `NoMatch` results stale, widening the pre-existing race and allowing a successful scan to omit a transaction. Location: [`src/wallet/scan.cpp:450`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/67940dc7573b9cbc83fdc83f086590672370ae74/src/wallet/scan.cpp#L450>) (head). **🔵 Suggestion · The `-walletpar` thread limit is ambiguous for concurrent rescans** Concurrent rescans of different wallets each receive up to 16 threads, but the release note does not make the per-rescan scope explicit. Location: [`src/wallet/scan.cpp:557`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/67940dc7573b9cbc83fdc83f086590672370ae74/src/wallet/scan.cpp#L557>) (head). **🔵 Suggestion · Cancellation still drains queued read-ahead filter checks** After an abort or shutdown request, parallel rescan teardown still executes every outstanding filter lookup, bounded by two read-ahead windows. Location: [`src/wallet/scan.cpp:218`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/67940dc7573b9cbc83fdc83f086590672370ae74/src/wallet/scan.cpp#L218>) (head). **🔵 Suggestion · Parallel tests do not distinguish the wallet tip from the node tip** The parallel tests do not exercise stopping at the wallet's processed tip while read-ahead can still obtain newer active-chain blocks. Location: [`src/wallet/test/rescan_tests.cpp:839`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/67940dc7573b9cbc83fdc83f086590672370ae74/src/wallet/test/rescan_tests.cpp#L839>) (head). **🔵 Suggestion · Abort coverage never tears down an active parallel scan** No rescan test aborts with parallel filter checks in flight, leaving the script-set lifetime and worker-join integration unexercised. Location: [`src/wallet/scan.cpp:180`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/67940dc7573b9cbc83fdc83f086590672370ae74/src/wallet/scan.cpp#L180>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`67940dc7573b`](<https://git.fish.foo/bitcoin/bitcoin/commit/67940dc7573b9cbc83fdc83f086590672370ae74>) · [Review report](<https://review.fish.foo/report/34400-67940dc7573b9cbc83fdc83f086590672370ae74-3513-14.html>) · [Previous reports](<https://review.fish.foo/traces/34400/>) [permalink](<https://review.fish.foo/report/34400-67940dc7573b9cbc83fdc83f086590672370ae74-3513-14.html>)
DrahtBot commented 2026-10-05 13:14:12 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
DrahtBot commented 2026-10-20 08:49:05 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
Eunovo commented 2026-11-03 09:43:20 +00:00 (Migrated from github.com)

Putting in draft while I finalize some changes.

Putting in draft while I finalize some changes.
polespinasa commented 2026-11-03 10:52:33 +00:00 (Migrated from github.com)

concept ACK

Will review when you force push and open it again :)

concept ACK Will review when you force push and open it again :)
Eunovo commented 2026-11-04 07:36:33 +00:00 (Migrated from github.com)

We replaced the previous implementation with a much simpler sliding-window implementation. New benchmark results are in https://github.com/bitcoin/bitcoin/pull/34400#issue-3851923967.

We replaced the previous implementation with a much simpler sliding-window implementation. New benchmark results are in https://github.com/bitcoin/bitcoin/pull/34400#issue-3851923967.
polespinasa (Migrated from github.com) reviewed 2026-11-18 17:53:47 +00:00
polespinasa (Migrated from github.com) left a comment

reviewed 15fa337407

will review the other 4 commits tomorrow :)

reviewed 15fa33740799875801707e6c8e06ff5ed480dbf1 will review the other 4 commits tomorrow :)
polespinasa (Migrated from github.com) commented 2026-11-18 16:59:48 +00:00

in c1b97000bc wallet/scan: combine block iteration and filtering in NextBlocksSerial

nit: in many places you use QueuedBlock and in others you use a pair of {block_hash, block_height}. I think you could just use QueuedBlock always as it represents the same pair.

diff
$ git diff
diff --git a/src/wallet/scan.cpp b/src/wallet/scan.cpp
index 155a496525..63d36e08e3 100644
--- a/src/wallet/scan.cpp
+++ b/src/wallet/scan.cpp
@@ -137,7 +137,7 @@ struct ChainScanner::ScanContext {
     //! Optional height limit of the scan range.
     const std::optional<int> max_height;
     //! The next block to read, if any.
-    std::optional<std::pair<uint256, int>> next_block;
+    std::optional<QueuedBlock> next_block;
     std::unique_ptr<FastWalletRescanFilter> filter;
     //! Verification progress of the last scanned or skipped block.
     double progress_current{0};
@@ -150,19 +150,19 @@ struct ChainScanner::ScanContext {
 
 std::optional<ChainScanner::QueuedBlock> ChainScanner::ReadNextBlock(ScanContext& ctx) {
     if (!ctx.next_block) return std::nullopt;
-    const auto [block_hash, block_height] = *ctx.next_block;
+    const QueuedBlock block{*ctx.next_block};
     // Blocks connected after this lookup are picked up by Scan() once the
     // wallet's tip moves past the last processed block.
-    ctx.next_block = FindNextBlock(ctx, block_hash, block_height);
-    return QueuedBlock{block_hash, block_height};
+    ctx.next_block = FindNextBlock(ctx, block.hash, block.height);
+    return block;
 }
 
-std::optional<std::pair<uint256, int>> ChainScanner::FindNextBlock(const ScanContext& ctx, const uint256& block_hash, int block_height) {
+std::optional<ChainScanner::QueuedBlock> ChainScanner::FindNextBlock(const ScanContext& ctx, const uint256& block_hash, int block_height) {
     bool has_next_block = false;
     uint256 next_block_hash;
     m_wallet.chain().findBlock(block_hash, FoundBlock().nextBlock(FoundBlock().inActiveChain(has_next_block).hash(next_block_hash)));
     if (!has_next_block || (ctx.max_height && block_height >= *ctx.max_height)) return std::nullopt;
-    return {{next_block_hash, block_height + 1}};
+    return QueuedBlock{next_block_hash, block_height + 1};
 }
 
 void ChainScanner::RecordSkipped(ScanContext& ctx, const QueuedBlock& block) {
@@ -301,7 +301,7 @@ ScanResult ChainScanner::Scan(const uint256& start_block, int start_height, std:
     state.progress_begin = chain.guessVerificationProgress(start_block);
     state.progress_end = chain.guessVerificationProgress(end_hash);
     ctx.progress_current = state.progress_begin;
-    ctx.next_block = {{start_block, start_height}};
+    ctx.next_block = QueuedBlock{start_block, start_height};
     ctx.block_hash = start_block;
     ctx.block_height = start_height;
     // Report progress for the given height, logging every INTERVAL_TIME.
diff --git a/src/wallet/scan.h b/src/wallet/scan.h
index df10f32f45..8cddab01ec 100644
--- a/src/wallet/scan.h
+++ b/src/wallet/scan.h
@@ -94,7 +94,7 @@ private:
     //! ctx.next_block if it exists and is within the scan range.
     std::optional<QueuedBlock> ReadNextBlock(ScanContext& ctx);
     //! The active-chain successor of a block, if it exists and is within range.
-    std::optional<std::pair<uint256, int>> FindNextBlock(const ScanContext& ctx, const uint256& block_hash, int block_height);
+    std::optional<QueuedBlock> FindNextBlock(const ScanContext& ctx, const uint256& block_hash, int block_height);
     //! Record a block skipped by the filter as the most recent successfully
     //! scanned block, and set ctx.done if it is at the wallet's tip.
     void RecordSkipped(ScanContext& ctx, const QueuedBlock& block);

<\details>

in c1b97000bcc7f975b17f3b0164a5396fa5767642 wallet/scan: combine block iteration and filtering in NextBlocksSerial nit: in many places you use `QueuedBlock` and in others you use a pair of `{block_hash, block_height}`. I think you could just use `QueuedBlock` always as it represents the same pair. <details> <summary>diff</summary> ```diff $ git diff diff --git a/src/wallet/scan.cpp b/src/wallet/scan.cpp index 155a496525..63d36e08e3 100644 --- a/src/wallet/scan.cpp +++ b/src/wallet/scan.cpp @@ -137,7 +137,7 @@ struct ChainScanner::ScanContext { //! Optional height limit of the scan range. const std::optional<int> max_height; //! The next block to read, if any. - std::optional<std::pair<uint256, int>> next_block; + std::optional<QueuedBlock> next_block; std::unique_ptr<FastWalletRescanFilter> filter; //! Verification progress of the last scanned or skipped block. double progress_current{0}; @@ -150,19 +150,19 @@ struct ChainScanner::ScanContext { std::optional<ChainScanner::QueuedBlock> ChainScanner::ReadNextBlock(ScanContext& ctx) { if (!ctx.next_block) return std::nullopt; - const auto [block_hash, block_height] = *ctx.next_block; + const QueuedBlock block{*ctx.next_block}; // Blocks connected after this lookup are picked up by Scan() once the // wallet's tip moves past the last processed block. - ctx.next_block = FindNextBlock(ctx, block_hash, block_height); - return QueuedBlock{block_hash, block_height}; + ctx.next_block = FindNextBlock(ctx, block.hash, block.height); + return block; } -std::optional<std::pair<uint256, int>> ChainScanner::FindNextBlock(const ScanContext& ctx, const uint256& block_hash, int block_height) { +std::optional<ChainScanner::QueuedBlock> ChainScanner::FindNextBlock(const ScanContext& ctx, const uint256& block_hash, int block_height) { bool has_next_block = false; uint256 next_block_hash; m_wallet.chain().findBlock(block_hash, FoundBlock().nextBlock(FoundBlock().inActiveChain(has_next_block).hash(next_block_hash))); if (!has_next_block || (ctx.max_height && block_height >= *ctx.max_height)) return std::nullopt; - return {{next_block_hash, block_height + 1}}; + return QueuedBlock{next_block_hash, block_height + 1}; } void ChainScanner::RecordSkipped(ScanContext& ctx, const QueuedBlock& block) { @@ -301,7 +301,7 @@ ScanResult ChainScanner::Scan(const uint256& start_block, int start_height, std: state.progress_begin = chain.guessVerificationProgress(start_block); state.progress_end = chain.guessVerificationProgress(end_hash); ctx.progress_current = state.progress_begin; - ctx.next_block = {{start_block, start_height}}; + ctx.next_block = QueuedBlock{start_block, start_height}; ctx.block_hash = start_block; ctx.block_height = start_height; // Report progress for the given height, logging every INTERVAL_TIME. diff --git a/src/wallet/scan.h b/src/wallet/scan.h index df10f32f45..8cddab01ec 100644 --- a/src/wallet/scan.h +++ b/src/wallet/scan.h @@ -94,7 +94,7 @@ private: //! ctx.next_block if it exists and is within the scan range. std::optional<QueuedBlock> ReadNextBlock(ScanContext& ctx); //! The active-chain successor of a block, if it exists and is within range. - std::optional<std::pair<uint256, int>> FindNextBlock(const ScanContext& ctx, const uint256& block_hash, int block_height); + std::optional<QueuedBlock> FindNextBlock(const ScanContext& ctx, const uint256& block_hash, int block_height); //! Record a block skipped by the filter as the most recent successfully //! scanned block, and set ctx.done if it is at the wallet's tip. void RecordSkipped(ScanContext& ctx, const QueuedBlock& block); ``` <\details>
polespinasa (Migrated from github.com) commented 2026-11-18 16:35:17 +00:00

in c1b97000bc wallet/scan: combine block iteration and filtering in NextBlocksSerial

This is in fact a behavior change :)

in c1b97000bcc7f975b17f3b0164a5396fa5767642 wallet/scan: combine block iteration and filtering in NextBlocksSerial This is in fact a behavior change :)
polespinasa (Migrated from github.com) commented 2026-11-18 16:03:12 +00:00

in fdb49a2b72 wallet/scan: check block is active under cs_wallet before syncing

As a small nit, I think there were some discussions about not creating more "result" enum types, and start using Expected. I think it would be cleaner to have a ScanBlockError type and return those if Unexpected happens.

diff
$ git diff
diff --git a/src/wallet/scan.cpp b/src/wallet/scan.cpp
index a4d783ef83..dc8c6612fe 100644
--- a/src/wallet/scan.cpp
+++ b/src/wallet/scan.cpp
@@ -181,7 +181,7 @@ void ChainScanner::UpdateTipIfChanged(LoopState& state) {
     }
 }
 
-ChainScanner::ScanBlockResult ChainScanner::ScanBlock(const uint256& block_hash, int block_height, bool save_progress) {
+util::Expected<void, ChainScanner::ScanBlockError> ChainScanner::ScanBlock(const uint256& block_hash, int block_height, bool save_progress) {
     // Read block data and locator if needed (the locator is usually null unless we need to save progress)
     CBlock block;
     CBlockLocator loc;
@@ -190,7 +190,7 @@ ChainScanner::ScanBlockResult ChainScanner::ScanBlock(const uint256& block_hash,
     if (save_progress) found_block.locator(loc);
     m_wallet.chain().findBlock(block_hash, found_block);
 
-    if (block.IsNull()) return ScanBlockResult::READ_FAILED;
+    if (block.IsNull()) return util::Unexpected{ScanBlockError::READ_FAILED};
 
     {
         // cs_wallet is a RecursiveMutex; ScanBlock may be called
@@ -203,7 +203,7 @@ ChainScanner::ScanBlockResult ChainScanner::ScanBlock(const uint256& block_hash,
         // undoes their confirmation.
         bool active{false};
         m_wallet.chain().findBlock(block_hash, FoundBlock().inActiveChain(active));
-        if (!active) return ScanBlockResult::NOT_ACTIVE;
+        if (!active) return util::Unexpected{ScanBlockError::NOT_ACTIVE};
         for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
             m_wallet.SyncTransaction(
                 block.vtx[posInBlock], TxStateConfirmed{block_hash, block_height,
@@ -217,7 +217,7 @@ ChainScanner::ScanBlockResult ChainScanner::ScanBlock(const uint256& block_hash,
             batch.WriteBestBlock(loc);
         }
     }
-    return ScanBlockResult::SCANNED;
+    return {};
 }
 
 ScanResult ChainScanner::Scan(const uint256& start_block, int start_height, std::optional<int> max_height,
@@ -271,9 +271,14 @@ ScanResult ChainScanner::Scan(const uint256& start_block, int start_height, std:
             fetch_block = ShouldFetchBlock(*fast_rescan_filter, block_hash, block_height);
         }
 
-        ScanBlockResult scan_result{ScanBlockResult::SCANNED};
+        util::Expected<void, ScanBlockError> scan_result;
         if (fetch_block) scan_result = ScanBlock(block_hash, block_height, save_progress && next_interval);
-        if (scan_result == ScanBlockResult::NOT_ACTIVE) {
+        if (scan_result) {
+            // scanned the block, or skipped it via the filter: record it as
+            // the most recent successfully scanned block
+            result.last_scanned_block = block_hash;
+            result.last_scanned_height = block_height;
+        } else if (scan_result.error() == ScanBlockError::NOT_ACTIVE) {
             // Abort scan if a block that needs to be inspected is no longer
             // active. A block skipped by the filter can stay skipped: it has
             // no successor in the active chain, so the scan ends successfully
@@ -282,12 +287,6 @@ ScanResult ChainScanner::Scan(const uint256& start_block, int start_height, std:
             result.last_failed_block = block_hash;
             result.status = ScanResult::FAILURE;
             break;
-        }
-        if (scan_result == ScanBlockResult::SCANNED) {
-            // scanned the block, or skipped it via the filter: record it as
-            // the most recent successfully scanned block
-            result.last_scanned_block = block_hash;
-            result.last_scanned_height = block_height;
         } else {
             // could not scan block, keep scanning but record this block as the most recent failure
             result.last_failed_block = block_hash;
diff --git a/src/wallet/scan.h b/src/wallet/scan.h
index 7f33608efa..e80e1091c0 100644
--- a/src/wallet/scan.h
+++ b/src/wallet/scan.h
@@ -6,6 +6,7 @@
 #define BITCOIN_WALLET_SCAN_H
 
 #include <uint256.h>
+#include <util/expected.h>
 #include <util/time.h>
 
 #include <atomic>
@@ -74,8 +75,7 @@ private:
         uint256 tip_hash;
     };
 
-    enum class ScanBlockResult {
-        SCANNED,
+    enum class ScanBlockError {
         READ_FAILED,
         //! The block left the active chain, so its transactions were not synced.
         NOT_ACTIVE,
@@ -84,7 +84,7 @@ private:
     //! Queue block_hash's active-chain successor into next_block if it
     //! exists and is within the scan range.
     void QueueNextBlock(const uint256& block_hash, int block_height, std::optional<std::pair<uint256, int>>& next_block, std::optional<int> max_height);
-    ScanBlockResult ScanBlock(const uint256& block_hash, int block_height, bool save_progress);
+    util::Expected<void, ScanBlockError> ScanBlock(const uint256& block_hash, int block_height, bool save_progress);
     void UpdateProgress(const LoopState& state, double progress_current, int block_height);
     void UpdateTipIfChanged(LoopState& state);
 

in fdb49a2b7264c317d04e387b3e632af00b57e26d wallet/scan: check block is active under cs_wallet before syncing As a small nit, I think there were some discussions about not creating more "result" enum types, and start using `Expected`. I think it would be cleaner to have a `ScanBlockError` type and return those if `Unexpected` happens. <details> <summary>diff</summary> ```diff $ git diff diff --git a/src/wallet/scan.cpp b/src/wallet/scan.cpp index a4d783ef83..dc8c6612fe 100644 --- a/src/wallet/scan.cpp +++ b/src/wallet/scan.cpp @@ -181,7 +181,7 @@ void ChainScanner::UpdateTipIfChanged(LoopState& state) { } } -ChainScanner::ScanBlockResult ChainScanner::ScanBlock(const uint256& block_hash, int block_height, bool save_progress) { +util::Expected<void, ChainScanner::ScanBlockError> ChainScanner::ScanBlock(const uint256& block_hash, int block_height, bool save_progress) { // Read block data and locator if needed (the locator is usually null unless we need to save progress) CBlock block; CBlockLocator loc; @@ -190,7 +190,7 @@ ChainScanner::ScanBlockResult ChainScanner::ScanBlock(const uint256& block_hash, if (save_progress) found_block.locator(loc); m_wallet.chain().findBlock(block_hash, found_block); - if (block.IsNull()) return ScanBlockResult::READ_FAILED; + if (block.IsNull()) return util::Unexpected{ScanBlockError::READ_FAILED}; { // cs_wallet is a RecursiveMutex; ScanBlock may be called @@ -203,7 +203,7 @@ ChainScanner::ScanBlockResult ChainScanner::ScanBlock(const uint256& block_hash, // undoes their confirmation. bool active{false}; m_wallet.chain().findBlock(block_hash, FoundBlock().inActiveChain(active)); - if (!active) return ScanBlockResult::NOT_ACTIVE; + if (!active) return util::Unexpected{ScanBlockError::NOT_ACTIVE}; for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) { m_wallet.SyncTransaction( block.vtx[posInBlock], TxStateConfirmed{block_hash, block_height, @@ -217,7 +217,7 @@ ChainScanner::ScanBlockResult ChainScanner::ScanBlock(const uint256& block_hash, batch.WriteBestBlock(loc); } } - return ScanBlockResult::SCANNED; + return {}; } ScanResult ChainScanner::Scan(const uint256& start_block, int start_height, std::optional<int> max_height, @@ -271,9 +271,14 @@ ScanResult ChainScanner::Scan(const uint256& start_block, int start_height, std: fetch_block = ShouldFetchBlock(*fast_rescan_filter, block_hash, block_height); } - ScanBlockResult scan_result{ScanBlockResult::SCANNED}; + util::Expected<void, ScanBlockError> scan_result; if (fetch_block) scan_result = ScanBlock(block_hash, block_height, save_progress && next_interval); - if (scan_result == ScanBlockResult::NOT_ACTIVE) { + if (scan_result) { + // scanned the block, or skipped it via the filter: record it as + // the most recent successfully scanned block + result.last_scanned_block = block_hash; + result.last_scanned_height = block_height; + } else if (scan_result.error() == ScanBlockError::NOT_ACTIVE) { // Abort scan if a block that needs to be inspected is no longer // active. A block skipped by the filter can stay skipped: it has // no successor in the active chain, so the scan ends successfully @@ -282,12 +287,6 @@ ScanResult ChainScanner::Scan(const uint256& start_block, int start_height, std: result.last_failed_block = block_hash; result.status = ScanResult::FAILURE; break; - } - if (scan_result == ScanBlockResult::SCANNED) { - // scanned the block, or skipped it via the filter: record it as - // the most recent successfully scanned block - result.last_scanned_block = block_hash; - result.last_scanned_height = block_height; } else { // could not scan block, keep scanning but record this block as the most recent failure result.last_failed_block = block_hash; diff --git a/src/wallet/scan.h b/src/wallet/scan.h index 7f33608efa..e80e1091c0 100644 --- a/src/wallet/scan.h +++ b/src/wallet/scan.h @@ -6,6 +6,7 @@ #define BITCOIN_WALLET_SCAN_H #include <uint256.h> +#include <util/expected.h> #include <util/time.h> #include <atomic> @@ -74,8 +75,7 @@ private: uint256 tip_hash; }; - enum class ScanBlockResult { - SCANNED, + enum class ScanBlockError { READ_FAILED, //! The block left the active chain, so its transactions were not synced. NOT_ACTIVE, @@ -84,7 +84,7 @@ private: //! Queue block_hash's active-chain successor into next_block if it //! exists and is within the scan range. void QueueNextBlock(const uint256& block_hash, int block_height, std::optional<std::pair<uint256, int>>& next_block, std::optional<int> max_height); - ScanBlockResult ScanBlock(const uint256& block_hash, int block_height, bool save_progress); + util::Expected<void, ScanBlockError> ScanBlock(const uint256& block_hash, int block_height, bool save_progress); void UpdateProgress(const LoopState& state, double progress_current, int block_height); void UpdateTipIfChanged(LoopState& state); ``` </details>
polespinasa (Migrated from github.com) commented 2026-11-18 17:08:14 +00:00

in 15fa337407 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;
 }

in 15fa33740799875801707e6c8e06ff5ed480dbf1 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: ```diff $ 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; } ```
Eunovo (Migrated from github.com) reviewed 2026-11-19 10:26:41 +00:00
Eunovo (Migrated from github.com) commented 2026-11-19 10:26:41 +00:00

Done.

Done.
Eunovo (Migrated from github.com) reviewed 2026-11-19 10:26:54 +00:00
Eunovo (Migrated from github.com) commented 2026-11-19 10:26:54 +00:00

Done.

Done.
polespinasa (Migrated from github.com) reviewed 2026-11-19 10:27:18 +00:00
polespinasa (Migrated from github.com) left a comment

reviewed db2d769ff2

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 5441a57e59 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 5441a57e59, and my LLM scan found the same as Ralph.

reviewed db2d769ff2ffa51d9a2800a036fb7477b58e8eb3 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 5441a57e598628e94880ffcd455cecad70845e7e 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 5441a57e598628e94880ffcd455cecad70845e7e, and my LLM scan found the same as Ralph.
Lines 167-171
polespinasa (Migrated from github.com) commented 2026-11-19 09:22:23 +00:00

in 5441a57e59 wallet/scan: check block filters in parallel

nit:

This shouldn't be uppercase. See https://github.com/bitcoin/bitcoin/blob/master/doc/developer-notes.md: "Enumerator constants may be snake_case, or PascalCase. They should not be ALL_CAPS, according to the [C++ Core Guidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#renum-caps), to avoid clashing with macros."

Also should probably use an enum class instead of just an enum per developer notes: "Prefer enum class (scoped enumerations) over enum (traditional enumerations) where possible."

in 5441a57e598628e94880ffcd455cecad70845e7e wallet/scan: check block filters in parallel nit: This shouldn't be uppercase. See https://github.com/bitcoin/bitcoin/blob/master/doc/developer-notes.md: "`Enumerator constants may be snake_case, or PascalCase. They should not be ALL_CAPS, according to the [C++ Core Guidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#renum-caps), to avoid clashing with macros.`" Also should probably use an `enum class` instead of just an `enum` per developer notes: "`Prefer enum class (scoped enumerations) over enum (traditional enumerations) where possible.`"
polespinasa (Migrated from github.com) commented 2026-11-19 09:30:32 +00:00

in ca3136699b wallet: don't rescan in parallel during IBD

In the case of IBD, if m_wallet_par > 1 probably should log that the value of m_wallet_par was ignored.

in ca3136699b8c8d926e31f04f2ad598bd5a731c9d wallet: don't rescan in parallel during IBD In the case of IBD, if `m_wallet_par > 1` probably should log that the value of `m_wallet_par` was ignored.
Eunovo (Migrated from github.com) reviewed 2026-11-19 10:28:47 +00:00
Eunovo (Migrated from github.com) commented 2026-11-19 10:28:47 +00:00

I updated the commit message to mention this second lookup. I also updated the comment.

I updated the commit message to mention this second lookup. I also updated the comment.
Eunovo (Migrated from github.com) reviewed 2026-11-19 10:36:31 +00:00
Eunovo (Migrated from github.com) commented 2026-11-19 10:36:31 +00:00

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.

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.
Eunovo (Migrated from github.com) reviewed 2026-11-19 11:29:23 +00:00
Eunovo (Migrated from github.com) commented 2026-11-19 11:29:23 +00:00

Done.

Done.
Eunovo (Migrated from github.com) reviewed 2026-11-19 11:29:39 +00:00
Lines 167-171
Eunovo (Migrated from github.com) commented 2026-11-19 11:29:39 +00:00

Done.

Done.
Eunovo commented 2026-11-19 11:45:14 +00:00 (Migrated from github.com)
CI failure seems unrelated. See https://github.com/bitcoin/bitcoin/issues/36913
w0xlt (Migrated from github.com) reviewed 2026-11-19 22:07:36 +00:00
w0xlt (Migrated from github.com) commented 2026-11-19 21:40:24 +00:00

Is there a reason to drop the anonymous namespace around FastWalletRescanFilter? The class is still only used inside scan.cpp. Keeping it preserves internal linkage and removes an unrelated change from this commit.

diff --git a/src/wallet/scan.cpp b/src/wallet/scan.cpp
index 9292b9cd8b..9a60bac7f3 100644
--- a/src/wallet/scan.cpp
+++ b/src/wallet/scan.cpp
@@ -79,6 +79,7 @@ void ChainScanner::Release() {
     m_scanning_with_passphrase = false;
 }
 
+namespace {
 class FastWalletRescanFilter
 {
 public:
@@ -146,6 +147,7 @@ private:
     std::map<uint256, int32_t> m_last_range_ends;
     GCSFilter::ElementSet m_filter_set;
 };
+} // namespace
 
 //! Blocks checked per thread-pool task, amortizing the per-task scheduling cost.
 static constexpr size_t BLOCKS_PER_FILTER_TASK{2};
Is there a reason to drop the anonymous namespace around FastWalletRescanFilter? The class is still only used inside scan.cpp. Keeping it preserves internal linkage and removes an unrelated change from this commit. ```diff diff --git a/src/wallet/scan.cpp b/src/wallet/scan.cpp index 9292b9cd8b..9a60bac7f3 100644 --- a/src/wallet/scan.cpp +++ b/src/wallet/scan.cpp @@ -79,6 +79,7 @@ void ChainScanner::Release() { m_scanning_with_passphrase = false; } +namespace { class FastWalletRescanFilter { public: @@ -146,6 +147,7 @@ private: std::map<uint256, int32_t> m_last_range_ends; GCSFilter::ElementSet m_filter_set; }; +} // namespace //! Blocks checked per thread-pool task, amortizing the per-task scheduling cost. static constexpr size_t BLOCKS_PER_FILTER_TASK{2}; ```
w0xlt (Migrated from github.com) commented 2026-11-19 21:48:39 +00:00

nit: this can be simplified for readability.

diff --git a/src/wallet/scan.cpp b/src/wallet/scan.cpp
index 9292b9cd8b..ef6a85148d 100644
--- a/src/wallet/scan.cpp
+++ b/src/wallet/scan.cpp
@@ -394,14 +394,15 @@ std::vector<ChainScanner::QueuedBlock> ChainScanner::NextBlocksSerial(ScanContex
     // repopulate filter with new scripts if top-up has happened since last iteration
     ctx.filter->Update();
 
-    auto matches_block{ctx.filter->MatchesBlock(block->hash)};
-    if (matches_block.has_value() && *matches_block) {
-        LogDebug(BCLog::SCAN, "Fast rescan: inspect block %d [%s] (filter matched)\n", block->height, block->hash.ToString());
-        return {*block};
-    } else if (!matches_block.has_value()) {
+    const auto matches_block{ctx.filter->MatchesBlock(block->hash)};
+    if (!matches_block) {
         LogDebug(BCLog::SCAN, "Fast rescan: inspect block %d [%s] (WARNING: block filter not found!)\n", block->height, block->hash.ToString());
         return {*block};
     }
+    if (*matches_block) {
+        LogDebug(BCLog::SCAN, "Fast rescan: inspect block %d [%s] (filter matched)\n", block->height, block->hash.ToString());
+        return {*block};
+    }
 
     // No match: this block needs no inspection and is skipped, even if it
     // left the active chain.
nit: this can be simplified for readability. ```diff diff --git a/src/wallet/scan.cpp b/src/wallet/scan.cpp index 9292b9cd8b..ef6a85148d 100644 --- a/src/wallet/scan.cpp +++ b/src/wallet/scan.cpp @@ -394,14 +394,15 @@ std::vector<ChainScanner::QueuedBlock> ChainScanner::NextBlocksSerial(ScanContex // repopulate filter with new scripts if top-up has happened since last iteration ctx.filter->Update(); - auto matches_block{ctx.filter->MatchesBlock(block->hash)}; - if (matches_block.has_value() && *matches_block) { - LogDebug(BCLog::SCAN, "Fast rescan: inspect block %d [%s] (filter matched)\n", block->height, block->hash.ToString()); - return {*block}; - } else if (!matches_block.has_value()) { + const auto matches_block{ctx.filter->MatchesBlock(block->hash)}; + if (!matches_block) { LogDebug(BCLog::SCAN, "Fast rescan: inspect block %d [%s] (WARNING: block filter not found!)\n", block->height, block->hash.ToString()); return {*block}; } + if (*matches_block) { + LogDebug(BCLog::SCAN, "Fast rescan: inspect block %d [%s] (filter matched)\n", block->height, block->hash.ToString()); + return {*block}; + } // No match: this block needs no inspection and is skipped, even if it // left the active chain. ```
w0xlt (Migrated from github.com) commented 2026-11-19 22:07:29 +00:00

Now that ScanContext holds the per-scan state, LoopState seems redundant.
LoopState's fields can be moved into ScanContext.
UpdateProgress and UpdateTipIfChanged can take ctx, like the other helpers.
That removes a struct and keeps all scan state in one place.

diff
diff --git a/src/wallet/scan.cpp b/src/wallet/scan.cpp
index 9292b9cd8b..56b0c5eeaa 100644
--- a/src/wallet/scan.cpp
+++ b/src/wallet/scan.cpp
@@ -337,8 +337,14 @@ struct ChainScanner::ScanContext {
     //! Checks block filters in parallel; only set when -walletpar > 1.
     //! Declared after filter, which it references, so it is destroyed first.
     std::unique_ptr<ParallelFilterChecker> checker;
+    //! Verification progress at the start and end of the scan range. Without
+    //! max_height, the end follows the wallet's tip (see UpdateTipIfChanged()).
+    double progress_begin{0};
+    double progress_end{0};
     //! Verification progress of the last scanned or skipped block.
     double progress_current{0};
+    //! The wallet's tip when progress_end was last computed.
+    uint256 tip_hash;
     //! Hash and height of the last scanned, skipped or failed block.
     uint256 block_hash;
     int block_height{0};
@@ -458,13 +464,13 @@ bool ChainScanner::HasPendingBlocks(const ScanContext& ctx) {
     return ctx.next_block || (ctx.checker && !ctx.checker->Empty());
 }
 
-void ChainScanner::UpdateProgress(const LoopState& state, double progress_current, int block_height) {
+void ChainScanner::UpdateProgress(const ScanContext& ctx, int block_height) {
     m_scanning_progress = 0;
-    double progress_diff = state.progress_end - state.progress_begin;
+    double progress_diff = ctx.progress_end - ctx.progress_begin;
 
     // avoid divide-by-zero for single block scan range (i.e. start and stop hashes are equal)
     if (progress_diff <= 0.0) return;
-    m_scanning_progress = (progress_current - state.progress_begin) / progress_diff;
+    m_scanning_progress = (ctx.progress_current - ctx.progress_begin) / progress_diff;
 
     if (block_height % 100 == 0) {
         m_wallet.ShowProgress(strprintf("[%s] %s", m_wallet.DisplayName(), _("Rescanning…")),
@@ -472,11 +478,11 @@ void ChainScanner::UpdateProgress(const LoopState& state, double progress_curren
     }
 }
 
-void ChainScanner::UpdateTipIfChanged(LoopState& state) {
+void ChainScanner::UpdateTipIfChanged(ScanContext& ctx) {
     const uint256 new_tip = WITH_LOCK(m_wallet.cs_wallet, return m_wallet.GetLastBlockHash());
-    if (new_tip != state.tip_hash) {
-        state.tip_hash = new_tip;
-        state.progress_end = m_wallet.chain().guessVerificationProgress(state.tip_hash);
+    if (new_tip != ctx.tip_hash) {
+        ctx.tip_hash = new_tip;
+        ctx.progress_end = m_wallet.chain().guessVerificationProgress(ctx.tip_hash);
     }
 }
 
@@ -551,20 +557,19 @@ ScanResult ChainScanner::Scan(const uint256& start_block, int start_height, std:
     m_wallet.ShowProgress(strprintf("[%s] %s", m_wallet.DisplayName(), _("Rescanning…")), 0);
 
     auto& result = ctx.result;
-    LoopState state;
-    state.tip_hash = WITH_LOCK(m_wallet.cs_wallet, return m_wallet.GetLastBlockHash());
-    uint256 end_hash = state.tip_hash;
-    if (max_height) chain.findAncestorByHeight(state.tip_hash, *max_height, FoundBlock().hash(end_hash));
-    state.progress_begin = chain.guessVerificationProgress(start_block);
-    state.progress_end = chain.guessVerificationProgress(end_hash);
-    ctx.progress_current = state.progress_begin;
+    ctx.tip_hash = WITH_LOCK(m_wallet.cs_wallet, return m_wallet.GetLastBlockHash());
+    uint256 end_hash = ctx.tip_hash;
+    if (max_height) chain.findAncestorByHeight(ctx.tip_hash, *max_height, FoundBlock().hash(end_hash));
+    ctx.progress_begin = chain.guessVerificationProgress(start_block);
+    ctx.progress_end = chain.guessVerificationProgress(end_hash);
+    ctx.progress_current = ctx.progress_begin;
     ctx.next_block = QueuedBlock{start_block, start_height};
     ctx.block_hash = start_block;
     ctx.block_height = start_height;
     // Report progress for the given height, logging every INTERVAL_TIME.
     // Returns whether the interval elapsed.
     const auto update_progress = [&](int height) {
-        UpdateProgress(state, ctx.progress_current, height);
+        UpdateProgress(ctx, height);
         const bool next_interval = reserver.now() >= current_time + INTERVAL_TIME;
         if (next_interval) {
             current_time = reserver.now();
@@ -607,7 +612,7 @@ ScanResult ChainScanner::Scan(const uint256& start_block, int start_height, std:
             if (ctx.done) break;
         }
         if (!ctx.done && !ctx.max_height) {
-            UpdateTipIfChanged(state);
+            UpdateTipIfChanged(ctx);
             // If nothing is pending, and the wallet's tip is past the last
             // processed block (or ctx.done would be set), blocks were connected
             // after the lookup of its successor found none. Look it up again.
diff --git a/src/wallet/scan.h b/src/wallet/scan.h
index fe27de7170..e934a6dad8 100644
--- a/src/wallet/scan.h
+++ b/src/wallet/scan.h
@@ -66,14 +66,6 @@ private:
     std::atomic<SteadyClock::time_point> m_scanning_start{SteadyClock::time_point{}};
     std::atomic<double> m_scanning_progress{0};
 
-    //! Progress window and tip tracked across Scan() iterations; only
-    //! UpdateTipIfChanged() mutates them.
-    struct LoopState {
-        double progress_begin{0};
-        double progress_end{0};
-        uint256 tip_hash;
-    };
-
     //! A block queued for filtering and scanning.
     struct QueuedBlock {
         uint256 hash;
@@ -112,8 +104,8 @@ private:
     //! Whether blocks remain to be read or delivered by the filter checker.
     static bool HasPendingBlocks(const ScanContext& ctx);
     util::Expected<void, ScanBlockError> ScanBlock(const uint256& block_hash, int block_height, bool save_progress);
-    void UpdateProgress(const LoopState& state, double progress_current, int block_height);
-    void UpdateTipIfChanged(LoopState& state);
+    void UpdateProgress(const ScanContext& ctx, int block_height);
+    void UpdateTipIfChanged(ScanContext& ctx);
 
     //! Only WalletRescanReserver may reserve and release scans, so that
     //! reservations are always managed RAII-style.
Now that S`canContext` holds the per-scan state, `LoopState` seems redundant. `LoopState`'s fields can be moved into `ScanContext`. `UpdateProgress` and `UpdateTipIfChanged` can take `ctx`, like the other helpers. That removes a struct and keeps all scan state in one place. <details> <summary>diff</summary> ```diff diff --git a/src/wallet/scan.cpp b/src/wallet/scan.cpp index 9292b9cd8b..56b0c5eeaa 100644 --- a/src/wallet/scan.cpp +++ b/src/wallet/scan.cpp @@ -337,8 +337,14 @@ struct ChainScanner::ScanContext { //! Checks block filters in parallel; only set when -walletpar > 1. //! Declared after filter, which it references, so it is destroyed first. std::unique_ptr<ParallelFilterChecker> checker; + //! Verification progress at the start and end of the scan range. Without + //! max_height, the end follows the wallet's tip (see UpdateTipIfChanged()). + double progress_begin{0}; + double progress_end{0}; //! Verification progress of the last scanned or skipped block. double progress_current{0}; + //! The wallet's tip when progress_end was last computed. + uint256 tip_hash; //! Hash and height of the last scanned, skipped or failed block. uint256 block_hash; int block_height{0}; @@ -458,13 +464,13 @@ bool ChainScanner::HasPendingBlocks(const ScanContext& ctx) { return ctx.next_block || (ctx.checker && !ctx.checker->Empty()); } -void ChainScanner::UpdateProgress(const LoopState& state, double progress_current, int block_height) { +void ChainScanner::UpdateProgress(const ScanContext& ctx, int block_height) { m_scanning_progress = 0; - double progress_diff = state.progress_end - state.progress_begin; + double progress_diff = ctx.progress_end - ctx.progress_begin; // avoid divide-by-zero for single block scan range (i.e. start and stop hashes are equal) if (progress_diff <= 0.0) return; - m_scanning_progress = (progress_current - state.progress_begin) / progress_diff; + m_scanning_progress = (ctx.progress_current - ctx.progress_begin) / progress_diff; if (block_height % 100 == 0) { m_wallet.ShowProgress(strprintf("[%s] %s", m_wallet.DisplayName(), _("Rescanning…")), @@ -472,11 +478,11 @@ void ChainScanner::UpdateProgress(const LoopState& state, double progress_curren } } -void ChainScanner::UpdateTipIfChanged(LoopState& state) { +void ChainScanner::UpdateTipIfChanged(ScanContext& ctx) { const uint256 new_tip = WITH_LOCK(m_wallet.cs_wallet, return m_wallet.GetLastBlockHash()); - if (new_tip != state.tip_hash) { - state.tip_hash = new_tip; - state.progress_end = m_wallet.chain().guessVerificationProgress(state.tip_hash); + if (new_tip != ctx.tip_hash) { + ctx.tip_hash = new_tip; + ctx.progress_end = m_wallet.chain().guessVerificationProgress(ctx.tip_hash); } } @@ -551,20 +557,19 @@ ScanResult ChainScanner::Scan(const uint256& start_block, int start_height, std: m_wallet.ShowProgress(strprintf("[%s] %s", m_wallet.DisplayName(), _("Rescanning…")), 0); auto& result = ctx.result; - LoopState state; - state.tip_hash = WITH_LOCK(m_wallet.cs_wallet, return m_wallet.GetLastBlockHash()); - uint256 end_hash = state.tip_hash; - if (max_height) chain.findAncestorByHeight(state.tip_hash, *max_height, FoundBlock().hash(end_hash)); - state.progress_begin = chain.guessVerificationProgress(start_block); - state.progress_end = chain.guessVerificationProgress(end_hash); - ctx.progress_current = state.progress_begin; + ctx.tip_hash = WITH_LOCK(m_wallet.cs_wallet, return m_wallet.GetLastBlockHash()); + uint256 end_hash = ctx.tip_hash; + if (max_height) chain.findAncestorByHeight(ctx.tip_hash, *max_height, FoundBlock().hash(end_hash)); + ctx.progress_begin = chain.guessVerificationProgress(start_block); + ctx.progress_end = chain.guessVerificationProgress(end_hash); + ctx.progress_current = ctx.progress_begin; ctx.next_block = QueuedBlock{start_block, start_height}; ctx.block_hash = start_block; ctx.block_height = start_height; // Report progress for the given height, logging every INTERVAL_TIME. // Returns whether the interval elapsed. const auto update_progress = [&](int height) { - UpdateProgress(state, ctx.progress_current, height); + UpdateProgress(ctx, height); const bool next_interval = reserver.now() >= current_time + INTERVAL_TIME; if (next_interval) { current_time = reserver.now(); @@ -607,7 +612,7 @@ ScanResult ChainScanner::Scan(const uint256& start_block, int start_height, std: if (ctx.done) break; } if (!ctx.done && !ctx.max_height) { - UpdateTipIfChanged(state); + UpdateTipIfChanged(ctx); // If nothing is pending, and the wallet's tip is past the last // processed block (or ctx.done would be set), blocks were connected // after the lookup of its successor found none. Look it up again. diff --git a/src/wallet/scan.h b/src/wallet/scan.h index fe27de7170..e934a6dad8 100644 --- a/src/wallet/scan.h +++ b/src/wallet/scan.h @@ -66,14 +66,6 @@ private: std::atomic<SteadyClock::time_point> m_scanning_start{SteadyClock::time_point{}}; std::atomic<double> m_scanning_progress{0}; - //! Progress window and tip tracked across Scan() iterations; only - //! UpdateTipIfChanged() mutates them. - struct LoopState { - double progress_begin{0}; - double progress_end{0}; - uint256 tip_hash; - }; - //! A block queued for filtering and scanning. struct QueuedBlock { uint256 hash; @@ -112,8 +104,8 @@ private: //! Whether blocks remain to be read or delivered by the filter checker. static bool HasPendingBlocks(const ScanContext& ctx); util::Expected<void, ScanBlockError> ScanBlock(const uint256& block_hash, int block_height, bool save_progress); - void UpdateProgress(const LoopState& state, double progress_current, int block_height); - void UpdateTipIfChanged(LoopState& state); + void UpdateProgress(const ScanContext& ctx, int block_height); + void UpdateTipIfChanged(ScanContext& ctx); //! Only WalletRescanReserver may reserve and release scans, so that //! reservations are always managed RAII-style. ``` </details>
w0xlt (Migrated from github.com) commented 2026-11-19 20:47:19 +00:00

nit:

        //! The block data could not be read (e.g. pruned or corrupt).
        READ_FAILED,
nit: ```suggestion //! The block data could not be read (e.g. pruned or corrupt). READ_FAILED, ```
w0xlt (Migrated from github.com) commented 2026-11-19 20:48:43 +00:00

nit:

+    //! Read a block and sync its transactions as confirmed in it.
+    //! May be called with or without cs_wallet held.
     util::Expected<void, ScanBlockError> ScanBlock(const uint256& block_hash, int block_height, bool save_progress);
nit: ```diff + //! Read a block and sync its transactions as confirmed in it. + //! May be called with or without cs_wallet held. util::Expected<void, ScanBlockError> ScanBlock(const uint256& block_hash, int block_height, bool save_progress); ```
DrahtBot commented 2026-11-23 10:51:36 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
Eunovo (Migrated from github.com) reviewed 2026-11-24 10:50:55 +00:00
Eunovo (Migrated from github.com) commented 2026-11-24 10:50:55 +00:00

Done.

Done.
Eunovo (Migrated from github.com) reviewed 2026-11-24 10:51:05 +00:00
Eunovo (Migrated from github.com) commented 2026-11-24 10:51:05 +00:00

Done.

Done.
Eunovo (Migrated from github.com) reviewed 2026-11-24 10:51:22 +00:00
Eunovo (Migrated from github.com) commented 2026-11-24 10:51:22 +00:00

Done.

Done.
Eunovo (Migrated from github.com) reviewed 2026-11-24 10:51:33 +00:00
Eunovo (Migrated from github.com) commented 2026-11-24 10:51:33 +00:00

Done.

Done.
Eunovo (Migrated from github.com) reviewed 2026-11-24 10:51:47 +00:00
Eunovo (Migrated from github.com) commented 2026-11-24 10:51:47 +00:00

Done.

Done.
polespinasa (Migrated from github.com) reviewed 2026-12-02 12:33:21 +00:00
polespinasa (Migrated from github.com) left a comment

I am close to acking it :)
reviewed cdbdfd8e93
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());

I am close to acking it :) reviewed cdbdfd8e93a0ad3883a8596c95c28c236c2cc580 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. <details> <summary>test diff</summary> ```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()); ``` </details>
Lines 167-170
polespinasa (Migrated from github.com) commented 2026-12-02 12:05:45 +00:00

faa01f0766 wallet/scan: check block filters in parallel

nit: PascalCase (also in the commit message)

faa01f0766b2c84796a2c79313dcfbc82cff4ff5 wallet/scan: check block filters in parallel nit: PascalCase (also in the commit message)
polespinasa (Migrated from github.com) commented 2026-12-02 10:47:45 +00:00

in 5fbcd6331a wallet/scan: check block is active under cs_wallet before syncing

nit:
ReadFailed and NotActive.

in 5fbcd6331a38e5a2761350da9886fa06e1bd5e1b wallet/scan: check block is active under cs_wallet before syncing nit: `ReadFailed` and `NotActive`.
polespinasa (Migrated from github.com) commented 2026-12-02 12:30:40 +00:00

in cdbdfd8e93 test: cover serial and parallel fast rescan in wallet_fast_rescan

the debug log assert checks for fast variant block filter but that matches both for parallel and serial scan. Adding the (...) characters to the check would explicitly search for the serial one.

$ git diff
diff --git a/test/functional/wallet_fast_rescan.py b/test/functional/wallet_fast_rescan.py
index efc4f29f02..06405ec536 100755
--- a/test/functional/wallet_fast_rescan.py
+++ b/test/functional/wallet_fast_rescan.py
@@ -101,7 +101,7 @@ class WalletFastRescanTest(BitcoinTestFramework):
         self.generateblock(node, output="raw(42)", transactions=[send_result['txid']])
 
         self.log.info("Import wallet backup with block filter index")
-        with node.assert_debug_log(['fast variant using block filters', *fast_rescan_messages]):
+        with node.assert_debug_log(['(fast variant using block filters)', *fast_rescan_messages]):
             node.restorewallet('rescan_fast', WALLET_BACKUP_FILENAME)
         txids_fast = self.get_wallet_txids(node, 'rescan_fast')
 
@@ -114,7 +114,7 @@ class WalletFastRescanTest(BitcoinTestFramework):
         self.log.info("Import non-active descriptors with block filter index")
         self.restart_node(0, [f'-keypool={KEYPOOL_SIZE}', '-blockfilterindex=1', '-walletpar=1'])
         node.createwallet(wallet_name='rescan_fast_nonactive', disable_private_keys=True, blank=True)
-        with node.assert_debug_log(['fast variant using block filters', *fast_rescan_messages]):
+        with node.assert_debug_log(['(fast variant using block filters)', *fast_rescan_messages]):
             w = node.get_wallet_rpc('rescan_fast_nonactive')
             w.importdescriptors([{"desc": descriptor['desc'], "timestamp": 0} for descriptor in descriptors])
         txids_fast_nonactive = self.get_wallet_txids(node, 'rescan_fast_nonactive')
@@ -138,7 +138,7 @@ class WalletFastRescanTest(BitcoinTestFramework):
         # A tip older than the maximum tip age puts the node in IBD.
         self.restart_node(0, [f'-keypool={KEYPOOL_SIZE}', '-blockfilterindex=1', '-walletpar=4', '-wallet=rescan_fast_par', f'-mocktime={int(time.time()) + 2 * 24 * 60 * 60}'])
         assert_equal(node.getblockchaininfo()['initialblockdownload'], True)
-        with node.assert_debug_log(['fast variant using block filters'], unexpected_msgs=['threads)']):
+        with node.assert_debug_log(['fast variant using block filters, -walletpar ignored during IBD'], unexpected_msgs=['threads)']):
             node.get_wallet_rpc('rescan_fast_par').rescanblockchain()
 
         self.restart_node(0, [f'-keypool={KEYPOOL_SIZE}', '-blockfilterindex=0'])

in cdbdfd8e93a0ad3883a8596c95c28c236c2cc580 test: cover serial and parallel fast rescan in wallet_fast_rescan the debug log assert checks for `fast variant block filter` but that matches both for parallel and serial scan. Adding the `(...)` characters to the check would explicitly search for the serial one. ```diff $ git diff diff --git a/test/functional/wallet_fast_rescan.py b/test/functional/wallet_fast_rescan.py index efc4f29f02..06405ec536 100755 --- a/test/functional/wallet_fast_rescan.py +++ b/test/functional/wallet_fast_rescan.py @@ -101,7 +101,7 @@ class WalletFastRescanTest(BitcoinTestFramework): self.generateblock(node, output="raw(42)", transactions=[send_result['txid']]) self.log.info("Import wallet backup with block filter index") - with node.assert_debug_log(['fast variant using block filters', *fast_rescan_messages]): + with node.assert_debug_log(['(fast variant using block filters)', *fast_rescan_messages]): node.restorewallet('rescan_fast', WALLET_BACKUP_FILENAME) txids_fast = self.get_wallet_txids(node, 'rescan_fast') @@ -114,7 +114,7 @@ class WalletFastRescanTest(BitcoinTestFramework): self.log.info("Import non-active descriptors with block filter index") self.restart_node(0, [f'-keypool={KEYPOOL_SIZE}', '-blockfilterindex=1', '-walletpar=1']) node.createwallet(wallet_name='rescan_fast_nonactive', disable_private_keys=True, blank=True) - with node.assert_debug_log(['fast variant using block filters', *fast_rescan_messages]): + with node.assert_debug_log(['(fast variant using block filters)', *fast_rescan_messages]): w = node.get_wallet_rpc('rescan_fast_nonactive') w.importdescriptors([{"desc": descriptor['desc'], "timestamp": 0} for descriptor in descriptors]) txids_fast_nonactive = self.get_wallet_txids(node, 'rescan_fast_nonactive') @@ -138,7 +138,7 @@ class WalletFastRescanTest(BitcoinTestFramework): # A tip older than the maximum tip age puts the node in IBD. self.restart_node(0, [f'-keypool={KEYPOOL_SIZE}', '-blockfilterindex=1', '-walletpar=4', '-wallet=rescan_fast_par', f'-mocktime={int(time.time()) + 2 * 24 * 60 * 60}']) assert_equal(node.getblockchaininfo()['initialblockdownload'], True) - with node.assert_debug_log(['fast variant using block filters'], unexpected_msgs=['threads)']): + with node.assert_debug_log(['fast variant using block filters, -walletpar ignored during IBD'], unexpected_msgs=['threads)']): node.get_wallet_rpc('rescan_fast_par').rescanblockchain() self.restart_node(0, [f'-keypool={KEYPOOL_SIZE}', '-blockfilterindex=0']) ```
Eunovo (Migrated from github.com) reviewed 2026-12-03 07:23:23 +00:00
Eunovo (Migrated from github.com) commented 2026-12-03 07:23:23 +00:00

Thanks, I missed this.

Thanks, I missed this.
Eunovo (Migrated from github.com) reviewed 2026-12-03 12:41:01 +00:00
Lines 167-170
Eunovo (Migrated from github.com) commented 2026-12-03 12:41:01 +00:00

Done.

Done.
Eunovo (Migrated from github.com) reviewed 2026-12-03 12:41:11 +00:00
Eunovo (Migrated from github.com) commented 2026-12-03 12:41:11 +00:00

Done.

Done.
Eunovo (Migrated from github.com) reviewed 2026-12-03 12:45:12 +00:00
Eunovo (Migrated from github.com) commented 2026-12-03 12:45:12 +00:00

Done.

Done.
Eunovo commented 2026-12-03 14:24:12 +00:00 (Migrated from github.com)

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

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
polespinasa commented 2026-12-04 10:15:20 +00:00 (Migrated from github.com)

From the remaining Ralph reports I think only this one is worth fixing.

🟠 Minor · Thread-creation failure can strand a loading wallet
An unobserved thread-exhaustion failure during a load-time parallel rescan can bypass notification cleanup, leaving the failed, unpublished wallet alive with its database locked until restart.

It is a weird case, but I don't think it is a pretty behavior to have. IIUC a failure to create a thread would lock the wallet and would make it even unable to unload or try to re-load, you would need to restart the node.
A simple fix would be to fallback to serial if threads cannot be created:

$ git diff
diff --git a/src/wallet/scan.cpp b/src/wallet/scan.cpp
index ca4f9ecbd1..e7adff1909 100644
--- a/src/wallet/scan.cpp
+++ b/src/wallet/scan.cpp
@@ -16,6 +16,7 @@
 #include <deque>
 #include <future>
 #include <memory>
+#include <system_error>
 
 using interfaces::FoundBlock;
 
@@ -552,8 +553,13 @@ ScanResult ChainScanner::Scan(const uint256& start_block, int start_height, std:
         } else if (chain.isInitialBlockDownload()) {
             log_message = "fast variant using block filters, -walletpar ignored during IBD";
         } else {
-            ctx.checker = std::make_unique<ParallelFilterChecker>(chain, *ctx.filter, "walletscan", m_wallet.m_wallet_par);
-            log_message = strprintf("fast variant using block filters (%d threads)", m_wallet.m_wallet_par);
+            try {
+                ctx.checker = std::make_unique<ParallelFilterChecker>(chain, *ctx.filter, "walletscan", m_wallet.m_wallet_par);
+                log_message = strprintf("fast variant using block filters (%d threads)", m_wallet.m_wallet_par);
+            } catch (const std::system_error& e) {
+                m_wallet.WalletLogPrintf("Unable to start rescan worker threads (%s); falling back to serial scanning.", e.what());
+                log_message = "fast variant using block filters";
+            }
         }
     }
     const auto next_blocks{ctx.checker ? &ChainScanner::NextBlocksParallel : &ChainScanner::NextBlocksSerial};

Got a clanker to code a functional test to trigger it:

test
#!/usr/bin/env python3
# Copyright (c) 2026-present The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or https://www.opensource.org/licenses/mit-license.php.
"""Fall back to serial rescanning if wallet filter workers cannot be created."""

import os
import sys

from test_framework.test_framework import BitcoinTestFramework, SkipTest
from test_framework.util import assert_equal


class WalletFastRescanThreadFailureTest(BitcoinTestFramework):
    def set_test_params(self):
        self.setup_clean_chain = True
        self.num_nodes = 1
        self.wallet_names = []
        self.extra_args = [["-blockfilterindex=1", "-walletpar=4", "-keypool=1", "-networkactive=0"]]

    def skip_test_if_missing_module(self):
        self.skip_if_no_wallet()
        if sys.platform != "linux":
            raise SkipTest("Requires Linux resource.prlimit and RLIMIT_NPROC thread limits")
        if os.getuid() == 0:
            raise SkipTest("RLIMIT_NPROC does not restrict root")

    def run_test(self):
        import resource

        node = self.nodes[0]
        self.generateblock(node, output="raw(51)", transactions=[])
        assert_equal(node.getblockchaininfo()["initialblockdownload"], False)

        node.createwallet("rescan", load_on_startup=False)
        wallet = node.get_wallet_rpc("rescan")
        address = wallet.getnewaddress()
        wallet.unloadwallet()

        # This payment must be discovered by the rescan during wallet loading.
        block_hash = self.generatetoaddress(node, 1, address)[0]
        coinbase_txid = node.getblock(block_hash)["tx"][0]
        node.wait_for_index_sync()

        self.log.info("Deny new threads only in the running node, then load the wallet")
        limits = resource.prlimit(node.process.pid, resource.RLIMIT_NPROC)
        try:
            # Existing RPC threads remain usable. Other processes retain their
            # limits, and no threads need to be created to perform a serial scan.
            resource.prlimit(node.process.pid, resource.RLIMIT_NPROC, (0, limits[1]))
            with node.assert_debug_log([
                "falling back to serial scanning",
                "(fast variant using block filters)",
            ]):
                node.loadwallet("rescan")
        finally:
            resource.prlimit(node.process.pid, resource.RLIMIT_NPROC, limits)

        assert_equal(node.listwallets(), ["rescan"])
        assert_equal(wallet.gettransaction(coinbase_txid)["confirmations"], 1)

        self.log.info("The wallet can be unloaded and loaded again")
        wallet.unloadwallet()
        assert_equal(node.listwallets(), [])
        node.loadwallet("rescan")
        assert_equal(wallet.gettransaction(coinbase_txid)["confirmations"], 1)


if __name__ == "__main__":
    WalletFastRescanThreadFailureTest(__file__).main()

From the remaining Ralph reports I think only this one is worth fixing. > 🟠 Minor · Thread-creation failure can strand a loading wallet An unobserved thread-exhaustion failure during a load-time parallel rescan can bypass notification cleanup, leaving the failed, unpublished wallet alive with its database locked until restart. It is a weird case, but I don't think it is a pretty behavior to have. IIUC a failure to create a thread would lock the wallet and would make it even unable to unload or try to re-load, you would need to restart the node. A simple fix would be to fallback to serial if threads cannot be created: ```diff $ git diff diff --git a/src/wallet/scan.cpp b/src/wallet/scan.cpp index ca4f9ecbd1..e7adff1909 100644 --- a/src/wallet/scan.cpp +++ b/src/wallet/scan.cpp @@ -16,6 +16,7 @@ #include <deque> #include <future> #include <memory> +#include <system_error> using interfaces::FoundBlock; @@ -552,8 +553,13 @@ ScanResult ChainScanner::Scan(const uint256& start_block, int start_height, std: } else if (chain.isInitialBlockDownload()) { log_message = "fast variant using block filters, -walletpar ignored during IBD"; } else { - ctx.checker = std::make_unique<ParallelFilterChecker>(chain, *ctx.filter, "walletscan", m_wallet.m_wallet_par); - log_message = strprintf("fast variant using block filters (%d threads)", m_wallet.m_wallet_par); + try { + ctx.checker = std::make_unique<ParallelFilterChecker>(chain, *ctx.filter, "walletscan", m_wallet.m_wallet_par); + log_message = strprintf("fast variant using block filters (%d threads)", m_wallet.m_wallet_par); + } catch (const std::system_error& e) { + m_wallet.WalletLogPrintf("Unable to start rescan worker threads (%s); falling back to serial scanning.", e.what()); + log_message = "fast variant using block filters"; + } } } const auto next_blocks{ctx.checker ? &ChainScanner::NextBlocksParallel : &ChainScanner::NextBlocksSerial}; ``` Got a clanker to code a functional test to trigger it: <details> <summary>test</summary> ```python #!/usr/bin/env python3 # Copyright (c) 2026-present The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or https://www.opensource.org/licenses/mit-license.php. """Fall back to serial rescanning if wallet filter workers cannot be created.""" import os import sys from test_framework.test_framework import BitcoinTestFramework, SkipTest from test_framework.util import assert_equal class WalletFastRescanThreadFailureTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 self.wallet_names = [] self.extra_args = [["-blockfilterindex=1", "-walletpar=4", "-keypool=1", "-networkactive=0"]] def skip_test_if_missing_module(self): self.skip_if_no_wallet() if sys.platform != "linux": raise SkipTest("Requires Linux resource.prlimit and RLIMIT_NPROC thread limits") if os.getuid() == 0: raise SkipTest("RLIMIT_NPROC does not restrict root") def run_test(self): import resource node = self.nodes[0] self.generateblock(node, output="raw(51)", transactions=[]) assert_equal(node.getblockchaininfo()["initialblockdownload"], False) node.createwallet("rescan", load_on_startup=False) wallet = node.get_wallet_rpc("rescan") address = wallet.getnewaddress() wallet.unloadwallet() # This payment must be discovered by the rescan during wallet loading. block_hash = self.generatetoaddress(node, 1, address)[0] coinbase_txid = node.getblock(block_hash)["tx"][0] node.wait_for_index_sync() self.log.info("Deny new threads only in the running node, then load the wallet") limits = resource.prlimit(node.process.pid, resource.RLIMIT_NPROC) try: # Existing RPC threads remain usable. Other processes retain their # limits, and no threads need to be created to perform a serial scan. resource.prlimit(node.process.pid, resource.RLIMIT_NPROC, (0, limits[1])) with node.assert_debug_log([ "falling back to serial scanning", "(fast variant using block filters)", ]): node.loadwallet("rescan") finally: resource.prlimit(node.process.pid, resource.RLIMIT_NPROC, limits) assert_equal(node.listwallets(), ["rescan"]) assert_equal(wallet.gettransaction(coinbase_txid)["confirmations"], 1) self.log.info("The wallet can be unloaded and loaded again") wallet.unloadwallet() assert_equal(node.listwallets(), []) node.loadwallet("rescan") assert_equal(wallet.gettransaction(coinbase_txid)["confirmations"], 1) if __name__ == "__main__": WalletFastRescanThreadFailureTest(__file__).main() ``` </details>
Eunovo commented 2026-12-04 11:42:29 +00:00 (Migrated from github.com)
@polespinasa re: https://github.com/bitcoin/bitcoin/pull/34400#issuecomment-7408450566 Done.
polespinasa (Migrated from github.com) reviewed 2026-12-04 12:01:14 +00:00
polespinasa (Migrated from github.com) left a comment

ACK 67940dc757

Nit: I think there is no need to create another test file for the thread failure casen, it can fit inside the wallet rescan one.

ACK 67940dc7573b9cbc83fdc83f086590672370ae74 Nit: I think there is no need to create another test file for the thread failure casen, it can fit inside the wallet rescan one.
Sign in to join this conversation.
No reviewers
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!34400
No description provided.