Repository navigation
validation: use parallel input prevout fetching in TestBlockValidity - #35751
andrewtoth wants to merge 2 commits into
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. |
|
For the record: This is a follow up to #31132 (comment) and #34164 (comment). https://corecheck.dev/bitcoin/bitcoin/pulls/35751 claimed DetailsCould you provide a reproducible way to test the performance claim, ideally using a deterministic set of mainnet block proposals or a microbenchmark? |
@l0rinc is that the correct benchmark data you meant to post in the details? It doesn't seem to show the a slowdown...
There have been many benchmarks performed already by you in #31132 for this change. Is this not obvious to you it will increase performance? |
I see it in the report too, and can measure the slowdown locally as well. |
|
If I fill up the block properly in the 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? |
|
Concept ACK on (indirectly) making the Although #35671 introduces a different approach for that, its I haven't studied the earlier work, so for that reason alone a quick benchmark might be nice to demonstrate to others too. |
985d248 to
2046c94
Compare
2046c94 to
ff4dd42
Compare
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
|
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 Before this change
After this change
@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. |
optout21
left a comment
There was a problem hiding this 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)};
Could this also use the newly introduced ConnectBlockView()?
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.
ff4dd42 to
2ba5628
Compare
|
Thanks for your review @optout21.
It was using a
Done. |
l0rinc
left a comment
There was a problem hiding this 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).
| tx.vout.emplace_back(1337, P2WSH_OP_TRUE); | ||
| tx.vout.assign(FAN_OUT, CTxOut{100'000, P2WSH_OP_TRUE}); | ||
| if (NUM_BLOCKS - b >= COINBASE_MATURITY) | ||
| txs.at(b) = MakeTransactionRef(tx); |
There was a problem hiding this comment.
nit: we could std::move a few of these (please check the other cases as well):
| txs.at(b) = MakeTransactionRef(tx); | |
| txs.at(b) = MakeTransactionRef(std::move(tx)); |
| LOCK(::cs_main); | ||
|
|
||
| for (const auto& txr : txs) { | ||
| for (const uint32_t o : std::views::iota(uint32_t{0}, FAN_OUT)) { |
There was a problem hiding this comment.
nit: I don't usually mind this iteration, but above we're using standard loop which makes the two iterations assymetric
| bench.run([&] { | ||
| PrepareBlock(test_setup->m_node, options); | ||
| }); | ||
| } |
There was a problem hiding this comment.
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.
| tx.vin.back().scriptWitness = witness; | ||
| tx.vout.emplace_back(1337, P2WSH_OP_TRUE); | ||
| tx.vout.assign(FAN_OUT, CTxOut{100'000, P2WSH_OP_TRUE}); | ||
| if (NUM_BLOCKS - b >= COINBASE_MATURITY) |
There was a problem hiding this comment.
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
| tx.vin.emplace_back(COutPoint{txr->GetHash(), o}); | ||
| tx.vin.back().scriptWitness = witness; | ||
| tx.vout.emplace_back(1337, P2WSH_OP_TRUE); | ||
| const MempoolAcceptResult res = test_setup->m_node.chainman->ProcessTransaction(MakeTransactionRef(tx)); |
There was a problem hiding this comment.
8ebb32e bench: fill assembled block to max weight in AssembleBlock:
we don't need to copy the existing style:
| const MempoolAcceptResult res = test_setup->m_node.chainman->ProcessTransaction(MakeTransactionRef(tx)); | |
| const auto res{test_setup->m_node.chainman->ProcessTransaction(MakeTransactionRef(tx))}; |
| index_dummy.nHeight = tip->nHeight + 1; | ||
| index_dummy.phashBlock = &block_hash; | ||
| CCoinsViewCache view_dummy(&chainstate.CoinsTip()); | ||
| CoinsViewOverlay& overlay_view{chainstate.ConnectBlockView()}; |
There was a problem hiding this comment.
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());
}There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Agree, the test is just a demonstration, an assert is the ideal solution here!
|
@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. |
|
@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 @Sjors' idea Sjors#122 might help here as well, but it's a much larger change.
Yes, good idea. I will try and gather some real world data with this. Marking as draft until I figure out the above. |
| tx.vin.emplace_back(COutPoint{txr->GetHash(), o}); | ||
| tx.vin.back().scriptWitness = witness; | ||
| tx.vout.emplace_back(1337, P2WSH_OP_TRUE); | ||
| const MempoolAcceptResult res = test_setup->m_node.chainman->ProcessTransaction(MakeTransactionRef(tx)); |
There was a problem hiding this comment.
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);| index_dummy.phashBlock = &block_hash; | ||
| CCoinsViewCache view_dummy(&chainstate.CoinsTip()); | ||
| CoinsViewOverlay& overlay_view{chainstate.ConnectBlockView()}; | ||
| const auto reset_guard{overlay_view.StartFetching(block)}; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
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. |
Give TxCollection a background thread that loads the input coins of collected transactions into the active chainstate's coins cache, so that by the time the client calls makeTemplate() the TestBlockValidity() check does not need to read them from disk. Work is queued by the constructor and by addMissingTxs(), both of which return without waiting for it: the coins load while the (Stratum v2 Job Declarator) client learns which transactions are missing and transfers them, taking the coin database reads off the template critical path. The thread warms the cache through CCoinsViewCache::HaveCoin() in batches of 128 outpoints per cs_main acquisition, so it never holds up validation for a full block's worth of disk reads. Coins fetched this way are clean cache entries: they do not grow the next flush and can be evicted at any time, and they remain useful when the actual block is connected. Inputs spending other transactions in the collection are skipped, since they have no coin in the UTXO set. Suggested by Sjors Provoost in bitcoin#35751 (comment) Co-Authored-By: Claude Fable 5 <[email protected]>
Give TxCollection a background thread that loads the input coins of collected transactions into the active chainstate's coins cache, so that by the time the client calls makeTemplate() the TestBlockValidity() check does not need to read them from disk. Work is queued by the constructor and by addMissingTxs(), both of which return without waiting for it: the coins load while the (Stratum v2 Job Declarator) client learns which transactions are missing and transfers them, taking the coin database reads off the template critical path. The thread warms the cache through CCoinsViewCache::HaveCoin() in batches of 128 outpoints per cs_main acquisition, so it never holds up validation for a full block's worth of disk reads. Coins fetched this way are clean cache entries: they do not grow the next flush and can be evicted at any time, and they remain useful when the actual block is connected. Inputs spending other transactions in the collection are skipped, since they have no coin in the UTXO set. Suggested by Sjors Provoost in bitcoin#35751 (comment) Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this 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 Sjors#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 does ~12ms of prep work during the network round-trip, but (so far) that implementation doesn't actually add any performance compared to this PR.
Update: with a 10 GB chainstate and a mostly cold cache, fetching from disk while waiting for the missing transactions can make a whole second difference in the final block check.
| Ticks<MillisecondsDouble>(time_2 - time_1)); | ||
| { | ||
| CoinsViewOverlay& view{*m_coins_views->m_connect_block_view}; | ||
| CoinsViewOverlay& view{ConnectBlockView()}; |
There was a problem hiding this comment.
In 2ba5628 validation: use parallel input prevout fetching in TestBlockValidity: maybe introduce ConnectBlockView in a pure refactor commit?

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.