Follow-up to #35675. This addresses the getblocktemplate part of the "Remove remaining global states" TODO in #33758, as suggested in #35675#pullrequestreview-5299625960.
getblocktemplate reuses 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:
- live as long as the process, so the cached
CBlockIndex*can outlive itsChainstateManager(as in unit tests); - rely on
cs_mainbeing held, which nothing checks; - can't be unit tested.
This PR moves the cache into BlockTemplateManager, in three commits:
- rpc: refactors the statics in place into a
CachedBlockTemplatestruct and aGetNewOrCachedBlockTemplate()helper,GUARDED_BY(::cs_main). The template'shashPrevBlockreplaces the cachedCBlockIndex*, and the 5 seconds becomesGBT_TEMPLATE_REBUILD_INTERVAL. - refactor: moves them into
BlockTemplateManager. It's easiest to review withgit show --color-moved=dimmed-zebra --color-moved-ws=allow-indentation-change. - test: adds a unit test for each rebuild rule and for the retry after a failed build.
No behavior change is intended, and only getblocktemplate uses the cache. It uses cs_main rather than its own mutex, since the RPC already holds it and building a template takes it anyway.