Repository navigation
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. |
|
I plan to review this. |
|
Concept ACK I think we can implement the broader cache as attempted here #33421, mempool estimator dependency on 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 POCWe 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 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 |
| ChainstateManager& m_chainman; | ||
| KernelNotifications& m_notifications; | ||
| const BlockCreateOptions m_block_create_args; | ||
| CachedBlockTemplate m_cached_template GUARDED_BY(::cs_main); |
There was a problem hiding this comment.
The cache is kept forever till shutdown. Should we clear it on a block connection?
There was a problem hiding this comment.
Thanks! Master already keeps the last template until the node stops (in the getblocktemplate statics); 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.
| * never null. | ||
| * @throws std::runtime_error if building the template fails. The cache is | ||
| * then left without a template, so the next call tries again. */ | ||
| CachedBlockTemplate RefreshCachedTemplate() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); |
There was a problem hiding this comment.
Should we pass the max_age so that it is not tied to GBT? Could we also rename it to GetNewOrCacheBlockTemplate or something similar?
There was a problem hiding this comment.
Thanks! Renamed it to GetNewOrCachedBlockTemplate().
I'd keep max_age out of this PR. The cache is still a single entry built with the default options, so another caller with a different max_age would 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.
|
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. |
c12310c to
ed3dd14
Compare
|
Thanks, good point. I've split it into three commits:
|
|
PR description updated. |
ed3dd14 to
b7a6cf4
Compare
enochaz
left a comment
There was a problem hiding this comment.
Code Review b7a6cf4
The cache fits better in BlockTemplateManager since 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_main critical section in a followup. At the moment, getblocktemplate holds 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 static unique_ptr could 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.
| ChainstateManager& m_chainman; | ||
| KernelNotifications& m_notifications; | ||
| const BlockCreateOptions m_block_create_args; | ||
| CachedBlockTemplate m_cached_template GUARDED_BY(::cs_main); |
There was a problem hiding this comment.
In commit 56078a5: 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:
index 5afa32f8a0..2a455bf53c 100644
--- a/src/test/miner_tests.cpp
+++ b/src/test/miner_tests.cpp
@@ -1048,4 +1048,26 @@ BOOST_FIXTURE_TEST_CASE(block_template_manager_cached_template, RegTestingSetup)
BOOST_CHECK_EQUAL(fifth.block_template->block.hashPrevBlock, new_tip);
}
+BOOST_AUTO_TEST_CASE(block_template_manager_cache_lifetime)
+{
+ LOCK(::cs_main);
+
+ Assert(m_node.mempool)->AddTransactionsUpdated(1);
+ const auto first{Assert(m_node.block_template_manager)->GetNewOrCachedBlockTemplate()};
+ BOOST_REQUIRE(first.block_template);
+ BOOST_REQUIRE(first.transactions_updated != 0);
+
+ m_node.block_template_manager.reset();
+ CreateBlockTemplateManager();
+
+ auto& manager{*Assert(m_node.block_template_manager)};
+ BOOST_CHECK_EQUAL(manager.GetCachedTransactionsUpdated(), 0);
+
+ const auto second{Assert(m_node.block_template_manager)->GetNewOrCachedBlockTemplate()};
+ BOOST_REQUIRE(second.block_template);
+ BOOST_CHECK(second.block_template != first.block_template);
+
+ BOOST_CHECK(manager.GetNewOrCachedBlockTemplate().block_template == second.block_template);
+}
+
BOOST_AUTO_TEST_SUITE_END()
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.
There was a problem hiding this comment.
Thanks. Done. Added you as co-author.
| } | ||
| CHECK_NONFATAL(pindexPrev); | ||
| const CachedBlockTemplate cached{GetNewOrCachedBlockTemplate(block_template_manager, chainman, mempool)}; | ||
| const std::shared_ptr<const node::CBlockTemplate> block_template{cached.block_template}; |
There was a problem hiding this comment.
In commit fceffe6: rpc: gather the getblocktemplate cache state into a struct
nit: Just a small cleanup but could we use this here instead:
index 1557e9f663..6c7c6d5453 100644
--- a/src/rpc/mining.cpp
+++ b/src/rpc/mining.cpp
@@ -888,7 +888,7 @@ static RPCMethod getblocktemplate()
// Update block
const node::CachedBlockTemplate cached{block_template_manager.GetNewOrCachedBlockTemplate()};
- const std::shared_ptr<const node::CBlockTemplate> block_template{cached.block_template};
+ const auto& block_template{cached.block_template};
const CBlockIndex* const pindexPrev{CHECK_NONFATAL(chainman.m_blockman.LookupBlockIndex(block_template->block.hashPrevBlock))};
CBlockHeader block_header{block_template->block};
cached already 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
| // Sample the mempool counter before building, so that a change made | ||
| // while CreateNewTemplate runs is seen as a change on the next call | ||
| cache.transactions_updated = mempool.GetTransactionsUpdated(); | ||
| cache.time_start = Now<NodeSeconds>(); |
There was a problem hiding this comment.
Could we use MockableSteadyClock here, since we only care about how much time has passed since the last build? NodeClock follows system time, so a possible backward clock adjustment could delay a mempool triggered rebuild?
There was a problem hiding this comment.
Thanks! A steady clock makes sense for measuring the rebuild interval. I’d leave the switch for a follow-up because mining_prioritisetransaction.py uses setmocktime to age the cached template. Updating that test would expand the scope of this PR.
Replace the function-local statics in getblocktemplate with a CachedBlockTemplate struct and a GetNewOrCachedBlockTemplate() helper, both local to rpc/mining.cpp. The cache is still process-wide, but it is now GUARDED_BY(::cs_main), so its synchronization is checked. GetNewOrCachedBlockTemplate() keeps the existing rules: the template is rebuilt when the tip changes, or when the mempool changed and the cached template is more than 5 seconds old. A failed rebuild leaves the cached template unset so that the next call tries again. This prepares for moving the cache into BlockTemplateManager in the next commit. While the code is still next to the original, it also: - Drops the static CBlockIndex pointer. pindexPrev is looked up from the template's hashPrevBlock, so it cannot outlive the ChainstateManager that owns it. - Reads the active chain tip inside GetNewOrCachedBlockTemplate() and compares it with the template's hashPrevBlock, so the cache cannot pair a template with a tip it does not build on. The caller no longer needs to re-read the tip after longpolling. - Builds the longpollid from hashPrevBlock, so it always names the block the template builds on. - Replaces the deprecated GetTime() with the equivalent Now<NodeSeconds>(). - Names the 5 second rebuild interval GBT_TEMPLATE_REBUILD_INTERVAL.
Move CachedBlockTemplate, GBT_TEMPLATE_REBUILD_INTERVAL and GetNewOrCachedBlockTemplate() from rpc/mining.cpp into BlockTemplateManager. The file-scope cache becomes a member that is still guarded by cs_main, and the interval becomes a public static member. The longpolling code reads the cached mempool counter through the new GetCachedTransactionsUpdated(). The cache now lives as long as the node context instead of the process. Apart from the member accesses and declarations, this is a move. It can be reviewed with: git show --color-moved=dimmed-zebra --color-moved-ws=allow-indentation-change
Check that GetNewOrCachedBlockTemplate() reuses the cached template until the tip changes, or until the mempool changes and the template is more than 5 seconds old, and that GetCachedTransactionsUpdated() reports the mempool counter sampled for the last build. Also check that a failed rebuild leaves the cache without a template, so that the next call retries without waiting for the 5 seconds to pass. Check that a replacement manager starts with an empty cache and builds its own template on the same tip with the same mempool. Co-authored-by: Enoch Azariah <[email protected]>
b7a6cf4 to
00a62a2
Compare
|
CI errors are unrelated |
|
@enochaz Following up on the 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! |

Follow-up to #35675. This addresses the
getblocktemplatepart of the "Remove remaining global states" TODO in #33758, as suggested in #35675 (review).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.