Skip to content

mining: add TxCollection to bandwidth-efficiently validate external block templates - #35671

Open
Sjors wants to merge 7 commits into
bitcoin:masterfrom
Sjors:2026/03/collect-txs
Open

Sjors wants to merge 7 commits into
bitcoin:masterfrom
Sjors:2026/03/collect-txs

Conversation

@Sjors

@Sjors Sjors commented Jul 6, 2026 •

Copy link
Copy Markdown
Member

The Stratum v2 spec defines a Job Declarator Server (JDS), whose job it is to approve custom miner templates. Since #34020 it can use getTransactionsByWitnessID() to request transactions from the node, instead of maintaining its own mempool mirror (see stratum-mining/sv2-apps#911), and then request any missing transactions from the miner.

The new TxCollection interface introduced by this PR optimizes this further. We build and validate the block template ourselves now, based on the requested transaction list and our own mempool, so known transactions don't need to cross the IPC boundary. This also fits the draft spec for JDS custom job validation through a Template Provider.

The following flow is demonstrated in stratum-mining/sv2-apps#599:

  1. Miner generates a template, e.g. using our createNewBlock() IPC method
  2. They send the list of Wtxids to the pool's JDS
  3. JDS calls Mining::collectTxs() (this PR) with that Wtxid list
  4. We check the list against our mempool and hold a CTransactionRef for each match
  5. The JDS queries unknownTxPos() to learn what's missing from the collection
  6. The JDS requests the fully serialized missing transactions from the miner (using native Stratum v2 messages)
  7. JDS calls addMissingTxs() which completes the collection
  8. JDS calls makeTemplate() which reconstructs the block and validates it, optionally with the coinbase it intends to use (e.g. to check the reward amount); a node-generated dummy is used otherwise. The JDS needs the check to succeed, may relay the BIP-22 failure reason to the miner.
  9. It returns a BlockTemplate which works as if we generated the template ourselves, but with methods like waitNext() disabled. The JDS can call submitSolution() (the sv2 spec allows for redundant block reconstruction by both the miner node and the JDS).

If this sounds very similar to compact block relay: it is! In fact, it would be easy to expand the above methods to take transaction short ids instead of Wtxid. That may be useful for the p2pool revival project, which needs a way to validate and relay weak blocks as compact blocks. The p2pool client software would need to (trivially) verify the PoW, but could use the TxCollection interface to reconstruct and verify the block content. That said, the SRI JDS implementation is much further along and likely to be the first consumer of this.

Commits:

  • ipc: add TxCollection scaffold - step 3 and 4
  • mining: add TxCollection unknownTxPos - step 5
  • mining: add TxCollection addMissingTxs - step 7
  • mining: add coinbase transaction helper - we need a dummy coinbase to verify the block, so extract a helper from BlockAssembler::CreateNewBlock()
  • mining: assemble block templates from TxCollection - step 8, node implementation
  • ipc: expose TxCollection template creation - step 8 and 9, including restrictions on externally generated templates
  • mining: allow TxCollection templates to use a supplied coinbase - optional coinbase in step 8

Potential followups:

@Sjors

Sjors commented Jul 6, 2026

Copy link
Copy Markdown
Member Author

@plebhash it would be very useful to have a (very) rough JDS draft that uses this interface, to see if it actually gets rid of the mirror mempool.

@DrahtBot

DrahtBot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

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.

Type Reviewers
Concept ACK ismaelsadeeq, pablomartin4btc, enochaz, jeanpablojp, plebhash

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:

  • #36922 (mining: use a steady clock for the getblocktemplate rebuild interval by w0xlt)
  • #36918 (Witness stacks in serialized form (optimization follow-ups) by sipa)
  • #36909 (kernel: add btck_witness_stack_get_items by pzafonte)
  • #36895 (Keep witness stacks in serialized form in CScriptWitness by sipa)
  • #36844 (iwyu: Fix warnings in more modules in src/ and treat them as errors by hebasto)
  • #36525 (mining: add Block interface, fix template data race by Sjors)
  • #36356 (mining: move getblocktemplate cache into BlockTemplateManager by w0xlt)
  • #36114 (wallet: harden external signer psbt processing, revamp mock 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.

LLM Linter (✨ experimental)

Possible places where named args for integral literals may be used (e.g. func(x, /*named_arg=*/0) in C++, and func(x, named_arg=0) in Python):

  • src/test/tx_collection_tests.cpp: CreateValidMempoolTransaction(m_coinbase_txns[0], 0, 1, coinbaseKey, ...)

2026-12-01 14:45:03

@DrahtBot

DrahtBot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/28818181619/job/85462853775
LLM reason (✨ experimental): CI failed because IWYU reported/required include fixes (modified files) and intentionally exited non-zero.

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.

@ismaelsadeeq

Copy link
Copy Markdown
Member

Concept ACK

The JDS queries unknownTxPos() to learn what's missing in our mempool

This could be collapsed to the response "JDS calls TxCollection::collectTxs() (this PR) with that Wtxid list" to reduce the round trip?

@Sjors
Sjors force-pushed the 2026/03/collect-txs branch from cf3aea1 to 8106852 Compare July 7, 2026 10:49
@Sjors

Sjors commented Jul 7, 2026 •

Copy link
Copy Markdown
Member Author

I added an optional coinbase argument to makeTemplate(). Based on my draft JDS implementation stratum-mining/sv2-apps#599 this does appear useful, e.g. for checking the reward amount. We still generate a dummy if no coinbase transaction is provided.

@ismaelsadeeq collectTxs() is the constructor so it needs to return an interface. I don't think it can return both the TxCollection interface and the list of missing transactions. But clients can chain requests (not sure if we've fully implemented the on the libmultiprocess side).

I can also imagine a (slight) benefit in clients being able to call unknownTxPos() multiple times, e.g. maybe in a future upgrade we could have the node request missing transactions from peers - not sure how useful that is though.

Sjors added a commit to Sjors/sv2-apps that referenced this pull request Jul 7, 2026
Transactions supplied through ProvideMissingTransactions.Success are
typically ones the JDS node will never learn over P2P (prioritized or
out-of-band transactions that don't meet its mempool policy). Without
a cache, every downstream declaring a template with such a transaction
-- and every retry -- pays its own ProvideMissingTransactions round.

Remember them in a bounded (32 MB), least-recently-used cache keyed by
wtxid, consulted only after unknownTxPos reports a transaction missing.
Unlike the retired mempool mirror this involves no background
synchronization and is never the source of truth: Bitcoin Core decides
what is missing, and the cache merely supplies it without asking the
client again. The wtxid key commits to the full serialized transaction,
so one downstream cannot misrepresent a transaction requested by
another; the worst a malicious downstream can do is churn the cache,
which degrades to today's behavior. Confirmed transactions stop being
looked up and age out on their own.

Bitcoin Core itself remembering TxCollection-provided transactions
(which would additionally improve relay and compact-block propagation
of the solved block) is a possible future replacement; see the
discussion in bitcoin/bitcoin#35671.

The new bitcoin_core_ipc_jdp_io scenario asserts that a transaction
provided once is remembered: a second downstream declaring it succeeds
without a missing-transactions round. It runs against all backends,
since the v30.x/v31.x mirror already behaves this way (previously
untested). The test-harness wallet helpers build a witness-free
transaction from an explicitly selected legacy coinbase output so the
minimal test coinbase needs no witness commitment, and mine funding
blocks in batches to stay under the RPC client timeout when several
test nodes mine concurrently.
@Sjors
Sjors force-pushed the 2026/03/collect-txs branch from 8106852 to 9bb89df Compare July 8, 2026 06:38
@Sjors

Sjors commented Jul 8, 2026

Copy link
Copy Markdown
Member Author

Rebased after #34020:

  • first test commit no longer needed
  • bumped collectTxs() to @10

Sjors added a commit to Sjors/bitcoin-capnp-types that referenced this pull request Jul 8, 2026
Sjors added a commit to Sjors/sv2-apps that referenced this pull request Jul 8, 2026
Point bitcoin_capnp_types_v32 at Sjors/bitcoin-capnp-types
2026/07/tx-collection (2140-dev/bitcoin-capnp-types#29), which adds the
capnp bindings for the TxCollection interface introduced by
bitcoin/bitcoin#35671.

Revert to the 2140-dev repository (or a crates.io release) once that PR
is merged.
Sjors added a commit to Sjors/sv2-apps that referenced this pull request Jul 8, 2026
The v32 integration test harness previously fell back to a hardcoded
local build path. Since the TxCollection work depends on a Bitcoin Core
build of bitcoin/bitcoin#35671, require the BITCOIN_CORE_V32_BINARY
environment variable instead and explain how to produce the binary.

Remove once an official Bitcoin Core release ships TxCollection and
v32 follows the standard release-binary download flow.
Sjors added a commit to Sjors/sv2-apps that referenced this pull request Jul 8, 2026
Instead of stubbing the v32 binary, build Bitcoin Core from the
bitcoin/bitcoin#35671 (TxCollection) PR branch in the Integration
Tests workflow, with ccache to keep warm-cache runs fast. This follows
the approach used by 2140-dev/bitcoin-capnp-types#29.

Remove once an official Bitcoin Core release ships TxCollection.
Sjors added a commit to Sjors/sv2-apps that referenced this pull request Jul 8, 2026
Bitcoin Core's TxCollection interface (bitcoin/bitcoin#35671) lets the
JDS validate an external block template directly against the node's
mempool, so the v32.x JDP backend no longer needs to keep an optimistic
local mempool mirror in sync via a waitNext monitor loop. This removes
the mirror, the monitor task, the startup createNewBlock call, and the
force-refresh retry logic, along with their staleness races (stratum-mining#268).

DeclareMiningJob validation now:
1. fetches the current tip via getTip
2. calls collectTxs with the declared wtxids
3. completes the collection via addMissingTxs when the client provided
   missing transactions (ProvideMissingTransactions.Success)
4. asks unknownTxPos which transactions are still unknown and, if any,
   responds with MissingTransactions
5. calls makeTemplate with the declared coinbase (zeroed extranonce,
   which no contextual check depends on), so Bitcoin Core reconstructs
   and fully validates the block including the coinbase (BIP34 height,
   output value, sigops, weight, witness commitment) and returns a
   BlockTemplate

The Success response parameters (prev_hash, nbits, min_ntime) come
from the validated template's header (getBlockHeader) and the full
transaction list from getBlock, preserving the response contract with
jd-server for SetCustomMiningJob validation and PushSolution block
reconstruction. The collection and template are destroyed once the
response is assembled.

Stale-tip classification compares the tip before and after validation,
plus a JDS-side check of the declared BIP34 height against the
expected next height so a stale job is reported as stale-chain-tip
rather than the generic invalid-job that bad-cb-height would map to.

Behavioral notes:
- readiness now waits for IBD to finish by polling
  isInitialBlockDownload instead of relying on createNewBlock blocking
  during IBD.
- a future optimization could retain the BlockTemplate and use its
  submitSolution method for PushSolution instead of reconstructing the
  full block in jd-server, which would also remove txdata from the
  Success response.
Sjors added a commit to Sjors/sv2-apps that referenced this pull request Jul 8, 2026
Transactions supplied through ProvideMissingTransactions.Success are
typically ones the JDS node will never learn over P2P (prioritized or
out-of-band transactions that don't meet its mempool policy). Without
a cache, every downstream declaring a template with such a transaction
-- and every retry -- pays its own ProvideMissingTransactions round.

Remember them in a bounded (32 MB), least-recently-used cache keyed by
wtxid, consulted only after unknownTxPos reports a transaction missing.
Unlike the retired mempool mirror this involves no background
synchronization and is never the source of truth: Bitcoin Core decides
what is missing, and the cache merely supplies it without asking the
client again. The wtxid key commits to the full serialized transaction,
so one downstream cannot misrepresent a transaction requested by
another; the worst a malicious downstream can do is churn the cache,
which degrades to today's behavior. Confirmed transactions stop being
looked up and age out on their own.

Bitcoin Core itself remembering TxCollection-provided transactions
(which would additionally improve relay and compact-block propagation
of the solved block) is a possible future replacement; see the
discussion in bitcoin/bitcoin#35671.

The new bitcoin_core_ipc_jdp_io scenario asserts that a transaction
provided once is remembered: a second downstream declaring it succeeds
without a missing-transactions round. It runs against all backends,
since the v30.x/v31.x mirror already behaves this way (previously
untested). The test-harness wallet helpers build a witness-free
transaction from an explicitly selected legacy coinbase output so the
minimal test coinbase needs no witness commitment, and mine funding
blocks in batches to stay under the RPC client timeout when several
test nodes mine concurrently.
@Sjors
Sjors force-pushed the 2026/03/collect-txs branch from de11d8e to 306ce7e Compare November 12, 2026 14:03
@Sjors

Sjors commented Nov 12, 2026

Copy link
Copy Markdown
Member Author

Trivial rebase after #36807.

average-gary added a commit to average-gary/rbitcoin that referenced this pull request Nov 17, 2026
`ProposeTemplate.Success` is `{request_id, template_id, prev_hash, fees}`;
`fees` is the sum of the fees of the declared transactions as
`ChainHub::check_block_proposal` computed it. This reverses 7f202e6's
field removal.

Only the validating node can derive the total: the fee of each
transaction is its inputs minus its outputs, which needs the UTXO set,
and the node computes it anyway for `bad-cb-amount`. Without it the Pool
has only the value the coinbase claims, which that check makes a lower
bound on the real total, not the total itself. Bitcoin Core's IPC does
not expose it today (`checkBlock` returns only reason, debug and result;
a `TxCollection.makeTemplate` template throws on `getTxFees`); that gap
is raised on bitcoin/bitcoin#35671 rather than designed around.

Red was E0560/E0609 (no field `fees`) on the round trip and
`expect_job_success`. Draft §2, §4.3, §6 and §7.1, Plan D (D4, D10) and
the changelog fragment say the field is returned.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@Sjors
Sjors force-pushed the 2026/03/collect-txs branch from 306ce7e to fa826de Compare November 18, 2026 15:15
@Sjors

Sjors commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

Rebased after #36451.

average-gary added a commit to average-gary/rbitcoin that referenced this pull request Nov 21, 2026
`ProposeTemplate.Success` is `{request_id, template_id, prev_hash, fees}`;
`fees` is the sum of the fees of the declared transactions as
`ChainHub::check_block_proposal` computed it. This reverses 7f202e6's
field removal.

Only the validating node can derive the total: the fee of each
transaction is its inputs minus its outputs, which needs the UTXO set,
and the node computes it anyway for `bad-cb-amount`. Without it the Pool
has only the value the coinbase claims, which that check makes a lower
bound on the real total, not the total itself. Bitcoin Core's IPC does
not expose it today (`checkBlock` returns only reason, debug and result;
a `TxCollection.makeTemplate` template throws on `getTxFees`); that gap
is raised on bitcoin/bitcoin#35671 rather than designed around.

Red was E0560/E0609 (no field `fees`) on the round trip and
`expect_job_success`. Draft §2, §4.3, §6 and §7.1, Plan D (D4, D10) and
the changelog fragment say the field is returned.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
average-gary added a commit to average-gary/rbitcoin that referenced this pull request Nov 30, 2026
`ProposeTemplate.Success` is `{request_id, template_id, prev_hash, fees}`;
`fees` is the sum of the fees of the declared transactions as
`ChainHub::check_block_proposal` computed it. This reverses 7f202e6's
field removal.

Only the validating node can derive the total: the fee of each
transaction is its inputs minus its outputs, which needs the UTXO set,
and the node computes it anyway for `bad-cb-amount`. Without it the Pool
has only the value the coinbase claims, which that check makes a lower
bound on the real total, not the total itself. Bitcoin Core's IPC does
not expose it today (`checkBlock` returns only reason, debug and result;
a `TxCollection.makeTemplate` template throws on `getTxFees`); that gap
is raised on bitcoin/bitcoin#35671 rather than designed around.

Red was E0560/E0609 (no field `fees`) on the round trip and
`expect_job_success`. Draft §2, §4.3, §6 and §7.1, Plan D (D4, D10) and
the changelog fragment say the field is returned.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Sjors and others added 7 commits December 1, 2026 15:35
Add node::TxCollection to retain references to requested transactions
found in the mempool. Later commits add methods to identify and supply
missing transactions.

BlockTemplateManager creates each collection. TxCollectionImpl owns it
and implements interfaces::TxCollection for mining clients.
Now that the collection can be mutated after construction, guard the
collected transactions with a mutex: IPC clients may call TxCollection
methods concurrently from different threads.
Move the coinbase construction out of CreateNewBlock() into a reusable
BlockAssembler::CreateCoinbaseTx() helper, so a later commit can build a
coinbase when assembling a template from externally collected
transactions.

Derive the height from pindexPrev so callers do not need to run
CreateNewBlock() to initialize the assembler's height.

This does not change behavior. Review with --color-moved=dimmed-zebra.

Co-authored-by: Enoch Azariah <[email protected]>
Add node::TxCollection::MakeTemplate() to assemble collected transactions
in their requested order on the active tip. Validate with a dummy coinbase
paying only the subsidy, using TestBlockValidity() with proof-of-work and
merkle-root checks disabled.

Add unit coverage for missing transactions, tip checks, transaction order,
successful assembly, and rejection of transactions already mined.
Expose makeTemplate() through the mining interface and IPC. Return a
BlockTemplate holding the block assembled by node::TxCollection.

Externally generated templates do not provide fee, sigop, or coinbase
construction metadata. Reject the corresponding getters, as well as
waitNext() and interruptWait(), which manage node-generated templates.

Exercise error propagation and the collect, complete, and submit workflow
through IPC, including submission of the same solution to both nodes.
Add an optional coinbase argument to makeTemplate(). When provided, retain
it in the template and validate the block with it. Otherwise, continue to
use a node-generated dummy coinbase.

Test that the supplied coinbase is preserved and that validation rejects
an excessive payout or a mismatched witness commitment.
@Sjors
Sjors force-pushed the 2026/03/collect-txs branch from fa826de to 5094a52 Compare December 1, 2026 14:44
@Sjors

Sjors commented Dec 1, 2026 •

Copy link
Copy Markdown
Member Author

@DrahtBot

DrahtBot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/46670896379/job/142725496969
LLM reason (✨ experimental): intermittent_network: apt-get install failed because Ubuntu package repositories repeatedly returned 503s and connection errors while fetching dependencies.

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.

  • Intermittent network issues can occur; re-run CI for now, and report the issue if they keep happening.

  • A functional or integration test failure may be intermittent or unrelated to this pull request.
    If no dedicated issue thread exists, create a new one to track it.

Leave a comment here, if you need help tracking down a confusing failure.

@DrahtBot

DrahtBot commented Dec 2, 2026

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.

10 participants