mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 16:05:36 +00:00
mining: add Block interface, fix template data race #36525
No reviewers
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!36525
Loading…
Reference in a new issue
No description provided.
Delete branch "2026/10/block-template-mutex"
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?
This PR catches two birds with one stone:
Blockinterface, which lets IPC clients fetch the block data (or its header)This means a client can still fetch (and store) the block after
submitSolution(), but we no longer mutate the template'sCBlockfor this.Block interface
submitSolution()no longer modifies the template. It applies the solution to a copy of the template block and returns aBlockhandle for that copy, also when the block is rejected.Mining::submitBlock()andBlockTemplate::block()do the same. The new interface has adata(),header()andcoinbaseMerklePath()method, so these are migrated from theBlockTemplateinterface.The interface can be expanded later, e.g. to tell whether the block is part of the active chain (or went stale, useful for a miner to know).
This is a breaking change for IPC clients:
getBlockHeader()→block().header()getBlock()→block().data()getCoinbaseMerklePath()→block().coinbaseMerklePath()bool submitSolution(..., reason, debug)→Block submitSolution(..., accepted, reason, debug)bool submitBlock(block, reason, debug)→Block submitBlock(block, accepted, reason, debug)It uses new ordinals and old methods throw.
submitSolution()now throws when the coinbase is null, instead of returning false.Performance
My agent measured how long after
submitSolution()sv2-tp forwards the next template, with master as the baseline and an adapted sv2-tp as the client:The extra
block()call costs about 0.15 ms per template for a C++ client. The alternative approach of havingsubmitSolution()return the fullCBlockadded 6ms.Memory
A
Blockhandle keeps the template's memory, including its transactions, allocated until the client destroys the handle. This also applies to handles returned bysubmitSolution()andsubmitBlock(). This doesn't matter much in practice since (the existing) clients don't hold on to aBlocklong.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:
CreateNewBlock_validityinto independent test cases by yuvicc)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.
LLM Linter (✨ experimental)
Possible places where named args for integral literals may be used (e.g.
func(x, /*named_arg=*/0)in C++, andfunc(x, named_arg=0)in Python):test/functional/interface_ipc_mining.py:template.submitSolution(ctx, 0, 0, 0, b"")2026-12-01 14:09:11
Earlier concerns neither republished nor resolved: 2 suggestions. See the Run archive linked from the Review report for their assessments.
🟠 Minor · Failure cleanup can destroy the template during
submitSolution()On failure or timeout,
run_concurrent_template_access_test()cancels client awaits without draining the writer worker, so template destruction can race with server-sidesubmitSolution().Location:
test/functional/interface_ipc_mining.py:951(head).🔵 Suggestion · Mining IPC migration is missing a release note
The intentional mining IPC break has no release note explaining the replacement methods,
acceptedresults, or the lifetime of returnedBlockhandles.Location:
src/ipc/capnp/mining.capnp:51(head).🔵 Suggestion · Submitted
Blocksnapshots are only checked immediatelyNo test rereads a
submitSolution()handle after another submission or template destruction, so it would miss reusable storage changing a previously returned block.Location:
test/functional/interface_ipc_mining.py:609(head).🔵 Suggestion · The race test is rewritten in the next commit
The race-test commit adds three
getBlockHeader()calls that the next commit immediately rewrites toblock().header(), adding avoidable review churn.Location: test/functional/interface_ipc_mining.py:925 (commit).
Review coverage was incomplete.
Reviewed:
283d5ae4e890· Review report · Previous reportspermalink
ACK
4774cf1de6I thought the client needed to access the individual fees, so we return a vector. It makes sense to return it so they don't have to sum them, so the vector one is now redundant?
See minimal test that fails on our tsan functional tests.
The vector was initially introduced for (internal) compatibility with the
getblocktemplateRPC, which returns this fee information.sv2-tponly uses fees (the total) for logging, the SRI implementation doesn't use it at all.I haven't done an inventory of software out there that uses the fees from
getblocktemplate. One use case I could imagine is a miner dashboard that shows the current template you're working on, and a breakdown of fees.We definitely need the internal total. Providing the total and individual via IPC is trivial, so I think we should keep it.
It works and I'm open to taking it, but failure isn't deterministic (just very likely with the 100 iterations).
Concept ACK
Indeed, it is not deterministic but is sure to fail at some point.
ACK
4774cf1de6This change fixes a data race between ipc calls running on different worker threads, where
submitSolutionmodifies a template while another call reads it. It also adds thegetTotalFeesIPC method, allowing external clients to retrieve the total fees without summing individual transaction fees.Ran @ismaelsadeeq's ipc test with tsan, 25 times each with 100, 150, 200 and 300 submissions. without the mutex fix, all 100 runs detected the race. with the fix, all 100 passed with no race reports or timeouts.
I think the test is worth including. even though reproduction depends on scheduling, it consistently caught the regression on my machine (macOS ARM64)
Added the test in a new commit, with some adjustments:
timeout_factorto avoid false positive failuresreACK
cbadeff334reACK https://github.com/bitcoin/bitcoin/pull/36525/changes/cbadeff334f182086538d7483dc1146c559859e6
ACK
cbadeff334nit:
@w0xlt I prefer the existing wording:
The function doesn't know where the caller got its hash.
Might it be preferable to make
m_block_templatenon-mutating? Do users of the interface even need the mutated template after submitting?AFAICT no, so we could do that and make the template const, that way no race and we copy when mutating for submission.
I think it's a preferable solution. With no writes after construction there's no race, and since
submitSolution()already copies the block, callingAddMerkleRootAndCoinbase()on that copy instead of on the template costs nothing.The documentation and tests would need to be updated too, since the in-place mutation is documented and tested since #33745 (released in v31).
The sv2-tp client apparently relies on that mutation (
SaveBlockAsync()), but it may be easy to update.Yes. Both existing clients call
getBlock()after submit to store a copy of the block. This is potentially very useful when debugging a rejected block.Clients could download the non-mutated block and re-apply the solution themselves before storing to disk. That's slightly more complicated, so I prefer the existing approach.
Could we just return the block copy after applying the solution?
@ismaelsadeeq in theory yes, but clients intentionally wait 1 second before requesting it. If the solution is correct, we don't want to "distract" the node from relaying it and from producing the next template.
I don't understand what you mean here. Doesn't the new valid header get processed synchronously anyway?
A call to
getBlock()lockscs_main(briefly). Sincesv2-tptypically runs on the same machine, when it saves to disk it also blocks the OS. Creating the new template blockscs_main. And IIUC so does our p2p code when it announces the new block and handles compact block missing-transaction requests.That said, I haven't done a very thorough analysis on whether the 1 second delay before
getBlock()actually matters.That should all be unrelated to copying a block. Or is the concern just that the OS might be something more important in the meantime and this might distract it? I don't think that is a valid concern.
I wrote:
This is not the case.
I benchmarked the approach of making the template block immutable and returning the full block in
submitSolution(). The good news is that there's no regression in compact block relay, not even when a transaction is missing.But it does add a 6ms slowdown to when sv2-tp serves the next template. That's because IPC code still bottlenecks a few things on a single thread (even with multiple connections).
I was able to reduce that by having sv2-tp skip block deserialization (including sha256 hashing), and write the serialized bytes straight to disk (after a 500ms delay). That still left 2.5ms.
Things can be sped up further by:
These require changes to libmultiprocess.
So my preference would be to defer making CBlockTemplate const until after these improvements land. This would be a breaking change for clients, but that's straight-forward to work around.
There's another approach, though a bit of a layer violation: we can have
submitSolution()defer its response so it comes afterwaitNext(). But I also prefer doing that as a followup, rather than increase the scope of this PR.🐙 This pull request conflicts with the target branch and needs rebase.
Rebased after #36192.
Concept ACK on getTotalFees()
Could you share how you benchmarked this? I'd like to reproduce it and it would also be useful for measuring the libmultiprocess improvements later.
IMO 6ms or 2.5ms seems an acceptable cost for an immutable template, especially since it only applies after the miner itself finds a valid block and you've already identified ways to bring it down. Doing it now avoids adding a mutex that would likely be removed later and gives a cleaner interface for users that are currently experimenting with it.
Here you go: https://gist.github.com/Sjors/22182fa24d2cf1337bed19cf70591c4f
One of the selling points of Stratum v2 is lower latency, see e.g. https://stratumprotocol.org/blog/case-study/hashlabs/
I don't know what methodology they used (might be a bit optimistic), but adding 6ms just for a code style improvement, doesn't seem justified in light of those numbers.
Thanks @Sjors! I was able to reproduce it on my machine. I got similar results.
The latency measured doens't affect block propagation but "Block Change latency" which is 325 ms for SV1 and 1.42 ms for SV2 with JD. I still consider the 6ms after
submitSolutiona negligible delay because its average cost per network block is about 6 ms × hashrate share: ~1.8 ms for a 30% pool, ~0.06 ms for a 1% miner.That said, I don’t feel strongly about. I am fine with it being a future follow up.
I tried another approach:
submitSolution()returns aSubmittedBlockcapability instead of the block itself, so the client can fetch it later withgetBlock(), only if and when it needs it. The template stays immutable and there's no mutex.Benchmarked it and got no performance regression with this approach.
Draft:
Bitcoin Core diff:
github.com/ViniciusCestarii/bitcoin@5c7fe8ee23sv2-tp diff:
github.com/ViniciusCestarii/sv2-tp@7faa751ed1This gets the immutable template without the regression and without waiting for the libmultiprocess improvements. Happy to open it as a followup PR.
🐙 This pull request conflicts with the target branch and needs rebase.
Rebased after #36451.
@ViniciusCestarii looking into your approach
I added a new
Blockinterface. To keep this PR simple, I'm going to open a fresh PR forgetTotalFees(), since it no longer makes sense to combine that feature (requested in https://github.com/bitcoin/bitcoin/pull/35671#issuecomment-6165435275) with the fix for https://github.com/bitcoin/bitcoin/issues/36515. Most review on this PR was focussed on the latter.The
Blockinterface is returned bysubmitSolution(),submitBlock()andgetBlock(). It starts out with justdata(),header()andcoinbaseMerklePath(). The latter two are moved out ofBlockTemplate.It could later be expanded later to e.g. say if a block is part of the active chain (very useful for a miner to know).
The
coinbaseTx()getter stays on the template, because it does not return the actual coinbase transaction but rather a struct that is only useful for mining software to generate a coinbase transaction.I'm keeping
getTxFees()andgetTxSigops()in the template, because they are calculated at template generation time and non-trivial to calculate in other contexts.The chain interface proposed in #29409 might also be able to use this.
I renamed
getBlock()toblock(), so clients callblock().data()to get the block's data. Note that this takes advantage of Cap’n Proto promise pipelining (see theipc_util.pychange).This is a breaking change and I intentionally made
getBlockOld2, etc fail, because in the past reviewers complained when I made backward compatible changes while the interface is still experimental. This is no problem for sv2-tp and SRI which are pretty good at handling our breaking changes between our major releases. (FWIW my goal is to remove the experimental status after Windows support lands)I ran the performance benchmark again and there's no regression, so: a better interface, no need for a mutex and it stays fast.
Code review
1f9fcfab45The approach is sound to me, but now the
Blockcapability served to clients holds references to TXs that might leave the mempool. IPC clients now take responsibility for dropping these block capabilities and as a result freeing up memory on the node (good this is that this is trivial to inspect with thegetMemoryLoadmethod proposed in #33922). This behaviour change should be documented in the PR description and the first commit msg.Planning to review more.
In commit
1f9fcfab45"mining: return Block from Mining::submitBlock()"nit:
result -> accepted
Taken, thanks.
Approach ACK
Approach ACK
Plan to review.
In "mining: add Block interface, return it from BlockTemplate::block()"
8649a6c2eaWhy name
blockinstead ofgetBlock? The otherBlockTemplateaccessors all have get as prefix (getTxFees,getTxSigops,getCoinbaseTx) so this makes it the odd one out.In "mining: add Block interface, return it from BlockTemplate::block()"
8649a6c2eanit: its type could be
util::NotNullSharedPtr<const CBlock>to make it explicit that it can't be null and also makes it consistent withm_block_template.Because
block()itself has aget()method which actually gets the block.Done.
I assume you mean
block()hasdata()that returns the block. So the convention is that methods starting withgetreturn data while handles don't? By that logic shouldn't theblockmethods begetData(),getHeader(),getCoinbaseMerklePath()?