WIP: validation: use parallel input prevout fetching in TestBlockValidity #35751

Draft
andrewtoth wants to merge 2 commits from testblockvalidity-startfetching into master AGit
andrewtoth commented 2026-07-19 23:30:37 +00:00 (Migrated from github.com)

Use CoinsViewOverlay to speed up ConnectBlock in TestBlockValidity. This also has the benefit of not inserting entries fetched from db into the main cache.

cs_main must be held for each place where the overlay is being used, and the reset guard ensures it will be reset for the next caller.

Use CoinsViewOverlay to speed up ConnectBlock in TestBlockValidity. This also has the benefit of not inserting entries fetched from db into the main cache. cs_main must be held for each place where the overlay is being used, and the reset guard ensures it will be reset for the next caller.
DrahtBot commented 2026-07-19 23:30:45 +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
Concept ACK Sjors
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:

  • #36066 (validation: Separate check-only version of ConnectBlock by optout21)

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/35751 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/35751.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/35751#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 | | ---- | --------- | | Concept ACK | [Sjors](https://github.com/bitcoin/bitcoin/pull/35751#issuecomment-5061422051) | | Stale ACK | [sedited](https://github.com/bitcoin/bitcoin/pull/35751#pullrequestreview-4753791958) | 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: * [#36066](https://github.com/bitcoin/bitcoin/pull/36066) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36066.svg"></sub> (validation: Separate check-only version of ConnectBlock by optout21) 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-->
sedited (Migrated from github.com) approved these changes 2026-07-22 11:18:43 +00:00
sedited (Migrated from github.com) left a comment

ACK 985d248383b43205f98a6971eb887ffa239adf85

ACK 985d248383b43205f98a6971eb887ffa239adf85
l0rinc commented 2026-07-22 21:17:24 +00:00 (Migrated from github.com)

For the record: This is a follow up to https://github.com/bitcoin/bitcoin/pull/31132#discussion_r2645502461 and https://github.com/bitcoin/bitcoin/pull/34164#discussion_r2657511963.


https://corecheck.dev/bitcoin/bitcoin/pulls/35751 claimed AssembleBlock slowed down considerably but I can't reproduce it locally (though I can confirm it's called from the benchmark).

Details
> Before:

|               ns/op |                op/s |    err% |     total | benchmark
|--------------------:|--------------------:|--------:|----------:|:----------
|           82,662.62 |           12,097.37 |    0.3% |      1.07 | `AssembleBlock`

> After

|               ns/op |                op/s |    err% |     total | benchmark
|--------------------:|--------------------:|--------:|----------:|:----------
|           82,993.67 |           12,049.11 |    0.4% |      1.08 | `AssembleBlock`

Could you provide a reproducible way to test the performance claim, ideally using a deterministic set of mainnet block proposals or a microbenchmark?
And since this change targets block-template validation, maybe we should ping @Sjors to get input from reviewers familiar with mining workloads.

For the record: This is a follow up to https://github.com/bitcoin/bitcoin/pull/31132#discussion_r2645502461 and https://github.com/bitcoin/bitcoin/pull/34164#discussion_r2657511963. ---- https://corecheck.dev/bitcoin/bitcoin/pulls/35751 claimed `AssembleBlock` slowed down considerably but I can't reproduce it locally (though I can confirm it's called from the benchmark). <details><summary>Details</summary> ``` > Before: | ns/op | op/s | err% | total | benchmark |--------------------:|--------------------:|--------:|----------:|:---------- | 82,662.62 | 12,097.37 | 0.3% | 1.07 | `AssembleBlock` > After | ns/op | op/s | err% | total | benchmark |--------------------:|--------------------:|--------:|----------:|:---------- | 82,993.67 | 12,049.11 | 0.4% | 1.08 | `AssembleBlock` ``` </details> Could you provide a reproducible way to test the performance claim, ideally using a deterministic set of mainnet block proposals or a microbenchmark? And since this change targets block-template validation, maybe we should ping @Sjors to get input from reviewers familiar with mining workloads.
andrewtoth commented 2026-07-23 02:43:39 +00:00 (Migrated from github.com)

https://corecheck.dev/bitcoin/bitcoin/pulls/35751 claimed AssembleBlock slowed down considerably

@l0rinc is that the correct benchmark data you meant to post in the details? It doesn't seem to show the a slowdown...

Could you provide a reproducible way to test the performance claim, ideally using a deterministic set of mainnet block proposals or a microbenchmark?

There have been many benchmarks performed already by you in #31132 for this change. Is this not obvious to you it will increase performance?

> https://corecheck.dev/bitcoin/bitcoin/pulls/35751 claimed AssembleBlock slowed down considerably @l0rinc is that the correct benchmark data you meant to post in the details? It doesn't seem to show the a slowdown... > Could you provide a reproducible way to test the performance claim, ideally using a deterministic set of mainnet block proposals or a microbenchmark? There have been many benchmarks performed already by you in #31132 for this change. Is this not obvious to you it will increase performance?
sedited commented 2026-07-23 12:13:06 +00:00 (Migrated from github.com)

@l0rinc is that the correct benchmark data you meant to post in the details? It doesn't seem to show the a slowdown...

I see it in the report too, and can measure the slowdown locally as well.

> @l0rinc is that the correct benchmark data you meant to post in the details? It doesn't seem to show the a slowdown... I see it in the report too, and can measure the slowdown locally as well.
sedited commented 2026-07-23 12:23:57 +00:00 (Migrated from github.com)

If I fill up the block properly in the AssembleBlock benchmark, this does indeed then speed up connection. Seems like we should be doing that anyway to make the benchmark realistic?

I'm guessing there is a cutover where the synchronization overhead outweighs getting the coins from cache (or maybe even from disk?). Maybe it would be worthwhile to introduce a heuristic where we skip background fetching if the block does not spend a lot of coins?

If I fill up the block properly in the `AssembleBlock` benchmark, this does indeed then speed up connection. Seems like we should be doing that anyway to make the benchmark realistic? I'm guessing there is a cutover where the synchronization overhead outweighs getting the coins from cache (or maybe even from disk?). Maybe it would be worthwhile to introduce a heuristic where we skip background fetching if the block does not spend a lot of coins?
Sjors commented 2026-07-23 17:30:19 +00:00 (Migrated from github.com)

Concept ACK on (indirectly) making the checkBlock() IPC faster. This is intended to be called frequently by the Job Declarator Server role in Stratum v2.

Although #35671 introduces a different approach for that, its makeTemplate() method also goes through TextBlockValidity. I wonder if TxCollection could be made even faster if pre-loads coins it needs, before a client calls makeTemplate()to check the full block. Update: see https://github.com/Sjors/bitcoin/pull/122

I haven't studied the earlier work, so for that reason alone a quick benchmark might be nice to demonstrate to others too.

Concept ACK on (indirectly) making the `checkBlock()` IPC faster. This is intended to be called frequently by the Job Declarator Server role in Stratum v2. Although #35671 introduces a different approach for that, its `makeTemplate()` method also goes through `TextBlockValidity`. I wonder if `TxCollection` could be made even faster if pre-loads coins it needs, _before_ a client calls `makeTemplate()`to check the full block. _Update: see https://github.com/Sjors/bitcoin/pull/122_ I haven't studied the earlier work, so for that reason alone a quick benchmark might be nice to demonstrate to others too.
DrahtBot commented 2026-07-29 03:02:34 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/30417973130/job/90468502585
LLM reason (✨ experimental): CI failed because IWYU reported a missing/incorrect #include in src/bench/block_assemble.cpp (triggering the “Failure generated from IWYU” step).

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 `iwyu`: https://github.com/bitcoin/bitcoin/actions/runs/30417973130/job/90468502585</sub> <sub>LLM reason (✨ experimental): CI failed because IWYU reported a missing/incorrect `#include` in `src/bench/block_assemble.cpp` (triggering the “Failure generated from IWYU” step).</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>
andrewtoth commented 2026-07-29 13:40:28 +00:00 (Migrated from github.com)

Yes, I see the regression in the in corecheck as well. I first read @l0rinc's comment as containing the regression. My apologies.

@Sjors I've included an additional commit at the start that improves the AssembleBlock benchmark by filling the block to max weight with transactions. The new benchmark shows a 10% speedup on my local machine when comparing the first and second commits.

Before this change
ns/op op/s err% ins/op cyc/op IPC bra/op miss% total benchmark
16,370,829.20 61.08 0.5% 169,414,150.61 36,723,542.62 4.613 21,344,193.75 0.2% 5.71 AssembleBlock
16,157,284.00 61.89 2.9% 169,412,308.63 36,308,394.28 4.666 21,345,426.37 0.2% 5.61 AssembleBlock
16,328,205.58 61.24 1.6% 169,374,584.69 36,629,119.06 4.624 21,343,993.70 0.2% 5.57 AssembleBlock
After this change
ns/op op/s err% ins/op cyc/op IPC bra/op miss% total benchmark
14,860,137.50 67.29 1.8% 160,474,005.09 35,797,692.66 4.483 21,636,973.66 0.2% 5.42 AssembleBlock
14,322,912.28 69.82 1.1% 160,432,472.41 34,525,565.16 4.647 21,656,523.97 0.2% 5.41 AssembleBlock
14,767,059.78 67.72 0.7% 160,474,240.27 35,583,122.53 4.510 21,644,652.59 0.2% 5.49 AssembleBlock

I'm guessing there is a cutover where the synchronization overhead outweighs getting the coins from cache (or maybe even from disk?). Maybe it would be worthwhile to introduce a heuristic where we skip background fetching if the block does not spend a lot of coins?

@sedited There is likely a cutover, but it would be dependent on the system as well as other factors like how many coins are in the cache vs have to be fetched from db.
re: a heuristic - what we really care about is that slow blocks are faster. A block spending few coins is already very fast, and so speeding it up from 2ms -> 1ms will not really benefit anything in the grand scheme IMO.

Yes, I see the regression in the in corecheck as well. I first read @l0rinc's comment as containing the regression. My apologies. @Sjors I've included an additional commit at the start that improves the `AssembleBlock` benchmark by filling the block to max weight with transactions. The new benchmark shows a 10% speedup on my local machine when comparing the first and second commits. <details><summary>Before this change</summary> | ns/op | op/s | err% | ins/op | cyc/op | IPC | bra/op | miss% | total | benchmark |--------------------:|--------------------:|--------:|----------------:|----------------:|-------:|---------------:|--------:|----------:|:---------- | 16,370,829.20 | 61.08 | 0.5% | 169,414,150.61 | 36,723,542.62 | 4.613 | 21,344,193.75 | 0.2% | 5.71 | `AssembleBlock` | 16,157,284.00 | 61.89 | 2.9% | 169,412,308.63 | 36,308,394.28 | 4.666 | 21,345,426.37 | 0.2% | 5.61 | `AssembleBlock` | 16,328,205.58 | 61.24 | 1.6% | 169,374,584.69 | 36,629,119.06 | 4.624 | 21,343,993.70 | 0.2% | 5.57 | `AssembleBlock` </details> <details><summary>After this change</summary> | ns/op | op/s | err% | ins/op | cyc/op | IPC | bra/op | miss% | total | benchmark |--------------------:|--------------------:|--------:|----------------:|----------------:|-------:|---------------:|--------:|----------:|:---------- | 14,860,137.50 | 67.29 | 1.8% | 160,474,005.09 | 35,797,692.66 | 4.483 | 21,636,973.66 | 0.2% | 5.42 | `AssembleBlock` | 14,322,912.28 | 69.82 | 1.1% | 160,432,472.41 | 34,525,565.16 | 4.647 | 21,656,523.97 | 0.2% | 5.41 | `AssembleBlock` | 14,767,059.78 | 67.72 | 0.7% | 160,474,240.27 | 35,583,122.53 | 4.510 | 21,644,652.59 | 0.2% | 5.49 | `AssembleBlock` </details> > I'm guessing there is a cutover where the synchronization overhead outweighs getting the coins from cache (or maybe even from disk?). Maybe it would be worthwhile to introduce a heuristic where we skip background fetching if the block does not spend a lot of coins? @sedited There is likely a cutover, but it would be dependent on the system as well as other factors like how many coins are in the cache vs have to be fetched from db. re: a heuristic - what we really care about is that slow blocks are faster. A block spending few coins is already very fast, and so speeding it up from 2ms -> 1ms will not really benefit anything in the grand scheme IMO.
optout21 (Migrated from github.com) reviewed 2026-08-07 07:27:49 +00:00
optout21 (Migrated from github.com) left a comment

Another performance improvement, a must-have follow-up of #35295/#34164/#31132, looks good.

Two comments:

I am confused by the description of the 2nd (last) commit. It states:

  • "Use CoinsViewOverlay to speed up ConnectBlock in TestBlockValidity." -- CoinsViewOverlay was used before; the change seems not about using it, but using an existing shared instance, instead of always a new one.

  • "This also has the benefit of not populating entries in the main cache." -- that was true also without the change.

There is also another usage of m_connect_block_view, at line 3055:

3055    CoinsViewOverlay& view{*m_coins_views->m_connect_block_view};
3056    const auto reset_guard{view.StartFetching(*block_to_connect)};

(github.com/andrewtoth/bitcoin@ff4dd421f9/src/validation.cpp (L3055-L3056))

Could this also use the newly introduced ConnectBlockView()?

Another performance improvement, a must-have follow-up of #35295/#34164/#31132, looks good. Two comments: I am confused by the description of the 2nd (last) commit. It states: - "Use CoinsViewOverlay to speed up ConnectBlock in TestBlockValidity." -- CoinsViewOverlay was used before; the change seems not about using it, but using an existing shared instance, instead of always a new one. - "This also has the benefit of not populating entries in the main cache." -- that was true also without the change. There is also another usage of `m_connect_block_view`, at line 3055: ``` 3055 CoinsViewOverlay& view{*m_coins_views->m_connect_block_view}; 3056 const auto reset_guard{view.StartFetching(*block_to_connect)}; ``` (https://github.com/andrewtoth/bitcoin/blob/ff4dd421f9020e85711c6e4069e62abf31fc3c0f/src/validation.cpp#L3055-L3056) Could this also use the newly introduced `ConnectBlockView()`?
optout21 (Migrated from github.com) commented 2026-08-07 07:21:24 +00:00

ff4dd42 validation: use parallel input prevout fetching in TestBlockValidity:

A note on "dummy" naming: before the change, view_dummy was a local-only instance, so the "dummy" naming makes sense. However, now it's a reference to a longer-living instance, so I find "dummy" misleading. I suggest renaming it to view_shared. (There are not many usages to change).

> [ff4dd42](https://github.com/bitcoin/bitcoin/pull/35751/changes/ff4dd421f9020e85711c6e4069e62abf31fc3c0f) _validation: use parallel input prevout fetching in TestBlockValidity_: A note on "dummy" naming: before the change, `view_dummy` was a local-only instance, so the "dummy" naming makes sense. However, now it's a reference to a longer-living instance, so I find "dummy" misleading. I suggest renaming it to `view_shared`. (There are not many usages to change).
andrewtoth (Migrated from github.com) reviewed 2026-08-08 17:22:17 +00:00
andrewtoth (Migrated from github.com) commented 2026-08-08 17:22:17 +00:00

I renamed it to overlay_view.

I renamed it to overlay_view.
andrewtoth commented 2026-08-08 17:26:01 +00:00 (Migrated from github.com)

Thanks for your review @optout21.

"Use CoinsViewOverlay to speed up ConnectBlock in TestBlockValidity." -- CoinsViewOverlay was used before; the change seems not about using it, but using an existing shared instance, instead of always a new one.

"This also has the benefit of not populating entries in the main cache." -- that was true also without the change.

It was using a CCoinsViewCache before as an ephemeral cache on top of the main cache. This patch changes it to use the CoinsViewOverlay. The previous version would insert cache misses into the cache before returning to the view_dummy cache, while CoinsViewOverlay does not do that. I updated the commit message and PR description to try and clarify that.

Could this also use the newly introduced ConnectBlockView()?

Done.

Thanks for your review @optout21. > "Use CoinsViewOverlay to speed up ConnectBlock in TestBlockValidity." -- CoinsViewOverlay was used before; the change seems not about using it, but using an existing shared instance, instead of always a new one. > > "This also has the benefit of not populating entries in the main cache." -- that was true also without the change. It was using a `CCoinsViewCache` before as an ephemeral cache on top of the main cache. This patch changes it to use the `CoinsViewOverlay`. The previous version would insert cache misses into the cache before returning to the `view_dummy` cache, while `CoinsViewOverlay` does not do that. I updated the commit message and PR description to try and clarify that. > Could this also use the newly introduced ConnectBlockView()? Done.
l0rinc (Migrated from github.com) requested changes 2026-08-16 05:33:47 +00:00
l0rinc (Migrated from github.com) left a comment

I think the reentrancy issue needs to be addressed before this can be merged.
I also left a few comments on making the benchmark match its stated workload, plus some nits (feel free to just resolve those, but since we need to push anyway, we might as well clean this up a bit).

I think the reentrancy issue needs to be addressed before this can be merged. I also left a few comments on making the benchmark match its stated workload, plus some nits (feel free to just resolve those, but since we need to push anyway, we might as well clean this up a bit).
l0rinc (Migrated from github.com) commented 2026-08-16 05:11:16 +00:00

8ebb32e bench: fill assembled block to max weight in AssembleBlock:

nit: and if we're modifying this we might as well add braces and format it

> [8ebb32e](https://github.com/bitcoin/bitcoin/pull/35751/changes/8ebb32e69f8a4959e4d73481c64d7c1282fc9e33) _bench: fill assembled block to max weight in AssembleBlock_: nit: and if we're modifying this we might as well add braces and format it
l0rinc (Migrated from github.com) commented 2026-08-12 04:11:11 +00:00

nit: we could std::move a few of these (please check the other cases as well):

            txs.at(b) = MakeTransactionRef(std::move(tx));
nit: we could `std::move` a few of these (please check the other cases as well): ```suggestion txs.at(b) = MakeTransactionRef(std::move(tx)); ```
l0rinc (Migrated from github.com) commented 2026-08-12 04:11:58 +00:00

nit: I don't usually mind this iteration, but above we're using standard loop which makes the two iterations assymetric

nit: I don't usually mind this iteration, but above we're using standard loop which makes the two iterations assymetric
l0rinc (Migrated from github.com) commented 2026-08-16 05:13:52 +00:00

8ebb32e bench: fill assembled block to max weight in AssembleBlock:

we don't need to copy the existing style:

                const auto res{test_setup->m_node.chainman->ProcessTransaction(MakeTransactionRef(tx))};
> [8ebb32e](https://github.com/bitcoin/bitcoin/pull/35751/changes/8ebb32e69f8a4959e4d73481c64d7c1282fc9e33) _bench: fill assembled block to max weight in AssembleBlock_: we don't need to copy the existing style: ```suggestion const auto res{test_setup->m_node.chainman->ProcessTransaction(MakeTransactionRef(tx))}; ```
l0rinc (Migrated from github.com) commented 2026-08-16 05:00:43 +00:00

The commit message claims we fill assembled block to max weight, but we still have leftover transactions - can we assert the claim (and adjust the FAN_OUT to make it true? Just make sure the number is not 110, we're still sensitive to that...)

    assert(GetBlockWeight(*PrepareBlock(test_setup->m_node, options)) > MAX_BLOCK_WEIGHT - DEFAULT_BLOCK_RESERVED_WEIGHT);
}

Edit: We could also assert that mining the fan-out transactions empties the mempool, to verify that the inputs are confirmed.

The commit message claims we `fill assembled block to max weight`, but we still have leftover transactions - can we assert the claim (and adjust the `FAN_OUT` to make it true? Just make sure the number is not `110`, we're still sensitive to that...) ```suggestion assert(GetBlockWeight(*PrepareBlock(test_setup->m_node, options)) > MAX_BLOCK_WEIGHT - DEFAULT_BLOCK_RESERVED_WEIGHT); } ``` > Edit: We could also assert that mining the fan-out transactions empties the mempool, to verify that the inputs are confirmed.
l0rinc (Migrated from github.com) commented 2026-08-16 05:15:58 +00:00

2ba5628 validation: use parallel input prevout fetching in TestBlockValidity:

TestBlockValidity() previously used a local cache. This PR changes it to reuse ConnectBlockView(), which a synchronous BlockChecked callback can reach while ConnectTip() still has a fetch active.

Could we first record that both paths now select the same overlay?

BOOST_AUTO_TEST_CASE(testblockvalidity_with_active_connect_view)
{
    auto tip_hash{WITH_LOCK(cs_main, return Assert(m_node.chainman)->ActiveTip()->GetBlockHash())};
    auto outer_block{BadBlock(tip_hash)};
    auto candidate_block{GoodBlock(tip_hash)};
    LOCK(cs_main);
    auto& chainstate{Assert(m_node.chainman)->ActiveChainstate()};
    auto reset_guard{chainstate.ConnectBlockView().StartFetching(*outer_block)};
    BOOST_CHECK(&chainstate.TestBlockValidityView() != &chainstate.ConnectBlockView());
    BOOST_CHECK(TestBlockValidity(chainstate, *candidate_block, /*check_pow=*/false, /*check_merkle_root=*/false).IsValid());
}
> [2ba5628](https://github.com/bitcoin/bitcoin/pull/35751/changes/2ba5628cb90ea2ae960d3823742412741704e4ca) _validation: use parallel input prevout fetching in TestBlockValidity_: `TestBlockValidity()` previously used a local cache. This PR changes it to reuse `ConnectBlockView()`, which a synchronous `BlockChecked` callback can reach while `ConnectTip()` still has a fetch active. Could we first record that both paths now select the same overlay? ```C++ BOOST_AUTO_TEST_CASE(testblockvalidity_with_active_connect_view) { auto tip_hash{WITH_LOCK(cs_main, return Assert(m_node.chainman)->ActiveTip()->GetBlockHash())}; auto outer_block{BadBlock(tip_hash)}; auto candidate_block{GoodBlock(tip_hash)}; LOCK(cs_main); auto& chainstate{Assert(m_node.chainman)->ActiveChainstate()}; auto reset_guard{chainstate.ConnectBlockView().StartFetching(*outer_block)}; BOOST_CHECK(&chainstate.TestBlockValidityView() != &chainstate.ConnectBlockView()); BOOST_CHECK(TestBlockValidity(chainstate, *candidate_block, /*check_pow=*/false, /*check_merkle_root=*/false).IsValid()); } ```
andrewtoth (Migrated from github.com) reviewed 2026-08-23 21:42:50 +00:00
andrewtoth (Migrated from github.com) commented 2026-08-23 21:42:50 +00:00

I think the reentrancy issue needs to be addressed before this can be merged.

I don't think there is a reentrancy issue? I see though that BlockChecked callbacks in ConnectTip are synchronous, so a future change could theoretically call TestBlockValidity from the callback on the same thread. Nothing does that today. We can prevent this by calling Assert(overlay_view.GetCacheSize() == 0); inside TestBlockValidity. I'm not sure I see the value of this unit test.

> I think the reentrancy issue needs to be addressed before this can be merged. I don't think there is a reentrancy issue? I see though that `BlockChecked` callbacks in `ConnectTip` are synchronous, so a future change could theoretically call `TestBlockValidity` from the callback on the same thread. Nothing does that today. We can prevent this by calling `Assert(overlay_view.GetCacheSize() == 0);` inside `TestBlockValidity`. I'm not sure I see the value of this unit test.
l0rinc (Migrated from github.com) reviewed 2026-08-26 21:30:14 +00:00
l0rinc (Migrated from github.com) commented 2026-08-26 21:30:14 +00:00

Agree, the test is just a demonstration, an assert is the ideal solution here!

Agree, the test is just a demonstration, an assert is the ideal solution here!
sedited commented 2026-10-02 17:09:10 +00:00 (Migrated from github.com)

@andrewtoth what is the status here? I think it would be interesting to add some more real block creation timings, i.e. run this side-by-side with master on hopefully a similar mempool and see if there is a difference.

@andrewtoth what is the status here? I think it would be interesting to add some more real block creation timings, i.e. run this side-by-side with master on hopefully a similar mempool and see if there is a difference.
First-time contributor

Base: a773e1e33b349dc819b5a0edc1c7a4839dc73b48
Head: 2ba5628cb90ea2ae960d3823742412741704e4ca

Findings

Suggestions

Benchmark workload does not reach the block-weight limit (src/bench/block_assemble.cpp:39, head)

With 200 mined blocks and coinbase maturity of 100, the array holds 101 fan-out transactions, producing 10,100 loose spends. Each spend weighs 381 WU (94 stripped bytes plus 5 witness-serialization bytes), for 3,848,100 WU total. Even with the default 8,000-WU reservation, the workload remains below the 4,000,000-WU limit, so the mempool is exhausted before weight-limited selection is exercised. Increase FAN_OUT or assert that the assembled template reaches the configured weight cap.

Review coverage was incomplete.

Review limitations
  • adversarial_deepseek: Stage reported incomplete evidence without identifying the missing evidence.
  • verifier: Finding withheld: Source evidence does not match the snapshot

Full review report

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:1e40d4c29146a38cb238a037edaa35c22b13996a5383ed7a85e089a15d569009:c9412d948811529792d161d97aa6951829440e3d548b7c576bb8d4df4183e0d0 --> Base: `a773e1e33b349dc819b5a0edc1c7a4839dc73b48` Head: `2ba5628cb90ea2ae960d3823742412741704e4ca` ##### Findings **Suggestions** **Benchmark workload does not reach the block-weight limit** (src/bench/block_assemble.cpp:39, head) With 200 mined blocks and coinbase maturity of 100, the array holds 101 fan-out transactions, producing 10,100 loose spends. Each spend weighs 381 WU (94 stripped bytes plus 5 witness-serialization bytes), for 3,848,100 WU total. Even with the default 8,000-WU reservation, the workload remains below the 4,000,000-WU limit, so the mempool is exhausted before weight-limited selection is exercised. Increase `FAN_OUT` or assert that the assembled template reaches the configured weight cap. Review coverage was incomplete. <details> <summary>Review limitations</summary> - adversarial_deepseek: Stage reported incomplete evidence without identifying the missing evidence. - verifier: Finding withheld: Source evidence does not match the snapshot </details> [Full review report](<https://review.fish.foo/traces/35751-2ba5628cb90ea2ae960d3823742412741704e4ca-1356-2.html>)
andrewtoth commented 2026-10-02 18:36:24 +00:00 (Migrated from github.com)

@sedited thanks for the ping. I have been distracted by other issues but I am still interested in pursuing this. I will address @l0rinc's latest comments soon.

One thing I would like to understand better is how checkBlock() is used in practice. How often do we actually call it? One thing to consider is that with this method none of the uncached coins will be pre-emptively inserted into the cache. When many of the block's coins are not cached, this will be much faster on the first call. However, currently these coins will all be cached, while after this change they will not be. So subsequent calls with a similar block might be slower due to not inserting the coins in the cache.

@Sjors' idea https://github.com/Sjors/bitcoin/pull/122 might help here as well, but it's a much larger change.

run this side-by-side with master on hopefully a similar mempool and see if there is a difference.

Yes, good idea. I will try and gather some real world data with this.

Marking as draft until I figure out the above.

@sedited thanks for the ping. I have been distracted by other issues but I am still interested in pursuing this. I will address @l0rinc's latest comments soon. One thing I would like to understand better is how `checkBlock()` is used in practice. How often do we actually call it? One thing to consider is that with this method none of the uncached coins will be pre-emptively inserted into the cache. When many of the block's coins are not cached, this will be much faster on the first call. However, currently these coins will all be cached, while after this change they will not be. So subsequent calls with a similar block might be slower due to not inserting the coins in the cache. @Sjors' idea https://github.com/Sjors/bitcoin/pull/122 might help here as well, but it's a much larger change. > run this side-by-side with master on hopefully a similar mempool and see if there is a difference. Yes, good idea. I will try and gather some real world data with this. Marking as draft until I figure out the above.
l0rinc (Migrated from github.com) requested changes 2026-10-07 07:18:20 +00:00
l0rinc (Migrated from github.com) commented 2026-10-07 06:02:27 +00:00

8ebb32e bench: fill assembled block to max weight in AssembleBlock:

Nit: the fixture checks the entire growing mempool after each insertion, we could probably disable those checks.

Avoid repeated mempool checks during setup
diff --git a/src/bench/block_assemble.cpp b/src/bench/block_assemble.cpp
index 5c15f3cebc..9f9dc5fae1 100644
--- a/src/bench/block_assemble.cpp
+++ b/src/bench/block_assemble.cpp
@@ -29,7 +29,7 @@ using node::BlockCreateOptions;
 
 static void AssembleBlock(benchmark::Bench& bench)
 {
-    const auto test_setup = MakeNoLogFileContext<const TestingSetup>();
+    const auto test_setup = MakeNoLogFileContext<const TestingSetup>(ChainType::REGTEST, {.extra_args = {"-checkmempool=0"}});
 
     CScriptWitness witness;
     witness.stack.push_back(WITNESS_STACK_ELEM_OP_TRUE);
> [8ebb32e](https://github.com/bitcoin/bitcoin/pull/35751/changes/8ebb32e69f8a4959e4d73481c64d7c1282fc9e33) _bench: fill assembled block to max weight in AssembleBlock_: Nit: the fixture checks the entire growing mempool after each insertion, we could probably disable those checks. <details><summary>Avoid repeated mempool checks during setup</summary> ```diff diff --git a/src/bench/block_assemble.cpp b/src/bench/block_assemble.cpp index 5c15f3cebc..9f9dc5fae1 100644 --- a/src/bench/block_assemble.cpp +++ b/src/bench/block_assemble.cpp @@ -29,7 +29,7 @@ using node::BlockCreateOptions; static void AssembleBlock(benchmark::Bench& bench) { - const auto test_setup = MakeNoLogFileContext<const TestingSetup>(); + const auto test_setup = MakeNoLogFileContext<const TestingSetup>(ChainType::REGTEST, {.extra_args = {"-checkmempool=0"}}); CScriptWitness witness; witness.stack.push_back(WITNESS_STACK_ELEM_OP_TRUE); ``` </details>
l0rinc (Migrated from github.com) commented 2026-10-07 06:35:43 +00:00

2ba5628 validation: use parallel input prevout fetching in TestBlockValidity:

Before #35295, coins were fetched as validation reached each transaction, so any failure avoided fetching later transactions, but StartFetching() can now retain those coins before validation rejects the template.

In normal block connection this is gated behind PoW, so paying for that work to allocate an extra ~250 MiB on a node (~25k max inputs × 10 kB max script sizes) seems like a poor trade-off for an attacker. Not sure if this can be amplified in any way by the threads or if it's a total (probably the latter).

But I wonder if this changes the threat model here, given that these template checks aren't behind PoW.

> [2ba5628](https://github.com/bitcoin/bitcoin/pull/35751/changes/2ba5628cb90ea2ae960d3823742412741704e4ca) _validation: use parallel input prevout fetching in TestBlockValidity_: Before #35295, coins were fetched as validation reached each transaction, so any failure avoided fetching later transactions, but `StartFetching()` can now retain those coins before validation rejects the template. In normal block connection this is gated behind PoW, so paying for that work to allocate an extra ~250 MiB on a node (~25k max inputs × 10 kB max script sizes) seems like a poor trade-off for an attacker. Not sure if this can be amplified in any way by the threads or if it's a total (probably the latter). But I wonder if this changes the threat model here, given that these template checks aren't behind PoW.
andrewtoth (Migrated from github.com) reviewed 2026-10-07 14:26:51 +00:00
andrewtoth (Migrated from github.com) commented 2026-10-07 14:26:51 +00:00

In normal block connection this is gated behind PoW, so paying for that work to allocate an extra ~250 MiB on a node (~25k max inputs × 10 kB max script sizes) seems like a poor trade-off for an attacker. Not sure if this can be amplified in any way by the threads or if it's a total (probably the latter).

I'm not sure I follow why an attacker would bother creating an invalid block here? If the goal is to have the node allocate ~250MB, they could create a block that spends ~25k distinct utxos with 10kb scripts. Why would they bother creating an invalid block to do this, instead of creating a valid one and keeping the block reward? I also don't see how #35295 changes anything here; this would allocate the same amount of memory before or after that PR.

But I wonder if this changes the threat model here, given that these template checks aren't behind PoW.

I don't think TestBlockValidity can be called via any untrusted paths, so any threat-model is substantially reduced.

> In normal block connection this is gated behind PoW, so paying for that work to allocate an extra ~250 MiB on a node (~25k max inputs × 10 kB max script sizes) seems like a poor trade-off for an attacker. Not sure if this can be amplified in any way by the threads or if it's a total (probably the latter). I'm not sure I follow why an attacker would bother creating an invalid block here? If the goal is to have the node allocate ~250MB, they could create a block that spends ~25k distinct utxos with 10kb scripts. Why would they bother creating an invalid block to do this, instead of creating a valid one and keeping the block reward? I also don't see how #35295 changes anything here; this would allocate the same amount of memory before or after that PR. > But I wonder if this changes the threat model here, given that these template checks aren't behind PoW. I don't think TestBlockValidity can be called via any untrusted paths, so any threat-model is substantially reduced.
l0rinc (Migrated from github.com) reviewed 2026-10-08 01:04:32 +00:00
l0rinc (Migrated from github.com) commented 2026-10-08 01:04:32 +00:00

These fetches happen before input validation, so the submitter doesn’t need PoW or valid signatures to trigger them. They can reference other people’s UTXOs, even repeating the same large-script UTXO across distinct transactions, and prefetching can allocate copies before validation rejects the attempted spends.

These fetches happen before input validation, so the submitter doesn’t need PoW or valid signatures to trigger them. They can reference other people’s UTXOs, even repeating the same large-script UTXO across distinct transactions, and prefetching can allocate copies before validation rejects the attempted spends.
Yudis-bit commented 2026-10-11 12:40:31 +00:00 (Migrated from github.com)

overlay_view.GetCacheSize() == 0 won't catch reentrancy while prefetching is in flight because worker threads write coins into m_inputs, not cacheCoins. The cache size stays at zero until ConnectBlock consumes the first coin, so an in-between call would pass that assert and hit Assert(m_futures.empty()) inside StartFetching.

Checking !m_futures.empty() or falling back to a local CCoinsViewCache when the shared overlay is busy would handle that cleanly without aborting.

overlay_view.GetCacheSize() == 0 won't catch reentrancy while prefetching is in flight because worker threads write coins into m_inputs, not cacheCoins. The cache size stays at zero until ConnectBlock consumes the first coin, so an in-between call would pass that assert and hit Assert(m_futures.empty()) inside StartFetching. Checking !m_futures.empty() or falling back to a local CCoinsViewCache when the shared overlay is busy would handle that cleanly without aborting.
Sjors (Migrated from github.com) reviewed 2026-10-26 11:33:03 +00:00
Sjors (Migrated from github.com) left a comment

It would be good to add some relevant benchmarks in the PR description.

This also has the benefit of not inserting entries fetched from db into the main cache.

This might be useful regardless of the other change. Although checkBlock() is called by a (for now) trusted IPC client, that client in turn takes mostly untrusted data for miners. They could stuff our hot cache and trigger a flush.

At least one pool (DMND), which supports stratum v2 miner-provided templates, rate limits the number of blocks each client can check. But the more DoS-resistant we can make this, the better.

On the other hand, when validating many similar templates, it might be nice to actually insert fetched entries. But maybe, in a future optimization, the block template manager (#35675) could create a shared cache and opt-in to inserting fetched coins, up to a certain limit.

I changed the approach in https://github.com/Sjors/bitcoin/pull/122 a bit and updated the benchmarks.

It optimistically pre-fetch coins as the template is being assembled (see #35671). This gives it a head start in cases where at least one transaction is missing, when we have to wait a network roundtrip for the miner to provide it. I then added the approach from this PR on top; the optimistic sync is stopped and the coins it fetched are passed on to TestBlockValidity.

That approach saves 10ms in the network round-trip scenario. Whether it's worth the complexity, I don't know.

It would be good to add some relevant benchmarks in the PR description. > This also has the benefit of not inserting entries fetched from db into the main cache. This might be useful regardless of the other change. Although `checkBlock()` is called by a (for now) trusted IPC client, that client in turn takes mostly untrusted data for miners. They could stuff our hot cache and trigger a flush. At least one pool (DMND), which supports stratum v2 miner-provided templates, rate limits the number of blocks each client can check. But the more DoS-resistant we can make this, the better. On the other hand, when validating many similar templates, it might be nice to actually insert fetched entries. But maybe, in a future optimization, the block template manager (#35675) could create a shared cache and opt-in to inserting fetched coins, up to a certain limit. I changed the approach in https://github.com/Sjors/bitcoin/pull/122 a bit and updated the benchmarks. It optimistically pre-fetch coins as the template is being assembled (see #35671). This gives it a head start in cases where at least one transaction is missing, when we have to wait a network roundtrip for the miner to provide it. I then added the approach from this PR on top; the optimistic sync is stopped and the coins it fetched are passed on to TestBlockValidity. That approach saves 10ms in the network round-trip scenario. Whether it's worth the complexity, I don't know.
Sjors (Migrated from github.com) commented 2026-10-26 09:11:09 +00:00

In 2ba5628cb9 validation: use parallel input prevout fetching in TestBlockValidity: maybe introduce ConnectBlockView in a pure refactor commit?

In 2ba5628cb90ea2ae960d3823742412741704e4ca _validation: use parallel input prevout fetching in TestBlockValidity_: maybe introduce `ConnectBlockView` in a pure refactor commit?
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!35751
No description provided.