mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 09:38:38 +00:00
WIP: validation: use parallel input prevout fetching in TestBlockValidity #35751
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!35751
Loading…
Reference in a new issue
No description provided.
Delete branch "testblockvalidity-startfetching"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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.
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.
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:
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.
ACK 985d248383b43205f98a6971eb887ffa239adf85
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
AssembleBlockslowed down considerably but I can't reproduce it locally (though I can confirm it's called from the benchmark).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.
@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
AssembleBlockbenchmark, 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?
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 throughTextBlockValidity. I wonder ifTxCollectioncould be made even faster if pre-loads coins it needs, before a client callsmakeTemplate()to check the full block. Update: see https://github.com/Sjors/bitcoin/pull/122I haven't studied the earlier work, so for that reason alone a quick benchmark might be nice to demonstrate to others too.
🚧 At least one of the CI tasks failed.
Task
iwyu: https://github.com/bitcoin/bitcoin/actions/runs/30417973130/job/90468502585LLM reason (✨ experimental): CI failed because IWYU reported a missing/incorrect
#includeinsrc/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.
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
AssembleBlockbenchmark 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
AssembleBlockAssembleBlockAssembleBlockAfter this change
AssembleBlockAssembleBlockAssembleBlock@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.
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:(
github.com/andrewtoth/bitcoin@ff4dd421f9/src/validation.cpp (L3055-L3056))Could this also use the newly introduced
ConnectBlockView()?A note on "dummy" naming: before the change,
view_dummywas 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 toview_shared. (There are not many usages to change).I renamed it to overlay_view.
Thanks for your review @optout21.
It was using a
CCoinsViewCachebefore as an ephemeral cache on top of the main cache. This patch changes it to use theCoinsViewOverlay. The previous version would insert cache misses into the cache before returning to theview_dummycache, whileCoinsViewOverlaydoes not do that. I updated the commit message and PR description to try and clarify that.Done.
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).
nit: and if we're modifying this we might as well add braces and format it
nit: we could
std::movea few of these (please check the other cases as well):nit: I don't usually mind this iteration, but above we're using standard loop which makes the two iterations assymetric
we don't need to copy the existing style:
The commit message claims we
fill assembled block to max weight, but we still have leftover transactions - can we assert the claim (and adjust theFAN_OUTto make it true? Just make sure the number is not110, we're still sensitive to that...)TestBlockValidity()previously used a local cache. This PR changes it to reuseConnectBlockView(), which a synchronousBlockCheckedcallback can reach whileConnectTip()still has a fetch active.Could we first record that both paths now select the same overlay?
I don't think there is a reentrancy issue? I see though that
BlockCheckedcallbacks inConnectTipare synchronous, so a future change could theoretically callTestBlockValidityfrom the callback on the same thread. Nothing does that today. We can prevent this by callingAssert(overlay_view.GetCacheSize() == 0);insideTestBlockValidity. I'm not sure I see the value of this unit test.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.
Base:
a773e1e33b349dc819b5a0edc1c7a4839dc73b48Head:
2ba5628cb90ea2ae960d3823742412741704e4caFindings
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_OUTor assert that the assembled template reaches the configured weight cap.Review coverage was incomplete.
Review limitations
Full review report
@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.
Yes, good idea. I will try and gather some real world data with this.
Marking as draft until I figure out the above.
Nit: the fixture checks the entire growing mempool after each insertion, we could probably disable those checks.
Avoid repeated mempool checks during setup
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.
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.
I don't think TestBlockValidity can be called via any untrusted paths, so any threat-model is substantially reduced.
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.
It would be good to add some relevant benchmarks in the PR description.
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.
In
2ba5628cb9validation: use parallel input prevout fetching in TestBlockValidity: maybe introduceConnectBlockViewin a pure refactor commit?