Skip to content

node: add block template manager and track waitNext fee inflow - #35581

Draft
ismaelsadeeq wants to merge 27 commits into
bitcoin:masterfrom
ismaelsadeeq:07-2026-block-template-man
Draft

ismaelsadeeq wants to merge 27 commits into
bitcoin:masterfrom
ismaelsadeeq:07-2026-block-template-man

Conversation

@ismaelsadeeq

Copy link
Copy Markdown
Member

Motivation

The mining interface and rpc helpers (WaitAndCreateNewBlock and friends) are free functions scattered across src/node/miner.cpp, and every caller has to pass ChainstateManager and KernelNotifications into them, which is verbose. SubmitBlock spins up a short-lived CValidationInterface subscriber on every call just to read back the block validation state. This PR adds a BlockTemplateManager that holds that state and exposes those helpers as methods, so callers don't have to thread chainman/notifications (or a throwaway subscriber) around.

It also removes a redundant pattern in waitNext. Currently, to decide whether mempool fee inflow rose enough to be worth a new template, waitNext locks cs_main and assembles a full block template every tick just to sum its fees and compare. After cluster mempool see https://delvingbitcoin.org/t/determining-blocktemplate-fee-increase-using-fee-rate-diagram/2052, we shouldn't have to build a whole block template to answer that question. This PR uses the #34803 mempool notifications to record the previous template state and track the inflow above the lowest included chunk, and only assembles and returns a new template once that inflow is above the threshold.

I added a fuzz harness and unit tests for the manager. The fuzz test already caught a bug in the miner where it skips legitimate transactions due to an incorrect block chunk size limit check #35580.

Changes

  • Populate the tx refs in the fee rate diagrams
  • Cache fee rate diagrams as chunks in ChangeSet and add SnapshotDiagrams
  • Add a MempoolUpdated notification that returns the before and after diagrams
  • Track the selected chunk information after each mempool update
  • Add fee-inflow staleness detection per template
  • Introduce a BlockTemplateManager wrapper around BlockAssembler that holds state and
    creates templates, and move the free functions (mining args, SubmitBlock, GetTip,
    WaitTipChanged, CooldownIfHeadersAhead, WaitAndCreateNewBlock) onto it as methods
  • Use the tracked inflow in waitNext instead of rebuilding a template each tick
  • Route in-process RPC and test template creation through BlockTemplateManager instead
    of the IPC Mining interface, which also drops the per-access block copies the IPC
    accessors (getBlock) forced
  • Add a fuzz test and unit tests

There are now two entry points for template creation. Mining clients go through the IPC
Mining interface and get tracked templates, while in-process RPC and tests call BlockTemplateManager directly and get untracked ones. This is deliberate: one-shot RPC templates don't need staleness tracking, and it also avoids process-static RPC caches owning BlockTemplateImpl objects whose destructor reaches back into NodeContext at shutdown.

50% of the code addition here are tests ~1090 lines

@DrahtBot

DrahtBot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

Code Coverage & Benchmarks

For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/35581.

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
Concept ACK w0xlt, pablomartin4btc

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:

  • #36322 (init: fee estimates can lag behind the chain after restart by l0rinc)
  • #36182 (fees: return block_policy fee rate estimate when mempool_policy is not ready by ismaelsadeeq)
  • #36156 (mining: include chunks that exactly fill block limits by l0rinc)
  • #36091 (test: Add debug output to common tested types by rustaceanrob)
  • #36074 (scripted-diff: [test] Add util/check.h includes for assertions by maflcko)
  • #36015 (txorphanage: bound orphan memory by storing transactions serialized by brunoerg)
  • #35671 (mining: add TxCollection to bandwidth-efficiently validate external block templates by Sjors)
  • #33922 (mining: add getMemoryLoad() and track template non-mempool memory footprint by Sjors)

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.

@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/27947406418/job/82695559978
LLM reason (✨ experimental): CI failed because the fuzz target (src/test/fuzz/blocktemplatemanager.cpp) would not compile: error: unknown type name 'SteadyClockContext'.

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.

@w0xlt

w0xlt commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

@ismaelsadeeq
ismaelsadeeq force-pushed the 07-2026-block-template-man branch from e03f222 to 28c9934 Compare June 23, 2026 10:25
@ismaelsadeeq
ismaelsadeeq force-pushed the 07-2026-block-template-man branch from 28c9934 to 8c73017 Compare June 24, 2026 09:46
@Sjors

Sjors commented Jun 25, 2026

Copy link
Copy Markdown
Member

It would be nice to have a PR focussed on the BlockTemplateManager:

  • 08181220b6 node: introduce block template manager
  • 8a4363ce6e test: add block template manager fuzz test
  • 595acb3762 interfaces: create block template via block template manager
  • cbc15a02e2 node: move mining_args to block template manager
  • f7f496d8dc miner: move SubmitBlock into BlockTemplateManager
  • 9099f6d875 node: move tip and wait helpers into BlockTemplateManager
  • dcbd4dbeb6 rpc, test: build block templates via BlockTemplateManager

I should be able to build #33922 / Sjors#120 on top of that.

The waitNext() cluster mempool enhancement would be a natural followup.

Add MemPoolChunk and MemPoolChunksUpdate structs to
kernel/mempool_entry.h and MakeMemPoolChunks helper to txmempool.cpp
for converting TxGraph::Chunk vectors into MemPoolChunk vectors.

Each removal path now captures the before/after fee rate diagram chunks
and fires MempoolUpdated so subscribers can observe every mempool change.

This signal allows subscribers to observe mempool fee rate diagram
changes in an asynchronous way without holding the mempool lock.

This changes the order of operations in removeForBlock: all block
transactions in the mempool are now removed before conflict
removals.

In blockencodings_tests, SyncWithValidationInterfaceQueue() drains the
async MempoolUpdated signal queue before LOCK2(cs_main, pool.cs).
The LOCK2 moves after the sync to avoid deadlock.
Replace `m_package_feerates` with `m_template_chunks`, which records
each selected chunk's `FeePerWeight` feerate, unadjusted weight, sigops
cost, and the witness IDs of the transactions selected in that chunk.

This gives block templates enough information to describe both the
selection order and the transaction group selected at each step.
Index template chunks by hash and feerate to update
snapshots without sorting them after each mempool addition.
Register BlockTemplateManager for validation callbacks
and keep tracked snapshots synchronized with mempool and
chain-tip changes.
Track template fee inflow and report staleness once the fee improvement
reaches the requested threshold. The fee improvement is the lower-bound
difference between the current tracked chunk fees and the original
template fees.
Use BlockTemplateManager snapshot tracking to
decide when waitNext should return a replacement
template due to fee inflow.

This avoids rebuilding full templates on every wait
tick just to compare fees. Tracked snapshots are cleaned
up by BlockTemplateImpl destruction, so an original template
can remain alive and call waitNext again after a replacement is returned.
@DrahtBot

Copy link
Copy Markdown
Contributor

🐙 This pull request conflicts with the target branch and needs rebase.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants