mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:47:36 +00:00
mining: move getblocktemplate cache into BlockTemplateManager #36356
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!36356
Loading…
Reference in a new issue
No description provided.
Delete branch "block-template-manager-gbt-cache"
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?
Follow-up to #35675. This addresses the
getblocktemplatepart of the "Remove remaining global states" TODO in #33758, as suggested in https://github.com/bitcoin/bitcoin/pull/35675#pullrequestreview-5299625960.getblocktemplatereuses its last template until the tip changes, or until the mempool changes and the template is more than 5 seconds old. That cache currently lives in four function-local statics, which:CBlockIndex*can outlive itsChainstateManager(as in unit tests);cs_mainbeing held, which nothing checks;This PR moves the cache into
BlockTemplateManager, in three commits:CachedBlockTemplatestruct and aGetNewOrCachedBlockTemplate()helper,GUARDED_BY(::cs_main). The template'shashPrevBlockreplaces the cachedCBlockIndex*, and the 5 seconds becomesGBT_TEMPLATE_REBUILD_INTERVAL.BlockTemplateManager. It's easiest to review withgit show --color-moved=dimmed-zebra --color-moved-ws=allow-indentation-change.No behavior change is intended, and only
getblocktemplateuses the cache. It usescs_mainrather than its own mutex, since the RPC already holds it and building a template takes it anyway.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.
No verified findings are available from this review.
Review coverage was incomplete.
Reviewed:
00a62a2a91e0· Review report · Previous reportspermalink
I plan to review this.
Concept ACK
I think we can implement the broader cache as attempted here #33421, mempool estimator dependency on
ChainStateManagerwill be gone, and the ipccreatenewblock,waitnextandgetblocktemplateRPC can use it too. That way we have shared code for all three?This has a bit of an advantage when the 7 sec for the mempool fee rate estimator elapses and no mempool change, we wont rebuilt; same for the waitnext too. We can later extend to use actual top block inflow to decide not just mempool transaction list number change, that may not affect the top block.
see POC
We may need to extend this to clear all cache on tip change though to free some memory, this diff currently has them till shutdown.
@ismaelsadeeq Thanks for the Concept ACK and the POC. I’d prefer to keep this PR focused on moving the existing getblocktemplate cache while preserving its behavior.
The POC introduces multiple entries keyed by build options, eviction, another mutex, configurable freshness and forced rebuilds, plus changes to IPC and fee estimation. Those bring separate correctness and performance questions, so I think the broader cache would be a better fit for a follow-up.
This refactor gives that work a place to build on.
Fair, I think it would be nice to have the cache and make this generic. The reason the broader cache wasn't pursued further in #33421 is thin motivation (i.e., no users as of then).
But with this, we cache anyway, so making it generic is a nice win and usable by not just
getblocktemplaterpc. However, I agree this is a start; we can extend it later. It is just a bit more work to have a single template cache design and then extend it to multiple after merging.I get that this is simpler to reason about and review, but it would be more ideal if we decide whether we want to do the caching for all or not.
CC @sedited and @stickies-v since u both weigh in here #33421
The cache is kept forever till shutdown. Should we clear it on a block connection?
Should we pass the
max_ageso that it is not tied to GBT? Could we also rename it toGetNewOrCacheBlockTemplateor something similar?🐙 This pull request conflicts with the target branch and needs rebase.
I also prefer to keep this simple and focussed.
I'm not sure if the current two commit split is the easiest to review, because instead of moving code we now have one commit that introduces new code and a second commit that deletes old code.
Thanks! Master already keeps the last template until the node stops (in the
getblocktemplatestatics); this PR only moves it.It's a single template, and the next call after a new block replaces it.
Clearing it on block connection would need a new notification hook in the manager, so I'd leave that for a follow-up.
Thanks! Renamed it to
GetNewOrCachedBlockTemplate().I'd keep
max_ageout of this PR. The cache is still a single entry built with the default options, so another caller with a differentmax_agewould just keep rebuilding the GBT template. It fits better in a follow-up that makes the cache generic, like your POC. I did give the 5 seconds a name, though:GBT_TEMPLATE_REBUILD_INTERVAL.Thanks, good point. I've split it into three commits:
rpc/mining.cpp, so the diff compares each change directly against master's code.BlockTemplateManager. It should be easy to check withgit show --color-moved=dimmed-zebra --color-moved-ws=allow-indentation-change.PR description updated.
🐙 This pull request conflicts with the target branch and needs rebase.
Code Review https://github.com/bitcoin/bitcoin/pull/36356/changes/b7a6cf47363c01d7507601bdb09847f90aaf2c59
The cache fits better in
BlockTemplateManagersince this is already where templates are created. Its lifetime now follows the manager, instead of leaving cache state around in the rpc statics.I think the shared template gives us room to shorten the
cs_maincritical section in a followup. At the moment,getblocktemplateholds the lock while encoding transactions, calculating their dependencies, and constructing the response. Most of that work only needs the template we already obtained.With
shared_ptr<const CBlockTemplate>, a request can keep reading its template after releasing the lock. Another request could rebuild the cache without destroying the template the first request is using. Previously, simply unlocking around that work would have been unsafe because replacing the staticunique_ptrcould invalidate what the first request was reading.We’d still need to collect the chain dependent information before unlocking. But moving the transaction encoding and response construction outside that section seems worth exploring, especially with multiple clients calling
getblocktemplate.In commit https://github.com/bitcoin/bitcoin/pull/36356/changes/56078a5bf728cd48882a17b49e6079267178698b: refactor: move getblocktemplate cache into BlockTemplateManager
I think would be useful to cover is the change in cache lifetime. The existing test checks when a manager reuses or rebuilds its template, but everything happens within the same manager instance.
Previously, the cache was process wide, so destroying and recreating the manager wouldn’t clear that state. Now that the cache belongs to
BlockTemplateManager, a new instance should start with an empty cache, even if the chain tip and mempool haven’t changed. That seems like one of the main benefits of this refactor, so it would be good to protect it with a test.I’ve included a small possible patch to achieve this:
this would build a template, destroy the manager, and create a replacement. It would then check that the replacement’s cached mempool counter starts at zero and that its first request produces a different template object. The original template is kept alive through its shared pointer, so its address cannot be reusued and accidentally affect the comparison.
Could we use
MockableSteadyClockhere, since we only care about how much time has passed since the last build?NodeClockfollows system time, so a possible backward clock adjustment could delay a mempool triggered rebuild?In commit https://github.com/bitcoin/bitcoin/pull/36356/changes/fceffe693c893cc45ffb6778c10be9410531fd93: rpc: gather the getblocktemplate cache state into a struct
nit: Just a small cleanup but could we use this here instead:
cachedalready owns the shared pointer and stays alive for the rest of this scope, so we can reference its member instead of making another shared pointer copy🐙 This pull request conflicts with the target branch and needs rebase.
Thanks. Done. Added you as co-author.
Thanks. Done.
Thanks! A steady clock makes sense for measuring the rebuild interval. I’d leave the switch for a follow-up because
mining_prioritisetransaction.pyusessetmocktimeto age the cached template. Updating that test would expand the scope of this PR.CI errors are unrelated
@enochaz Following up on the
MockableSteadyClocksuggestion: while looking atmining_prioritisetransaction.py, I found its check passes even when the template isn't rebuilt, sincecurtimechanges with mocktime. I opened #36921 to fix that.The steady clock change is in #36922, on top of this PR and #36921.
I added you as co-author on both PRs. Thanks for the suggestion!