Skip to content

validation: fetch block input prevouts in parallel during ConnectBlock - #35295

Merged
ryanofsky merged 10 commits into
bitcoin:masterfrom
andrewtoth:threaded-inputs
Jul 9, 2026
Merged

ryanofsky merged 10 commits into
bitcoin:masterfrom
andrewtoth:threaded-inputs

Conversation

@andrewtoth

@andrewtoth andrewtoth commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

This PR is a continuation of #31132. All outstanding issues raised there have been resolved, but the volume of stale comments can make that change difficult to review.

Currently, when connecting a block, each input prevout is looked up one at a time. For every input we first check the in-memory coins cache, and on a miss we make a synchronous round-trip to the chainstate LevelDB to read the coin from disk. Because these lookups happen serially as the block is being validated, the disk read latency stacks up and dominates the time spent in ConnectBlock whenever many inputs are not already in the cache.

This PR moves those disk reads onto a pool of worker threads that run in parallel with block connection. Before entering ConnectBlock the block is handed to a CoinsViewOverlay, which kicks off the workers to begin fetching all of the block's prevouts from disk and warming the cache. The main validation thread continues to do exactly the same work it does today, hitting the cache for each input in order. The only difference is that by the time it asks, the coin is much more likely to already be there. There are no validation logic or consensus behavior changes. This is purely a parallelization of an existing read pattern.

The number of fetcher threads is configurable via -prevoutfetchthreads=<n>, defaulting to 8 and capped at 16. Setting it to 0 disables input fetching entirely and reverts to the previous serial behavior.

We have measured large performance gains for IBD and -reindex-chainstate, as well as worst-case steady-state block connection at the tip. l0rinc ran many thorough benchmarking passes on the original PR across multiple machines, storage types, dbcache sizes1, operating systems2, and fetcher thread counts3. Many other contributors also posted their benchmark results in the original PR. IBD speedups range from 1.18× to over 3× faster4. Worst-case block connection time for network-attached storage was over 2× faster5. Flamegraph comparisons before and after this change are available6.

On safety: ConnectBlock runs while holding cs_main, so nothing else in the node can mutate the chainstate while the fetchers are reading it.

On LevelDB: concurrent reads are fully supported and documented as such. We already rely on this in production today against our other LevelDB-backed databases. The txindex DB is read by multiple simultaneous HTTP RPC worker threads via the getrawtransaction RPC. The blockfilterindex DB is called concurrently from both the P2P cfilters / cfheaders / cfcheckpt message handlers on the msghand thread, and from the getblockfilter RPC on the HTTP RPC worker threads. We have not yet been issuing concurrent reads against the chainstate DB, but there is no LevelDB-side reason we can't. In fact, the chainstate DB is already being touched by more than one thread on master, because LevelDB schedules its own background compaction work.

For reviewers:

The main change is CoinsViewOverlay gets 1 new public and 2 new private methods.

  • StartFetching: public method called in lieu of CreateResetGuard before we enter ConnectBlock. It still returns a ResetGuard so the view is Reset before the block it is working on leaves scope. This kicks off worker threads who each just run while (ProcessInput()) {} and then return.
  • StopFetching: private method called on Reset whenever the guard leaves scope or Flush. Stops all threads and clears multi threaded state.
  • ProcessInput: private method that fetches a single input prevout. Returns true if an input was fetched and false otherwise. This is the only method on CoinsViewOverlay that is called concurrently by multiple threads. Every other method on the overlay is still called synchronously on the main thread.

The CoinsViewOverlay::FetchCoinFromBase method is also extended to lookup the coins fetched from ProcessInput first before falling back to base->PeekCoin.

Mutating methods Reset and Flush are overridden in CoinsViewOverlay to call StopFetching first.

Footnotes

  1. https://github.com/bitcoin/bitcoin/pull/31132#pullrequestreview-3515011880 ↩

  2. https://github.com/bitcoin/bitcoin/pull/31132#issuecomment-3767758819 ↩

  3. https://github.com/bitcoin/bitcoin/pull/31132#issuecomment-3617721711 ↩

  4. https://github.com/bitcoin/bitcoin/pull/31132#issuecomment-3678847806 ↩

  5. https://github.com/bitcoin/bitcoin/pull/31132#issuecomment-4071032270 ↩

  6. https://github.com/bitcoin/bitcoin/pull/31132#issuecomment-3617315125 ↩

@DrahtBot

DrahtBot commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

Code Coverage & Benchmarks

For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/35295.

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
ACK l0rinc, willcl-ark, theStack, ryanofsky
Concept ACK rkrux, w0xlt, jsarenik
Approach ACK sipa
Stale ACK sedited

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:

  • #35646 (RFC: Separate out runtime errors from BlockValidationState using util::Expected by yuvicc)
  • #35569 (Encapsulation for CTransaction by purpleKarrot)
  • #34132 (coins: drop error catcher, centralize fatal read handling by l0rinc)
  • #32317 (kernel: Separate UTXO set access from validation functions by sedited)
  • #28690 (build: Introduce internal kernel library by sedited)

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.

@l0rinc l0rinc left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ACK d6946a1

My concerns from the original PR were addressed, left a few ideas on how to extend code coverage but the implementation finally seems complete to me, thanks for your persistence @andrewtoth \:D/

Comment thread src/node/chainstatemanager_args.cpp Resolved
Comment thread src/validation.cpp Resolved
Comment thread src/coins.h Resolved
Comment thread src/coins.h Resolved
Comment thread src/coins.h Resolved
Comment thread src/coins.h Resolved
Comment thread src/test/fuzz/coins_view.cpp Resolved
Comment thread src/test/coinsviewoverlay_tests.cpp Resolved
Comment thread src/coins.h Resolved
Comment thread src/test/coinsviewoverlay_tests.cpp Resolved
@rkrux

rkrux commented May 20, 2026

Copy link
Copy Markdown
Contributor

I don't know when I will get around to reviewing this PR but
I do want to leave a Concept ACK d6946a1 here at this stage.

It's also very very good to see multiple use cases of the
common thread pool coming up in the codebase:
http/rpcserver, wallet chain scanning, and this.

@ryanofsky ryanofsky left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code review d6946a1. I've been meaning to review this for a while and finally getting to it now. Just one question so far below

Comment thread src/coins.h Resolved

@theStack theStack left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Concept ACK

I haven't had a chance yet to look at the code in-depth, but noticed that starting with commit a3981aa ("coins: introduce thread pool in CoinsViewOverlay"), the seemingly unrelated unit test test_LockDirectory fails on my arm64 Linux machine:

$ git rev-parse --short HEAD
a3981aa8a0
$ ./build/bin/test_bitcoin --log_level=test_suite --run_test=coinsviewoverlay_tests,util_tests
./test/util_tests.cpp(1056): Entering test case "test_LockDirectory"     
unknown location(0): fatal error: in "util_tests/test_LockDirectory": memory access violation at address: 0xffffb44470f0: no mapping at fault address
./test/util_tests.cpp(1068): last checkpoint                                                
Test is aborted                                                                             
./test/util_tests.cpp(1056): Leaving test case "test_LockDirectory"; testing time: 2099us
Test is aborted                                                                                                                                                                         
./test/util_tests.cpp(71): Leaving test suite "util_tests"; testing time: 10658us
Test is aborted                                                                                                                                                                         
Leaving test module "Bitcoin Core Test Suite"; testing time: 1008us                       
                                                                                                                                                                                        
*** 1 failure is detected in the test module "Bitcoin Core Test Suite"                                                                                                                  
./test/util_tests.cpp(1135): error: in "util_tests/test_LockDirectory": check processstatus == 0 has failed [51456 != 0]      

I suspect that the problem is that the forked unit test process in test_LockDirectory gets shut down hard, while the thread pool from the coinsviewoverlay_tests (started by StartedThreadPool) is still running. Keeping only the following minimal unit test in coinsviewoverlay_tests.cpp still fails on my machine with the command from above:

BOOST_AUTO_TEST_CASE(lockdirectory_test_fail_reproducer)
{
    CCoinsViewDB db{{.path = "", .cache_bytes = 1_MiB, .memory_only = true}, {}};
    CCoinsViewCache main_cache{&db};
    CoinsViewOverlay view{&main_cache, StartedThreadPool()};
}

If I add StartedThreadPool()->Stop(); at the end, the LockDirectory unit test failure is gone. Happy to share more details and debug if there is a suspicion that this could point to a deeper issue, though ISTM that this is only a test problem and stopping the thread pool at the end of the coinsviewoverlay test suite (with a test fixture?) would solve the problem.

Comment thread src/coins.h Resolved
Comment thread src/coins.h Resolved
Comment thread src/coins.h Resolved
Comment thread src/coins.h Resolved
Comment thread src/coins.h Resolved
Comment thread src/coins.h Resolved
Comment thread src/init.cpp Resolved
Comment thread src/node/chainstatemanager_args.cpp Resolved
Comment thread src/test/coinsviewoverlay_tests.cpp Resolved
Comment thread src/coins.h Resolved
Comment thread src/coins.h Resolved
@andrewtoth andrewtoth changed the title validation: fetch block inputs in parallel during ConnectBlock validation: fetch block input prevouts in parallel during ConnectBlock May 31, 2026
@andrewtoth

Copy link
Copy Markdown
Contributor Author

Thanks for your reviews @l0rinc @ryanofsky @theStack. I have taken most of your suggestions.

  • We no longer call ProcessInput on main thread, and just wait on the ready flag. This let's us drop const from ProcessInput.
  • Renamed all inputfetch|InputFetch to prevoutfetch|PrevoutFetch.
  • Bumped DEFAULT_PREVOUTFETCH_THREADS from 4 to 8. This was precipitated by no longer working on main thread, so we should have more workers.
  • Addressed various other suggestions.
  • The increase in diff size is mainly from adding unit tests for full code coverage.

git diff d6946a12ab306c5054b535b0b7fac0101fb306ae..e71a395dfcc01d66ad0cafdc67fd87ba1de04a4b

@l0rinc l0rinc left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The number of fetcher threads is configurable via -prevoutfetchthreads=, defaulting to 4

Could you please update the PR description?
Btw, I'm measuring the effect of 8 new threads on minimum node memory usage, will report back when it finishes.

My remaining concern after the recent changes is that I don't understand the difference between parallelism of 0 and 1 - see comments.

I remeasured reindex-chainstate with 1GB and 50GB dbcache on SSD and HDD to see the extremes (rebased to get seek competition as well): they're looking really good:

Image
i7
for DBCACHE in 1000 50000; do \
    COMMITS="fbe628756cc417dd4b6ccd9d3a709ca8e2f6023c 3e90c5e1ceecb8fcb6a4271b98e84ded171252a7"; \
    STOP=950059; CC=gcc; CXX=g++; \
    BASE_DIR="/mnt/my_storage"; DATA_DIR="$BASE_DIR/BitcoinData"; LOG_DIR="$BASE_DIR/logs"; \
    (echo ""; for c in $COMMITS; do git fetch -q origin "$c" 2>/dev/null || true; git log -1 --pretty='%h %s' $c || exit 1; done) && \
    (echo "" && echo "$(date -I) | reindex-chainstate | ${STOP} blocks | dbcache ${DBCACHE} | $(hostname) | $(uname -m) | $(lscpu | grep 'Model name' | head -1 | cut -d: -f2 | xargs) | $(nproc) cores | $(free -h | awk '/^Mem:/{print $2}') RAM | $(lsblk -no ROTA $(df --output=source $BASE_DIR | tail -1) | grep -q 1 && echo HDD || echo SSD)"; echo "") && \
    hyperfine \
    --sort command \
    --runs 1 \
    --export-json "$BASE_DIR/rdx-$(sed -E 's/[^ ]+/\L&/g;s/[.]/_/g;s/ /-/g'<<<"$COMMITS")-$STOP-$DBCACHE-$CC.json" \
    --parameter-list COMMIT ${COMMITS// /,} \
    --prepare "killall -9 bitcoind 2>/dev/null; rm -f ./build/bin/bitcoind; done"; \he=$DBCACHE -reindex-chainstate -blocksonly -connect=0 -printtoconso

fbe628756c Merge bitcoin/bitcoin#35131: guix, refactor: Minor script cleanups and improvements
3e90c5e1ce fuzz: add coins_view_stacked fuzz harness to test concurrent leveldb reads

2026-05-31 | reindex-chainstate | 950059 blocks | dbcache 1000 | i7-hdd | x86_64 | Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz | 8 cores | 62Gi RAM | HDD

Benchmark 1: COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=950059 -dbcache=1000 -reindex-chainstate -blocksonly -connect=0 -printtoconsole=0 (COMMIT = fbe628756cc417dd4b6ccd9d3a709ca8e2f6023c)
  Time (abs ≡):        30962.748 s               [User: 33946.611 s, System: 1343.201 s]

Benchmark 2: COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=950059 -dbcache=1000 -reindex-chainstate -blocksonly -connect=0 -printtoconsole=0 (COMMIT = 3e90c5e1ceecb8fcb6a4271b98e84ded171252a7)
  Time (abs ≡):        26650.647 s               [User: 38790.705 s, System: 1775.691 s]

Relative speed comparison
        1.16          COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=950059 -dbcache=1000 -reindex-chainstate -blocksonly -connect=0 -printtoconsole=0 (COMMIT = fbe628756cc417dd4b6ccd9d3a709ca8e2f6023c)
        1.00          COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=950059 -dbcache=1000 -reindex-chainstate -blocksonly -connect=0 -printtoconsole=0 (COMMIT = 3e90c5e1ceecb8fcb6a4271b98e84ded171252a7)

fbe628756c Merge bitcoin/bitcoin#35131: guix, refactor: Minor script cleanups and improvements
3e90c5e1ce fuzz: add coins_view_stacked fuzz harness to test concurrent leveldb reads

2026-06-01 | reindex-chainstate | 950059 blocks | dbcache 50000 | i7-hdd | x86_64 | Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz | 8 cores | 62Gi RAM | HDD

Benchmark 1: COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=950059 -dbcache=50000 -reindex-chainstate -blocksonly -connect=0 -printtoconsole=0 (COMMIT = fbe628756cc417dd4b6ccd9d3a709ca8e2f6023c)
  Time (abs ≡):        24869.226 s               [User: 28333.773 s, System: 779.739 s]

Benchmark 2: COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=950059 -dbcache=50000 -reindex-chainstate -blocksonly -connect=0 -printtoconsole=0 (COMMIT = 3e90c5e1ceecb8fcb6a4271b98e84ded171252a7)
  Time (abs ≡):        25187.463 s               [User: 30291.512 s, System: 885.903 s]

Relative speed comparison
        1.00          COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=950059 -dbcache=50000 -reindex-chainstate -blocksonly -connect=0 -printtoconsole=0 (COMMIT = fbe628756cc417dd4b6ccd9d3a709ca8e2f6023c)
        1.01          COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=950059 -dbcache=50000 -reindex-chainstate -blocksonly -connect=0 -printtoconsole=0 (COMMIT = 3e90c5e1ceecb8fcb6a4271b98e84ded171252a7)
i9
 for DBCACHE in 1000 50000; do \
    COMMITS="fbe628756cc417dd4b6ccd9d3a709ca8e2f6023c 3e90c5e1ceecb8fcb6a4271b98e84ded171252a7"; \
    STOP=950059; CC=gcc; CXX=g++; \
    BASE_DIR="/mnt/my_storage"; DATA_DIR="$BASE_DIR/BitcoinData"; LOG_DIR="$BASE_DIR/logs"; \
    (echo ""; for c in $COMMITS; do git fetch -q origin "$c" 2>/dev/null || true; git log -1 --pretty='%h %s' $c || exit 1; done) && \
    (echo "" && echo "$(date -I) | reindex-chainstate | ${STOP} blocks | dbcache ${DBCACHE} | $(hostname) | $(uname -m) | $(lscpu | grep 'Model name' | head -1 | cut -d: -f2 | xargs) | $(nproc) cores | $(free -h | awk '/^Mem:/{print $2}') RAM | $(lsblk -no ROTA $(df --output=source $BASE_DIR | tail -1) | grep -q 1 && echo HDD || echo SSD)"; echo "") && \
    hyperfine \
    --sort command \
    --runs 1 \
    --export-json "$BASE_DIR/rdx-$(sed -E 's/[^ ]+/\L&/g;s/[.]/_/g;s/ /-/g'<<<"$COMMITS")-$STOP-$DBCACHE-$CC.json" \
    --parameter-list COMMIT ${COMMITS// /,} \
    --prepare "killall -9 bitcoind 2>/dev/null; rm -f ./build/bin/bitcoind;done=0"; \e=$DBCACHE -reindex-chainstate -blocksonly -connect=0 -printtocon

fbe628756c Merge bitcoin/bitcoin#35131: guix, refactor: Minor script cleanups and improvements
3e90c5e1ce fuzz: add coins_view_stacked fuzz harness to test concurrent leveldb reads

2026-05-31 | reindex-chainstate | 950059 blocks | dbcache 1000 | i9-ssd | x86_64 | Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz | 16 cores | 62Gi RAM | SSD

Benchmark 1: COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=950059 -dbcache=1000 -reindex-chainstate -blocksonly -connect=0 -printtoconsole=0 (COMMIT = fbe628756cc417dd4b6ccd9d3a709ca8e2f6023c)
  Time (abs ≡):        19558.763 s               [User: 31796.752 s, System: 1064.759 s]

Benchmark 2: COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=950059 -dbcache=1000 -reindex-chainstate -blocksonly -connect=0 -printtoconsole=0 (COMMIT = 3e90c5e1ceecb8fcb6a4271b98e84ded171252a7)
  Time (abs ≡):        14958.313 s               [User: 35308.810 s, System: 1574.040 s]

Relative speed comparison
        1.31          COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=950059 -dbcache=1000 -reindex-chainstate -blocksonly -connect=0 -printtoconsole=0 (COMMIT = fbe628756cc417dd4b6ccd9d3a709ca8e2f6023c)
        1.00          COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=950059 -dbcache=1000 -reindex-chainstate -blocksonly -connect=0 -printtoconsole=0 (COMMIT = 3e90c5e1ceecb8fcb6a4271b98e84ded171252a7)

fbe628756c Merge bitcoin/bitcoin#35131: guix, refactor: Minor script cleanups and improvements
3e90c5e1ce fuzz: add coins_view_stacked fuzz harness to test concurrent leveldb reads

2026-06-01 | reindex-chainstate | 950059 blocks | dbcache 50000 | i9-ssd | x86_64 | Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz | 16 cores | 62Gi RAM | SSD

Benchmark 1: COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=950059 -dbcache=50000 -reindex-chainstate -blocksonly -connect=0 -printtoconsole=0 (COMMIT = fbe628756cc417dd4b6ccd9d3a709ca8e2f6023c)
  Time (abs ≡):        17399.201 s               [User: 25711.641 s, System: 684.138 s]

Benchmark 2: COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=950059 -dbcache=50000 -reindex-chainstate -blocksonly -connect=0 -printtoconsole=0 (COMMIT = 3e90c5e1ceecb8fcb6a4271b98e84ded171252a7)
  Time (abs ≡):        16674.033 s               [User: 27487.513 s, System: 800.722 s]

Relative speed comparison
        1.04          COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=950059 -dbcache=50000 -reindex-chainstate -blocksonly -connect=0 -printtoconsole=0 (COMMIT = fbe628756cc417dd4b6ccd9d3a709ca8e2f6023c)
        1.00          COMPILER=gcc ./build/bin/bitcoind -datadir=/mnt/my_storage/BitcoinData -stopatheight=950059 -dbcache=50000 -reindex-chainstate -blocksonly -connect=0 -printtoconsole=0 (COMM

Comment thread src/coins.h Resolved
Comment thread src/coins.h Resolved
Comment thread src/coins.h Resolved
Comment thread src/test/coinsviewoverlay_tests.cpp Resolved
Comment thread src/node/chainstatemanager_args.cpp Resolved
Comment thread src/test/coinsviewoverlay_tests.cpp Resolved
Comment thread src/test/coinsviewoverlay_tests.cpp Resolved
Comment thread src/test/coinsviewoverlay_tests.cpp Resolved
Comment thread src/test/coinsviewoverlay_tests.cpp Resolved
Comment thread src/validation.h Resolved
@andrewtoth

Copy link
Copy Markdown
Contributor Author

Thanks for the review @l0rinc, addressed all suggestions.

@l0rinc l0rinc left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

CI would probably pass after a rebase (which would also get us the seek compaction fixes)

Comment thread src/coins.h Resolved
Comment thread src/coins.h Resolved
Comment thread src/test/fuzz/coins_view.cpp Resolved
@andrewtoth

Copy link
Copy Markdown
Contributor Author

Rebased on master to test compatibility with bitcoin-core/leveldb-subtree#61.

Also addressed #35295 (comment) (thanks @l0rinc).

git range-diff 9961229360..22066bfb4c 7c2718a4b8..9db6f241c7

@ryanofsky ryanofsky self-assigned this Jul 9, 2026
@ryanofsky
ryanofsky merged commit c0e91ef into bitcoin:master Jul 9, 2026
26 checks passed
@andrewtoth
andrewtoth deleted the threaded-inputs branch July 9, 2026 00:52
@andrewtoth

Copy link
Copy Markdown
Contributor Author

Thank you everyone! 🍾

std::shared_ptr<ThreadPool> g_thread_pool{std::make_shared<ThreadPool>("view_fuzz")};
Mutex g_thread_pool_mutex;

void StartPoolIfNeeded() EXCLUSIVE_LOCKS_REQUIRED(!g_thread_pool_mutex)

@maflcko maflcko Jul 9, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: Silent merge conflict with style-cleanup commit 48df093 (aka remove the unused/confusing mutex in this fuzz test)?

Would be good to remove it here as well.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@marcofleon did you want to follow up here?

oleonardolima added a commit to oleonardolima/rust-bitcoinkernel that referenced this pull request Jul 9, 2026
…05fc7ab

81405fc7ab Merge bitcoin/bitcoin#35689: test: Inline incorrect check in `util_tests`
cd2a4bc510 test: Redeclare variable as signed in `util_tests`
6f1c56f03a Merge bitcoin/bitcoin#35670: net: optimize compact block extra tx iteration
e94fda8a40 Merge bitcoin/bitcoin#35685: doc: Archive 30.3 release notes
5223cf1795 Merge bitcoin/bitcoin#35616: refactor: Use u64 over size_t for all cache sizes to fix a 32-bit overflow
c0e91efdb3 Merge bitcoin/bitcoin#35295: validation: fetch block input prevouts in parallel during ConnectBlock
f0da26cfc8 Merge bitcoin/bitcoin#34997: p2p: Don't participate in addr relay with feelers
443179a9eb doc: Archive 30.3 release notes
fabafd91f1 refactor: Use u64 over size_t for all cache sizes to fix a 32-bit overflow
32941e1314 Merge bitcoin/bitcoin#35649: depends: move FreeBSD SDK handling to CI
f379d716b1 Merge bitcoin/bitcoin#35669: doc: archive release notes for v31.1
881bb7b355 Merge bitcoin/bitcoin#35673: refactor: Move LoadGenesisBlock to ChainstateManager
3f3e644beb Merge bitcoin/bitcoin#35678: private broadcast: define and use new RPC_LIMIT_EXCEEDED error code ( + other follow-ups)
e3b026bf56 Merge bitcoin/bitcoin#34020: mining: add getTransactions(ByWitnessID) IPC methods
62f9089343 Merge bitcoin/bitcoin#35386: doc: add an AI contribution policy
fa615bd163 refactor: Move LoadGenesisBlock to ChainstateManager
8ac222484c private broadcast: remove no-op [[nodiscard]]
191bdcba26 test: align test better with described scenario
7ad311be18 test: use BOOST_CHECK_EQUAL for PrivateBroadcast::AddResult
82a02a2a22 rpc: define and use new  RPC_LIMIT_EXCEEDED error code
a64df338e6 Merge bitcoin/bitcoin#35651: doc: Improve offline-signing-tutorial after 32489
4498fa5d5b Merge bitcoin/bitcoin#35406: private broadcast: limit outstanding txs to count of 10,000
ec5edcd72b Merge bitcoin/bitcoin#35661: Update libmultiprocess subtree to add `ThreadMap.makePool` method
ea67fea062 Merge bitcoin/bitcoin#35464: kernel: Add function for creating chainparams with a signet challenge
a7b5f23bb8 Merge bitcoin/bitcoin#35667: refactor: Use `NetworkErrorString` for macOS code in `netif.cpp`
69fc991791 Merge bitcoin/bitcoin#32606: p2p: Drop unsolicited CMPCTBLOCK from non-HB peer and when blocksonly
1a3cbf1bd2 net: optimize compact block extra tx iteration
bc33509ae2 Merge bitcoin/bitcoin#35650: doc: Add release notes for 32489 (exportwatchonlywallet RPC)
2b6e767d96 doc: archive release notes for v31.1
b0735336ee p2p: Don't participate in addr relay with feeler connections
302733fd96 Merge bitcoin/bitcoin#35652: init: fix reindex deadlock by waking cv after interrupt
c1313b199f init: wake genesis wait after ImportBlocks() returns
eccb04a321 refactor: Use `NetworkErrorString` for macOS code in `netif.cpp`
f79ecfd9c7 Merge bitcoin/bitcoin#35658: refactor: Drop unneeded `<sys/types.h>` include before `<ifaddrs.h>`
22ac4ad949 ci: ensure we use correct lld version in OpenBSD job
495f43f7b3 ci: FreeBSD 15.1
244739db9d depends: move FreeBSD SDK handling to CI
bab0120053 Merge bitcoin/bitcoin#35621: validation: Ignore eventual error message from flushing in AcceptBlock
02afa66169 Merge commit '6b0a907302364649dcaffeb0340b985f14141b4e' into pr/subtree-11
6b0a907302 Squashed 'src/ipc/libmultiprocess/' changes from 3edbe8f67c1..16bf05dea02
22c328d388 refactor: Drop unneeded `<sys/types.h>` include before `<ifaddrs.h>`
2063f02bd5 Merge bitcoin/bitcoin#35510: test: SOCKS5 proxy: expect that connection may be reset during SOCKS5 handshake or data forwarding
1360001f43 Merge bitcoin/bitcoin#34959: wallet: Enforce BDB btree levels and overflow item sizes
10ffef4b3b Merge bitcoin/bitcoin#35604: log: expose `-logratelimit` in normal help
b393985aa0 Merge bitcoin/bitcoin#35634: txospenderindex: use zero-byte entry values
1835f2fcbf Merge bitcoin/bitcoin#35653: fuzz: Remove `ConsumeUniValue`
9f3e427228 fuzz: Remove ConsumeUniValue
68cb7840d2 doc: improve offline-signing-tutorial after 32489
32ddfc92d9 Merge bitcoin/bitcoin#35599: doc: Add release notes for #33671 (getbalances nonmempool field)
f56804bcf5 Merge bitcoin/bitcoin#35640: ci: use a 8x instance over 16x for riscv job
239d6c5260 Merge bitcoin/bitcoin#35614: HTTPServer: Prevent race condition between worker thread and I/O thread
cddbad325d doc: Add release notes for 32489 (exportwatchonlywallet RPC)
0a1bbec688 Merge bitcoin/bitcoin#32489: wallet: Add `exportwatchonlywallet` RPC to export a watchonly version of a wallet
4a007126fb Merge bitcoin/bitcoin#35147: depends: Boost 1.91.0-1
31abaa264c doc: add an AI contribution policy
a15bdc0598 doc: update offline-signing-tutorial to use exportwatchonlywallet rpc
a388076401 test: Test for exportwatchonlywallet
d053e3e5c8 wallet, rpc: Add exportwatchonlywallet RPC
444878efef wallet: Add CWallet::ExportWatchOnly
f9273f01db wallet: Move listdescriptors retrieving from RPC to CWallet
a1c83789a7 wallet: Write new descriptor's cache in AddWalletDescriptor
1e996640e6 wallet: Use Descriptor::CanSelfExpand() in CanGetAddresses()
d2ee9227da descriptor: Add CanSelfExpand()
2990bd7735 Merge bitcoin/bitcoin#35118: fuzz: add ipc round-trip fuzz target
fb1d152c24 depends: Boost 1.91.0-1
ba48852f9e Merge bitcoin/bitcoin#35438: test: introduce NodeSigner, run feature_taproot.py without wallet compiled
47bbed052e ci: use true|false over "true|false"
9a25bc3989 ci: use a 8x instance over 16x
9871dc7ab4 Merge bitcoin/bitcoin#31425: CI: Add Riscv bare metal job
113402286e doc: add txospenderindex release note
ce06878288 index: shrink txospenderindex value markers
a99148d576 test kernel: Don't log on warnings change
5b4fd284f4 kernel: Generate a signet with a challenge
037ad77071 fuzz: add IPC round-trip target
a8823c0996 Merge bitcoin/bitcoin#35607: nanobench: fix performance counter buffer initialization
f26c15bdd2 Merge bitcoin/bitcoin#35397: ci: add OpenBSD Clang cross job
91586f701e test: introduce NodeSigner, run feature_taproot.py without wallet compiled
771200ca43 test: return full keypair from `getnewdestination` helper
4e29de719e private broadcast: add release note for limited cap
cbf8c107c1 Release cs_main between individual private tx re-attempts
5aea3d0373 private broadcast: limit outstanding txs to count of 10,000
dc282ff31d Merge bitcoin/bitcoin#35597: logging: More fully remove libevent log category
ec98037f7a Merge bitcoin/bitcoin#35615: fuzz: restore CreateSock in PCP targets
43d89bb6e1 Merge bitcoin/bitcoin#35610: bitcoin-util: Add netmagic command
e35c805489 Merge bitcoin/bitcoin#35129: test: add fuzz test for private broadcast
dc1c17c085 doc: add release notes
0e10937184 fuzz: add coins_view_stacked fuzz harness to test concurrent leveldb reads
ce610a6ff4 fuzz: update harnesses to cover CoinsViewOverlay::StartFetching
760fb22dc3 test: add unit tests for CoinsViewOverlay::StartFetching
d69a3b20de doc: update CoinsViewOverlay docstring to describe parallel fetching
ab2a379237 coins: fetch inputs in parallel
fdf283036a coins: add ready flag to InputToFetch
ede11b8314 validation: collect block inputs in CoinsViewOverlay before ConnectBlock
f82043af50 coins: introduce thread pool in CoinsViewOverlay
5bf1c32008 validation: add -prevoutfetchthreads configuration option
a318f43254 bitcoin-util: Add netmagic command
256482ab56 validation: In AcceptBlock, ignore flush result
3c76bd4356 Merge bitcoin/bitcoin#35603: build: QRencode cleanups
f595daf1dd test: ensure HTTPServer race condition is fixed
b98b10c072 test: introduce a worker thread in http socket error test
922b08d375 test: socket error handling in HTTPServer using ErrorSock mock socket
73da2a8a52 http: prevent race condition between worker thread and I/O thread
57b3bf8496 Merge bitcoin/bitcoin#35609: ci: Bump tsan config to ubuntu:26.04 with -U_FORTIFY_SOURCE
d64ea15824 ci: add openBSD cross CI job
5404b62074 depends: add openbsd_LDFLAGS
2a9e35d293 Merge bitcoin/bitcoin#35588: scripted-diff: Rename `Sock::{RECV,SEND,ERR}`
a0e5e30010 fuzz: restore CreateSock in PCP targets
41ceea400e scripted-diff: Rename `StatusLevel::{INFO,WARN,ERR}`
f395acdeee scripted-diff: Rename `Sock::{RECV,SEND,ERR}`
7a74f65293 Merge bitcoin/bitcoin#35536: fuzz: share a single mocked steady clock across FuzzedSock instances
e1290ce7f7 Merge bitcoin/bitcoin#35543: test: introduce ExtendedPrivateKey and ExtendedPublicKey classes
7ac25c9177 util, refactor: Rename local `ERR` in `Sock::Accept`
bbbbab86a8 ci: Bump tsan config to ubuntu:26.04 with -U_FORTIFY_SOURCE
095596ddf7 log: expose -logratelimit option
ea9afb61a1 Merge bitcoin/bitcoin#35602: doc: Clarify build docs about `pkgconf` / `pkg-config` requirements
672eedc46b Merge bitcoin/bitcoin#35220: fuzz: connman: strengthen assertions and extend coverage
0e5c718d8a Merge bitcoin/bitcoin#35506: test: ensure group data cluster pointers are live
b6b1d0653a nanobench: fix perf counter buffer init
93012d7ff9 Merge bitcoin/bitcoin#35601: wallet: remove experimental warning from send and sendall
829255c8be cmake: Remove `SelectLibraryConfigurations` from `FindQRencode` module
5c55606da9 depends: Remove unused `lib/pkgconfig` in `qrencode` package
402ba10b20 cmake: Drop optional `PkgConfig` use in `FindQRencode` module
8ebfff0f88 doc: add send RPC release note
fb8a103886 doc: Clarify build docs about `pkgconf` / `pkg-config` requirements
5884f5a4fa wallet: remove experimental warning from send RPCs
7b84e5106c Merge bitcoin/bitcoin#35595: ci: remove some packages from Chimera job
58560c281d ci: remove some packages from Chimera job
295ce6f45c Merge bitcoin/bitcoin#35576: test: raise `feature_reindex` RPC timeout
b36730a3ef  Add CI job for riscv bare metal
bfdbf513f6 Add CI job for producing a static bare metal binary
a9a1d92a1d build: Add option for building for bare metal envs
9b2ef81757 doc: add release notes for #33671 (getbalances nonmempool field)
633044f143 Merge bitcoin/bitcoin#35266: rpc, wallet: add an option to not load the wallet after migrating
d6269e2a90 Merge bitcoin/bitcoin#35594: fuzz: cover async chainstate compaction
3765b428d1 logging: More fully remove libevent log category
703a671fbc fuzz: compact coins view db during fuzzing
0868c85fd5 refactor: rename async coin compaction
6fa4132298 fuzz: share a single mocked steady clock across FuzzedSock instances
8791c4764c test: use ExtendedPrivateKey in wallet_taproot.py
89ceafafb9 test: use ExtendedPrivateKey in wallet_listdescriptors.py
bbfffcab58 test: use ExtendedPrivateKey in wallet_send.py
2ab6e590f7 test: use ExtendedPrivateKey in wallet_keypool.py
9e20118720 test: use ExtendedPrivateKey in wallet_fundrawtransaction.py
06af0cddbb test: use ExtendedPrivateKey in wallet_descriptor.py
4100fac20e test: use ExtendedPrivateKey in wallet_createwallet.py
ff3f6def9a test: use ExtendedPrivateKey in wallet_bumpfee.py
003f2a01f6 test: use ExtendedPrivateKey in feature_notifications.py
f988e6d6e6 test: use ExtendedPrivateKey in wallet_importdescriptors.py
0cdd817a82 add release note
517d37ce3e test: tests wallet migration with load_wallet disabled
b98dd63da7 rpc: Add load_wallet argument to migratewallet RPC
4acd063ba6 wallet: make loading the wallet after migrating optional
1a3cfdf1b7 fuzz: connman: cover AddLocalServices/RemoveLocalServices
c507fb3063 fuzz: connman: add outbound-bytes invariants
4a6fce43ea fuzz: connman: add AddNode/RemoveAddedNode invariants
9e6546c517 test: raise reindex mining RPC timeout
d2a03d50ac test: add extendedkey.py unit tests by using BIP32 test vectors
afdb378082 test: introduce ExtendedPrivateKey and ExtendedPublicKey classes
55e3a57f22 qa: Avoid UTXO reuse between test functions
9c5dd2926a p2p: Ignore CMPCTBLOCK from peer that hasn't sent SENDCMPCT
bf9884f4e5 p2p: make blocksonly nodes ignore CMPCTBLOCK messages
92cea63c71 test: (Un)solicited invalid cb -> get disconnected.
e845e26344 test: p2p: Nodes ignore unsolicited CMPCTBLOCK's
8313591715 p2p: Drop unsolicited CMPCTBLOCK from non-HB peer
44f377a71f refactor: test: Static assert_highbandwidth_states
25457a3272 test: Tighten getblocktxn checks in parallel cb reconstruction test.
2ee4fafa3f test: add fuzz test for private broadcast
08b7c61fc7 private broadcast: enforce sending to unique node ids
9a8ef9b0a3 test: SOCKS5 proxy: expect that connection may be reset during handshake
eb3208364a test: SOCKS5 proxy: expect that connection may be reset when forwarding
4dbaa7cc65 test: generalise byte_to_base58 utility function to allow more version types
df9eb72b12 test: ensure group data cluster pointers are live
a5859edef4 fuzz: connman: set m_local_services/m_use_addrman_outgoing/m_max_automatic_connections
4b84c9125a fuzz: connman: add network activity invariants
9784818442 mining: add getTransactionsByWitnessID() IPC method
d282ae6883 mining: add getTransactionsByTxID() IPC method
0d5e4d4712 test: restart node after IPC option override test
f16b3613cd ipc: Serialize null CTransactionRef as empty Data
0f466e1094 mempool: add lookup by witness hash
51dd90fb50 refactor: Merge announce_cmpct_block() defs into one
97d08d62ba refactor: store wallet names to MigrationResult
8a739a5510 build: allow ipc fuzz builds
b2de59d486 wallet, bdbro: Validate btree page levels
dc3a2b9c3b wallet, bdbro: Enforce overflow data lengths

git-subtree-dir: libbitcoinkernel-sys/bitcoin
git-subtree-split: 81405fc7abbd1889f3978b8924e7acbe12b3403b

@sipa sipa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Postmergeous ACK dc1c17c

Comment thread src/coins.h

explicit InputToFetch(const COutPoint& o LIFETIMEBOUND) noexcept : outpoint{o} {}

//! Move ctor is required for resizing m_inputs in StartFetching. Elements will never move once parallel tasks

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This feels like a hack. Maybe it can be avoided by using std::unique_ptr<InputToFetch[]> m_inputs instead of std::vector<InputToFetch>?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

re: #35295 (comment)

This feels like a hack. Maybe it can be avoided by using std::unique_ptr<InputToFetch[]> m_inputs instead of std::vector<InputToFetch>?

Could still be a good idea, but this was discussed previously here: https://mirror.b10c.me/bitcoin-bitcoin/35295#discussion_r3307189323

Kino1994 pushed a commit to Kino1994/bitcoin-full-history that referenced this pull request Jul 10, 2026
…n parallel during ConnectBlock

aceceb0 doc: add release notes (Andrew Toth)
3238584 fuzz: add coins_view_stacked fuzz harness to test concurrent leveldb reads (Andrew Toth)
f11d406 fuzz: update harnesses to cover CoinsViewOverlay::StartFetching (Andrew Toth)
571236a test: add unit tests for CoinsViewOverlay::StartFetching (Andrew Toth)
0525ba0 doc: update CoinsViewOverlay docstring to describe parallel fetching (Andrew Toth)
4863fdb coins: fetch inputs in parallel (Andrew Toth)
e97ccc0 coins: add ready flag to InputToFetch (Andrew Toth)
797f658 validation: collect block inputs in CoinsViewOverlay before ConnectBlock (Andrew Toth)
e69b38e coins: introduce thread pool in CoinsViewOverlay (Andrew Toth)
edf82b6 validation: add -prevoutfetchthreads configuration option (Andrew Toth)

Pull request description:

  This PR is a continuation of bitcoin/bitcoin#31132. All outstanding issues raised there have been resolved, but the volume of stale comments can make that change difficult to review.

  Currently, when connecting a block, each input prevout is looked up one at a time. For every input we first check the in-memory coins cache, and on a miss we make a synchronous round-trip to the chainstate LevelDB to read the coin from disk. Because these lookups happen serially as the block is being validated, the disk read latency stacks up and dominates the time spent in `ConnectBlock` whenever many inputs are not already in the cache.

  This PR moves those disk reads onto a pool of worker threads that run in parallel with block connection. Before entering `ConnectBlock` the block is handed to a `CoinsViewOverlay`, which kicks off the workers to begin fetching all of the block's prevouts from disk and warming the cache. The main validation thread continues to do exactly the same work it does today, hitting the cache for each input in order. The only difference is that by the time it asks, the coin is much more likely to already be there. There are no validation logic or consensus behavior changes. This is purely a parallelization of an existing read pattern.

  The number of fetcher threads is configurable via `-prevoutfetchthreads=<n>`, defaulting to 8 and capped at 16. Setting it to 0 disables input fetching entirely and reverts to the previous serial behavior.

  We have measured large performance gains for IBD and `-reindex-chainstate`, as well as worst-case steady-state block connection at the tip. l0rinc ran many thorough benchmarking passes on the original PR across multiple machines, storage types, dbcache sizes[^1], operating systems[^2], and fetcher thread counts[^3]. Many other contributors also posted their benchmark results in the original PR. IBD speedups range from 1.18× to over 3× faster[^4]. Worst-case block connection time for network-attached storage was over 2× faster[^5]. Flamegraph comparisons before and after this change are available[^6].

  On safety: `ConnectBlock` runs while holding `cs_main`, so nothing else in the node can mutate the chainstate while the fetchers are reading it.

  On LevelDB: [concurrent reads are fully supported](https://github.com/bitcoin/bitcoin/blob/master/src/leveldb/include/leveldb/db.h#L44) and [documented as such](https://github.com/bitcoin/bitcoin/blob/master/src/leveldb/doc/index.md#concurrency). We already rely on this in production today against our other LevelDB-backed databases. The `txindex` DB is read by multiple simultaneous HTTP RPC worker threads via the `getrawtransaction` RPC. The `blockfilterindex` DB is called concurrently from both the P2P `cfilters` / `cfheaders` / `cfcheckpt` message handlers on the `msghand` thread, and from the `getblockfilter` RPC on the HTTP RPC worker threads. We have not yet been issuing concurrent reads against the chainstate DB, but there is no LevelDB-side reason we can't. In fact, the chainstate DB is already being touched by more than one thread on master, because LevelDB schedules its own background compaction work.

  For reviewers:

  The main change is `CoinsViewOverlay` gets 1 new public and 2 new private methods.

  - `StartFetching`: public method called in lieu of `CreateResetGuard` before we enter `ConnectBlock`. It still returns a `ResetGuard` so the view is `Reset` before the block it is working on leaves scope. This kicks off worker threads who each just run `while (ProcessInput()) {}` and then return.
  - `StopFetching`: private method called on `Reset` whenever the guard leaves scope or `Flush`. Stops all threads and clears multi threaded state.
  - `ProcessInput`: private method that fetches a single input prevout. Returns `true` if an input was fetched and `false` otherwise. This is the only method on `CoinsViewOverlay` that is called concurrently by multiple threads. Every other method on the overlay is still called synchronously on the main thread.

  The `CoinsViewOverlay::FetchCoinFromBase` method is also extended to lookup the coins fetched from `ProcessInput` first before falling back to `base->PeekCoin`.

  Mutating methods `Reset` and `Flush` are overridden in `CoinsViewOverlay` to call `StopFetching` first.

  [^1]: bitcoin/bitcoin#31132 (review)
  [^2]: bitcoin/bitcoin#31132 (comment)
  [^3]: bitcoin/bitcoin#31132 (comment)
  [^4]: bitcoin/bitcoin#31132 (comment)
  [^5]: bitcoin/bitcoin#31132 (comment)
  [^6]: bitcoin/bitcoin#31132 (comment)

ACKs for top commit:
  l0rinc:
    reACK aceceb0
  willcl-ark:
    ACK aceceb0
  theStack:
    re-ACK aceceb0
  ryanofsky:
    Code review ACK aceceb0 with changes to StopFetching and AllInputsConsumed checking behavior since last review.

Tree-SHA512: 89c1c2890f65aac5cd546edc44504956c47b6fada256d3b86ced47e6dd8c72f633a4357753b3b9805b9ba6ed02790822090d70578aba2964baf50d7eb956864c
fanquake added a commit that referenced this pull request Jul 14, 2026
240d5f7 fuzz: Drop unnecessary mutexes (marcofleon)

Pull request description:

  Quick cleanup addressing #35295 (comment).

  This follows the same logic as 48df093 from #35521.

ACKs for top commit:
  maflcko:
    lgtm ACK 240d5f7
  nervana21:
    ACK 240d5f7
  l0rinc:
    code review ACK 240d5f7

Tree-SHA512: 869127dc8cec4fc0688f92d67dc22f643cf3741c62d645eb4a959a9d8f46590efe19765f7df97ee36f9a3ca759c50fe983a3e6655e40a53ea99904e7a1ec00f6
achow101 added a commit that referenced this pull request Jul 14, 2026
72db4ac coins: drop stale cursor null checks (Lőrinc)
3d2f2d8 coins: pass UTXO stats view by reference (Lőrinc)
35aedb2 coins: drop cursor from base view (Lőrinc)
c6fbe2f coins: pass DB view to cursor users (Lőrinc)

Pull request description:

  **Problem:** `CCoinsView::Cursor()` makes cursor iteration look like a generic coins view operation, but cursor iteration is only supported by the DB-backed coins view.
  The cache override only threw, and the `coins_view` fuzz target only asserted that deterministic unsupported throw path.

  **Fix:** Make cursor iteration a `CCoinsViewDB` operation.
  Cursor users now take the DB-backed view directly, `CCoinsView` no longer exposes `Cursor()`, and the fuzz target keeps DB-backed cursor coverage while dropping the unsupported cache throw probe.
  The UTXO stats path is also tightened to pass the non-null DB view by reference, and stale null handling for DB cursors is removed.

  This was extracted from review discussion in #35295 (comment) and extended based on #35562 (comment).

ACKs for top commit:
  achow101:
    ACK 72db4ac
  sedited:
    Re-ACK 72db4ac
  w0xlt:
    ACK 72db4ac
  andrewtoth:
    ACK 72db4ac

Tree-SHA512: 12a81330a6ec1b91a7e4393f3761ea9ed4702ecb24312f1defa5a9a079a396ce921fc52f74fe296e5ac7ab20d5b5a8a84e858c96847f333c58b7fa9de9e8143e
Kino1994 pushed a commit to Kino1994/bitcoin-full-history that referenced this pull request Jul 19, 2026
a05186f fuzz: Drop unnecessary mutexes (marcofleon)

Pull request description:

  Quick cleanup addressing bitcoin/bitcoin#35295 (comment).

  This follows the same logic as bafc97f from bitcoin/bitcoin#35521.

ACKs for top commit:
  maflcko:
    lgtm ACK a05186f
  nervana21:
    ACK a05186f
  l0rinc:
    code review ACK a05186f

Tree-SHA512: 869127dc8cec4fc0688f92d67dc22f643cf3741c62d645eb4a959a9d8f46590efe19765f7df97ee36f9a3ca759c50fe983a3e6655e40a53ea99904e7a1ec00f6
Kino1994 pushed a commit to Kino1994/bitcoin-full-history that referenced this pull request Jul 19, 2026
9fdde8e coins: drop stale cursor null checks (Lőrinc)
c42bfb3 coins: pass UTXO stats view by reference (Lőrinc)
18dab78 coins: drop cursor from base view (Lőrinc)
fffcc01 coins: pass DB view to cursor users (Lőrinc)

Pull request description:

  **Problem:** `CCoinsView::Cursor()` makes cursor iteration look like a generic coins view operation, but cursor iteration is only supported by the DB-backed coins view.
  The cache override only threw, and the `coins_view` fuzz target only asserted that deterministic unsupported throw path.

  **Fix:** Make cursor iteration a `CCoinsViewDB` operation.
  Cursor users now take the DB-backed view directly, `CCoinsView` no longer exposes `Cursor()`, and the fuzz target keeps DB-backed cursor coverage while dropping the unsupported cache throw probe.
  The UTXO stats path is also tightened to pass the non-null DB view by reference, and stale null handling for DB cursors is removed.

  This was extracted from review discussion in bitcoin/bitcoin#35295 (comment) and extended based on bitcoin/bitcoin#35562 (comment).

ACKs for top commit:
  achow101:
    ACK 9fdde8e
  sedited:
    Re-ACK 9fdde8e
  w0xlt:
    ACK 9fdde8e
  andrewtoth:
    ACK 9fdde8e

Tree-SHA512: 12a81330a6ec1b91a7e4393f3761ea9ed4702ecb24312f1defa5a9a079a396ce921fc52f74fe296e5ac7ab20d5b5a8a84e858c96847f333c58b7fa9de9e8143e
Kino1994 pushed a commit to Kino1994/bitcoin-full-history that referenced this pull request Aug 19, 2026
…n parallel during ConnectBlock

dc1c17c0856e3455a0d62f9ffd807c0d14feff62 doc: add release notes (Andrew Toth)
0e10937184438f8d81940336b183267e59f959b7 fuzz: add coins_view_stacked fuzz harness to test concurrent leveldb reads (Andrew Toth)
ce610a6ff445bb8a812e650c91f501a1ecf0b19c fuzz: update harnesses to cover CoinsViewOverlay::StartFetching (Andrew Toth)
760fb22dc370b0882bd345ff913f9337a9b6e4c1 test: add unit tests for CoinsViewOverlay::StartFetching (Andrew Toth)
d69a3b20deca56ff8f925d93471d4caeacaa4d21 doc: update CoinsViewOverlay docstring to describe parallel fetching (Andrew Toth)
ab2a3792372c6b99b9d6749a1841dbb363264573 coins: fetch inputs in parallel (Andrew Toth)
fdf283036a1e16f546f96ca9c2d6d33f3a4fea56 coins: add ready flag to InputToFetch (Andrew Toth)
ede11b83141d0d0998cd95ebabf8d1656c6f7765 validation: collect block inputs in CoinsViewOverlay before ConnectBlock (Andrew Toth)
f82043af507a2f2caacdae1af6bcacddc8c4876b coins: introduce thread pool in CoinsViewOverlay (Andrew Toth)
5bf1c32008173db2080286b2690f4951299d1619 validation: add -prevoutfetchthreads configuration option (Andrew Toth)

Pull request description:

  This PR is a continuation of bitcoin/bitcoin#31132. All outstanding issues raised there have been resolved, but the volume of stale comments can make that change difficult to review.

  Currently, when connecting a block, each input prevout is looked up one at a time. For every input we first check the in-memory coins cache, and on a miss we make a synchronous round-trip to the chainstate LevelDB to read the coin from disk. Because these lookups happen serially as the block is being validated, the disk read latency stacks up and dominates the time spent in `ConnectBlock` whenever many inputs are not already in the cache.

  This PR moves those disk reads onto a pool of worker threads that run in parallel with block connection. Before entering `ConnectBlock` the block is handed to a `CoinsViewOverlay`, which kicks off the workers to begin fetching all of the block's prevouts from disk and warming the cache. The main validation thread continues to do exactly the same work it does today, hitting the cache for each input in order. The only difference is that by the time it asks, the coin is much more likely to already be there. There are no validation logic or consensus behavior changes. This is purely a parallelization of an existing read pattern.

  The number of fetcher threads is configurable via `-prevoutfetchthreads=<n>`, defaulting to 8 and capped at 16. Setting it to 0 disables input fetching entirely and reverts to the previous serial behavior.

  We have measured large performance gains for IBD and `-reindex-chainstate`, as well as worst-case steady-state block connection at the tip. l0rinc ran many thorough benchmarking passes on the original PR across multiple machines, storage types, dbcache sizes[^1], operating systems[^2], and fetcher thread counts[^3]. Many other contributors also posted their benchmark results in the original PR. IBD speedups range from 1.18× to over 3× faster[^4]. Worst-case block connection time for network-attached storage was over 2× faster[^5]. Flamegraph comparisons before and after this change are available[^6].

  On safety: `ConnectBlock` runs while holding `cs_main`, so nothing else in the node can mutate the chainstate while the fetchers are reading it.

  On LevelDB: [concurrent reads are fully supported](https://github.com/bitcoin/bitcoin/blob/master/src/leveldb/include/leveldb/db.h#L44) and [documented as such](https://github.com/bitcoin/bitcoin/blob/master/src/leveldb/doc/index.md#concurrency). We already rely on this in production today against our other LevelDB-backed databases. The `txindex` DB is read by multiple simultaneous HTTP RPC worker threads via the `getrawtransaction` RPC. The `blockfilterindex` DB is called concurrently from both the P2P `cfilters` / `cfheaders` / `cfcheckpt` message handlers on the `msghand` thread, and from the `getblockfilter` RPC on the HTTP RPC worker threads. We have not yet been issuing concurrent reads against the chainstate DB, but there is no LevelDB-side reason we can't. In fact, the chainstate DB is already being touched by more than one thread on master, because LevelDB schedules its own background compaction work.

  For reviewers:

  The main change is `CoinsViewOverlay` gets 1 new public and 2 new private methods.

  - `StartFetching`: public method called in lieu of `CreateResetGuard` before we enter `ConnectBlock`. It still returns a `ResetGuard` so the view is `Reset` before the block it is working on leaves scope. This kicks off worker threads who each just run `while (ProcessInput()) {}` and then return.
  - `StopFetching`: private method called on `Reset` whenever the guard leaves scope or `Flush`. Stops all threads and clears multi threaded state.
  - `ProcessInput`: private method that fetches a single input prevout. Returns `true` if an input was fetched and `false` otherwise. This is the only method on `CoinsViewOverlay` that is called concurrently by multiple threads. Every other method on the overlay is still called synchronously on the main thread.

  The `CoinsViewOverlay::FetchCoinFromBase` method is also extended to lookup the coins fetched from `ProcessInput` first before falling back to `base->PeekCoin`.

  Mutating methods `Reset` and `Flush` are overridden in `CoinsViewOverlay` to call `StopFetching` first.

  [^1]: bitcoin/bitcoin#31132 (review)
  [^2]: bitcoin/bitcoin#31132 (comment)
  [^3]: bitcoin/bitcoin#31132 (comment)
  [^4]: bitcoin/bitcoin#31132 (comment)
  [^5]: bitcoin/bitcoin#31132 (comment)
  [^6]: bitcoin/bitcoin#31132 (comment)

ACKs for top commit:
  l0rinc:
    reACK dc1c17c0856e3455a0d62f9ffd807c0d14feff62
  willcl-ark:
    ACK dc1c17c0856e3455a0d62f9ffd807c0d14feff62
  theStack:
    re-ACK dc1c17c0856e3455a0d62f9ffd807c0d14feff62
  ryanofsky:
    Code review ACK dc1c17c0856e3455a0d62f9ffd807c0d14feff62 with changes to StopFetching and AllInputsConsumed checking behavior since last review.

Tree-SHA512: 89c1c2890f65aac5cd546edc44504956c47b6fada256d3b86ced47e6dd8c72f633a4357753b3b9805b9ba6ed02790822090d70578aba2964baf50d7eb956864c
Kino1994 pushed a commit to Kino1994/bitcoin-full-history that referenced this pull request Aug 19, 2026
240d5f743aab0ff4f3e5d7d1783b410aa3306ad3 fuzz: Drop unnecessary mutexes (marcofleon)

Pull request description:

  Quick cleanup addressing bitcoin/bitcoin#35295 (comment).

  This follows the same logic as 48df0939e7250a2de8a0c336bc3ddbcbe0578812 from bitcoin/bitcoin#35521.

ACKs for top commit:
  maflcko:
    lgtm ACK 240d5f743aab0ff4f3e5d7d1783b410aa3306ad3
  nervana21:
    ACK 240d5f743aab0ff4f3e5d7d1783b410aa3306ad3
  l0rinc:
    code review ACK 240d5f743aab0ff4f3e5d7d1783b410aa3306ad3

Tree-SHA512: 869127dc8cec4fc0688f92d67dc22f643cf3741c62d645eb4a959a9d8f46590efe19765f7df97ee36f9a3ca759c50fe983a3e6655e40a53ea99904e7a1ec00f6
Kino1994 pushed a commit to Kino1994/bitcoin-full-history that referenced this pull request Aug 19, 2026
72db4accbf5bae74d061db1aeee9e0688c0da2f5 coins: drop stale cursor null checks (Lőrinc)
3d2f2d8de09d162863f7b8e7e48e347d7d87c648 coins: pass UTXO stats view by reference (Lőrinc)
35aedb2823692756dbe958b08f415c2b3e0be4ea coins: drop cursor from base view (Lőrinc)
c6fbe2f66cff3846068795b3e2c459242b7be56b coins: pass DB view to cursor users (Lőrinc)

Pull request description:

  **Problem:** `CCoinsView::Cursor()` makes cursor iteration look like a generic coins view operation, but cursor iteration is only supported by the DB-backed coins view.
  The cache override only threw, and the `coins_view` fuzz target only asserted that deterministic unsupported throw path.

  **Fix:** Make cursor iteration a `CCoinsViewDB` operation.
  Cursor users now take the DB-backed view directly, `CCoinsView` no longer exposes `Cursor()`, and the fuzz target keeps DB-backed cursor coverage while dropping the unsupported cache throw probe.
  The UTXO stats path is also tightened to pass the non-null DB view by reference, and stale null handling for DB cursors is removed.

  This was extracted from review discussion in bitcoin/bitcoin#35295 (comment) and extended based on bitcoin/bitcoin#35562 (comment).

ACKs for top commit:
  achow101:
    ACK 72db4accbf5bae74d061db1aeee9e0688c0da2f5
  sedited:
    Re-ACK 72db4accbf5bae74d061db1aeee9e0688c0da2f5
  w0xlt:
    ACK 72db4accbf5bae74d061db1aeee9e0688c0da2f5
  andrewtoth:
    ACK 72db4accbf5bae74d061db1aeee9e0688c0da2f5

Tree-SHA512: 12a81330a6ec1b91a7e4393f3761ea9ed4702ecb24312f1defa5a9a079a396ce921fc52f74fe296e5ac7ab20d5b5a8a84e858c96847f333c58b7fa9de9e8143e
sedited added a commit that referenced this pull request Sep 5, 2026
8e4b7ab fuzz: use per-level fetch scopes in coinscache_sim (Andrew Toth)
5292386 doc: improve CoinsViewOverlay documentation (Andrew Toth)
d552c52 coins: log error reason when prevout fetch submission fails (Andrew Toth)
2ffaa6e coins: delete Sync and SetBackend on CoinsViewOverlay (Andrew Toth)
3300229 coins: filter coinbase txid from parallel input fetching (Andrew Toth)

Pull request description:

  This addresses various follow-ups requested in #35295.

  - add the coinbase txid to the filter so inputs spending the coinbase are not fetched.
  - delete Sync and SetBackend from CoinsViewOverlay
  - various logging and documentation improvements
  - improve coinscache_sim fuzzing so we continue parallel fetching while more caches are added on to the cache stack

ACKs for top commit:
  optout21:
    reACK 8e4b7ab
  l0rinc:
    ACK 8e4b7ab
  sedited:
    ACK 8e4b7ab

Tree-SHA512: 38001f96be6f893e2610bb81f379ecc0c40ffd39da5bfe1f5db47db1ef2f725d80ae3f9b5e25acd64e65013176ba3ba4e3e8585cb55420b2793845c292beda23
Kino1994 pushed a commit to Kino1994/bitcoin-full-history that referenced this pull request Sep 6, 2026
…ollowups

8e4b7ab7258aa8497ef90847e495e81d984b99d4 fuzz: use per-level fetch scopes in coinscache_sim (Andrew Toth)
5292386b785a0a133368b5429a2363cf53e29e00 doc: improve CoinsViewOverlay documentation (Andrew Toth)
d552c52b081c4c0853086bcdce38d67fd02f2c67 coins: log error reason when prevout fetch submission fails (Andrew Toth)
2ffaa6e6a7db239306309a859b7e8aed478a810d coins: delete Sync and SetBackend on CoinsViewOverlay (Andrew Toth)
330022993fb96b3b776e562f1de6696d381e6524 coins: filter coinbase txid from parallel input fetching (Andrew Toth)

Pull request description:

  This addresses various follow-ups requested in bitcoin/bitcoin#35295.

  - add the coinbase txid to the filter so inputs spending the coinbase are not fetched.
  - delete Sync and SetBackend from CoinsViewOverlay
  - various logging and documentation improvements
  - improve coinscache_sim fuzzing so we continue parallel fetching while more caches are added on to the cache stack

ACKs for top commit:
  optout21:
    reACK 8e4b7ab7258aa8497ef90847e495e81d984b99d4
  l0rinc:
    ACK 8e4b7ab7258aa8497ef90847e495e81d984b99d4
  sedited:
    ACK 8e4b7ab7258aa8497ef90847e495e81d984b99d4

Tree-SHA512: 38001f96be6f893e2610bb81f379ecc0c40ffd39da5bfe1f5db47db1ef2f725d80ae3f9b5e25acd64e65013176ba3ba4e3e8585cb55420b2793845c292beda23
sedited added a commit that referenced this pull request Nov 4, 2026
… test fixtures

1c62336 test: avoid snapshot insertion in coin fixtures (Lőrinc)

Pull request description:

  **Problem:** Several coin-cache fixtures use `EmplaceCoinInternalDANGER` just to set up their coins, even though it is reserved for snapshot loading.

  **Fix:** Use `AddCoin` and `SpendCoin` for fixture setup, keeping the entries dirty but not fresh, as before. Keep the [simulation](#33512), [fuzz and duplicate-insertion coverage](#32313) that intentionally tests the bypass.

  This is a small extraction from #36598 that can be reviewed and merged independently of the broader AssumeUTXO removal demo. The overlay fixture change also follows the earlier [suggestion in #35295](#35295 (comment)).

ACKs for top commit:
  Hamza1610:
    Tested ACK 1c62336
  sedited:
    ACK 1c62336

Tree-SHA512: c67cee9efaa7cf56a76ee51bb1274033e6f618e14c15c2f0f3e7625b6e401417c71e9bb956cbff2e9c937453b106a5e469ad8bc391343d86838d39d9f99a89df
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.