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

Open
Sjors wants to merge 7 commits from 2026/03/collect-txs into master AGit
Sjors commented 2026-07-06 19:36:53 +00:00 (Migrated from github.com)

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 https://github.com/stratum-mining/sv2-apps/pull/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 https://github.com/stratum-mining/sv2-apps/pull/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:

The Stratum v2 spec defines a [Job Declarator Server](https://stratumprotocol.org/specification/06-job-declaration-protocol) (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 https://github.com/stratum-mining/sv2-apps/pull/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](https://github.com/stratum-mining/sv2-spec/discussions/239) for JDS custom job validation through a Template Provider. The following flow is demonstrated in https://github.com/stratum-mining/sv2-apps/pull/599: 1. Miner generates a template, e.g. using our `createNewBlock()` IPC method 2. They send the list of `Wtxid`s 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](https://www.vinteum.org/blog/reviving-p2pool-welcoming-johnny-santos-as-a-vinteum-grantee), 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](https://github.com/stratum-mining/sv2-apps/issues?q=is%3Aissue%20state%3Aopen%20JDS) 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: - https://github.com/Sjors/bitcoin/pull/122 - expose total fees for externally generated templates, building on #36525 - have `addMissingTxs()` (optionally) insert favorable transactions into our mempool - add a data structure to store transactions that don't meet our mempool threshold (so `TxCollection` can grab them, instead of needing another round trip)
Sjors commented 2026-07-06 19:37:44 +00:00 (Migrated from github.com)

@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.

@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 commented 2026-07-06 19:37:48 +00:00 (Migrated from github.com)

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

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/35671 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/35671.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/35671#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | Concept ACK | [ismaelsadeeq](https://github.com/bitcoin/bitcoin/pull/35671#issuecomment-4902377507), [pablomartin4btc](https://github.com/bitcoin/bitcoin/pull/35671#pullrequestreview-4769906047), [enochaz](https://github.com/bitcoin/bitcoin/pull/35671#pullrequestreview-4907232495), [jeanpablojp](https://github.com/bitcoin/bitcoin/pull/35671#pullrequestreview-5125552680), [plebhash](https://github.com/bitcoin/bitcoin/pull/35671#issuecomment-6672451090) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#36922](https://github.com/bitcoin/bitcoin/pull/36922) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36922.svg"></sub> (mining: use a steady clock for the getblocktemplate rebuild interval by w0xlt) * [#36918](https://github.com/bitcoin/bitcoin/pull/36918) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36918.svg"></sub> (Witness stacks in serialized form (optimization follow-ups) by sipa) * [#36909](https://github.com/bitcoin/bitcoin/pull/36909) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36909.svg"></sub> (kernel: add btck_witness_stack_get_items by pzafonte) * [#36895](https://github.com/bitcoin/bitcoin/pull/36895) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36895.svg"></sub> (Keep witness stacks in serialized form in CScriptWitness by sipa) * [#36844](https://github.com/bitcoin/bitcoin/pull/36844) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36844.svg"></sub> (iwyu: Fix warnings in more modules in `src/` and treat them as errors by hebasto) * [#36525](https://github.com/bitcoin/bitcoin/pull/36525) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36525.svg"></sub> (mining: add Block interface, fix template data race by Sjors) * [#36356](https://github.com/bitcoin/bitcoin/pull/36356) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36356.svg"></sub> (mining: move getblocktemplate cache into BlockTemplateManager by w0xlt) * [#36114](https://github.com/bitcoin/bitcoin/pull/36114) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36114.svg"></sub> (wallet: harden external signer psbt processing, revamp mock by Sjors) * [#33922](https://github.com/bitcoin/bitcoin/pull/33922) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/33922.svg"></sub> (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. <!--5faf32d7da4f0f540f40219e4f7537a3--> ### 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, ...)` <sup>2026-12-01 14:45:03</sup>
DrahtBot commented 2026-07-06 19:51:09 +00:00 (Migrated from github.com)

🚧 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.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `iwyu`: https://github.com/bitcoin/bitcoin/actions/runs/28818181619/job/85462853775</sub> <sub>LLM reason (✨ experimental): CI failed because IWYU reported/required include fixes (modified files) and intentionally exited non-zero.</sub> <details><summary>Hints</summary> 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. </details>
ismaelsadeeq commented 2026-07-07 09:41:38 +00:00 (Migrated from github.com)

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?

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 commented 2026-07-07 10:49:32 +00:00 (Migrated from github.com)

I added an optional coinbase argument to makeTemplate(). Based on my draft JDS implementation https://github.com/stratum-mining/sv2-apps/pull/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.

I added an optional `coinbase` argument to `makeTemplate()`. Based on my draft JDS implementation https://github.com/stratum-mining/sv2-apps/pull/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](https://capnproto.org/rpc.html) (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.
DrahtBot commented 2026-07-08 00:00:32 +00:00 (Migrated from github.com)

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

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
Sjors commented 2026-07-08 06:41:09 +00:00 (Migrated from github.com)

Rebased after https://github.com/bitcoin/bitcoin/pull/34020:

  • first test commit no longer needed
  • bumped collectTxs() to @10
Rebased after https://github.com/bitcoin/bitcoin/pull/34020: - first test commit no longer needed - bumped `collectTxs()` to `@10`
ViniciusCestarii commented 2026-07-09 18:45:43 +00:00 (Migrated from github.com)

But clients can chain requests (not sure if we've fully implemented the on the libmultiprocess side).

Capnp pipelining works for any client hitting the RPC socket, regardless of libmultiprocess, because it's a protocol-level feature the server doesn't need to implement. So the client (JDS) just needs to pipeline requests and it will work.

(The caveat only applies to Bitcoin Core's own libmultiprocess generated C++ client code, which currently blocks per call in clientInvoke and doesn't exploit pipelining internally. But since this interface is expected to be consumed by external clients this doens't apply)

> But clients [can chain requests](https://capnproto.org/rpc.html) (not sure if we've fully implemented the on the libmultiprocess side). Capnp pipelining works for any client hitting the RPC socket, regardless of libmultiprocess, because it's a protocol-level feature the server doesn't need to implement. So the client (JDS) just needs to pipeline requests and it will work. (The caveat only applies to Bitcoin Core's own libmultiprocess generated C++ client code, which currently blocks per call in clientInvoke and doesn't exploit pipelining internally. But since this interface is expected to be consumed by external clients this doens't apply)
ViniciusCestarii (Migrated from github.com) reviewed 2026-07-09 21:13:21 +00:00
ViniciusCestarii (Migrated from github.com) commented 2026-07-09 21:02:23 +00:00

In "mining: add TxCollection to bandwidth-efficiently validate external block templates" 9bb89df02fc3dbcb870b36d4a339986089ea40e2

not blocking/design question: would it be worth splitting into two capnp interfaces instead of throwing on methods: an ExternalBlockTemplate with just getBlockHeader/getBlock/getCoinbaseMerklePath/submitSolution and BlockTemplate extends(ExternalBlockTemplate) adding getTxFees/getTxSigops/getCoinbaseTx/waitNext/interruptWait? Then TxCollection::makeTemplate() returns the narrower type and the disallowed methods aren't callable, rather than compiling and throwing on call.

I took the liberty to prototype this here: https://github.com/ViniciusCestarii/bitcoin/compare/9bb89df02fc3dbcb870b36d4a339986089ea40e2...pr-35671-new-interface

In "mining: add TxCollection to bandwidth-efficiently validate external block templates" 9bb89df02fc3dbcb870b36d4a339986089ea40e2 not blocking/design question: would it be worth splitting into two capnp interfaces instead of throwing on methods: an ExternalBlockTemplate with just getBlockHeader/getBlock/getCoinbaseMerklePath/submitSolution and BlockTemplate extends(ExternalBlockTemplate) adding getTxFees/getTxSigops/getCoinbaseTx/waitNext/interruptWait? Then TxCollection::makeTemplate() returns the narrower type and the disallowed methods aren't callable, rather than compiling and throwing on call. I took the liberty to prototype this here: https://github.com/ViniciusCestarii/bitcoin/compare/9bb89df02fc3dbcb870b36d4a339986089ea40e2...pr-35671-new-interface
ViniciusCestarii (Migrated from github.com) commented 2026-07-09 21:06:34 +00:00

In "ipc: add TxCollection scaffold" 19bae00aa17be0964e28529ecc348a94522204af

nit: commit states that it adds CollectedTxs class but there's no CollectedTxs class

In "ipc: add TxCollection scaffold" 19bae00aa17be0964e28529ecc348a94522204af nit: commit states that it adds CollectedTxs class but there's no CollectedTxs class
ViniciusCestarii (Migrated from github.com) commented 2026-07-08 14:29:06 +00:00

In "mining: add TxCollection addMissingTxs" ee1c43e3ceb21fdf38340801221e9fa42c8e6993

AddMissingTxs is order-dependent, a bad entry aborts the loop at that point, so [valid, invalid] keeps valid but [invalid, valid] doesn't. Is this intentional? Correct me if I am wrong but validate-then-apply seems to be a safer approach.

In "mining: add TxCollection addMissingTxs" ee1c43e3ceb21fdf38340801221e9fa42c8e6993 AddMissingTxs is order-dependent, a bad entry aborts the loop at that point, so [valid, invalid] keeps valid but [invalid, valid] doesn't. Is this intentional? Correct me if I am wrong but validate-then-apply seems to be a safer approach.
ViniciusCestarii (Migrated from github.com) commented 2026-07-09 19:27:27 +00:00

In "mining: add TxCollection addMissingTxs" ee1c43e3ceb21fdf38340801221e9fa42c8e6993

nit: there could be a test case for "unexpected null transaction" when calling addMissingTxs with a null tx

In "mining: add TxCollection addMissingTxs" ee1c43e3ceb21fdf38340801221e9fa42c8e6993 nit: there could be a test case for "unexpected null transaction" when calling addMissingTxs with a null tx
Sjors commented 2026-07-10 11:50:10 +00:00 (Migrated from github.com)

@ViniciusCestarii wrote:

But since this interface is expected to be consumed by external clients this doens't apply

Interesting, so we don't need to change anything in libmultiprocess on the server (node) side?

I'll take your inline comments into account on the next rebase. As I mentioned in the PR description, the code is still a bit rough.

@ViniciusCestarii wrote: > But since this interface is expected to be consumed by external clients this doens't apply Interesting, so we don't need to change anything in libmultiprocess on the server (node) side? I'll take your inline comments into account on the next rebase. As I mentioned in the PR description, the code is still a bit rough.
ViniciusCestarii commented 2026-07-13 19:48:02 +00:00 (Migrated from github.com)

Interesting, so we don't need to change anything in libmultiprocess on the server (node) side?

Yes, pipelining is already possible: I have made this client demo that chains calls, including the new interface TxCollection, in a single round trip with only one .wait() at the end.

OBS: Only interface fields (and struct fields that transitively lead to one) can be actually pipelined. (in the example I only pipelined interfaces), any other value like int, bool, enum, text, data, list, etc cannot be pipelined.

> Interesting, so we don't need to change anything in libmultiprocess on the server (node) side? Yes, pipelining is already possible: I have made [this client demo](https://github.com/ViniciusCestarii/bitcoin-ipc-demo/blob/mining/src/ipc.cpp) that chains calls, including the new interface TxCollection, in a single round trip with only one .wait() at the end. OBS: [Only interface fields (and struct fields that transitively lead to one) can be actually pipelined](https://github.com/capnproto/capnproto/blob/v2/c%2B%2B/src/capnp/dynamic.c%2B%2B#L396C15-L396C84). (in the example I only pipelined interfaces), any other value like int, bool, enum, text, data, list, etc cannot be pipelined.
gmaxwell commented 2026-07-14 22:03:12 +00:00 (Migrated from github.com)

compact blocks uses a differential index not primarily for efficiency (though it does save quite a bit when there are many misses) but so that the wire format is safe by construction against an attack that applies the same large transaction over and over again (e.g. if index 5 is some giant txn, you request 5,5,5,5,5,5...) and overflows a buffer or OOMs an implementation explicitly constructs the block and without having to have expensive duplication checks.

compact blocks uses a differential index not primarily for efficiency (though it does save quite a bit when there are many misses) but so that the wire format is safe by construction against an attack that applies the same large transaction over and over again (e.g. if index 5 is some giant txn, you request 5,5,5,5,5,5...) and overflows a buffer or OOMs an implementation explicitly constructs the block and without having to have expensive duplication checks.
Sjors commented 2026-07-15 08:59:14 +00:00 (Migrated from github.com)

@gmaxwell the Mining IPC client1 is expected to run on the same machine, so unknownTxPos() and addMissingTxs() are not designed for bandwidth efficiency.

We also (currently) more or less trust the IPC client. It needs to deal with any hardening against its clients itself.2

Using absolute positions matches the Stratum v2 spec3, so there's probably no point in hardening it at the node level. But cc @TheBlueMatt as to why it didn't use a differential index?

If we later expand TxCollection to support compact blocks, we would probably add new unknownTxDifferentialPos() and addMissingTxsForCompactBlock() methods. Those should then match the p2p pattern you describe.


  1. for TxCollection it's the Job Declarator Server: https://github.com/stratum-mining/sv2-apps/tree/main/pool-apps/jd-server ↩︎

  2. not having to deal with another network protocol and its DoS risks was one of the motivations for not supporting Stratum v2 p2p messages directly, see discussion that starts at: https://github.com/bitcoin/bitcoin/pull/29432#pullrequestreview-2132699185. That said, over time we could gradually harden the IPC to where the Stratum v2 client can be a very thin wrapper. ↩︎

  3. ProvideMissingTransactions and ProvideMissingTransactions.Success ↩︎

@gmaxwell the Mining IPC client[^0] is expected to run on the same machine, so `unknownTxPos()` and `addMissingTxs()` are not designed for bandwidth efficiency. We also (currently) more or less trust the IPC client. It needs to deal with any hardening against _its_ clients itself.[^1] Using absolute positions matches the Stratum v2 spec[^2], so there's probably no point in hardening it at the node level. But cc @TheBlueMatt as to why it didn't use a differential index? If we later expand `TxCollection` to support compact blocks, we would probably add new `unknownTxDifferentialPos()` and `addMissingTxsForCompactBlock()` methods. Those should then match the p2p pattern you describe. [^0]: for `TxCollection` it's the Job Declarator Server: https://github.com/stratum-mining/sv2-apps/tree/main/pool-apps/jd-server [^1]: not having to deal with another network protocol and its DoS risks was one of the motivations for not supporting Stratum v2 p2p messages directly, see discussion that starts at: https://github.com/bitcoin/bitcoin/pull/29432#pullrequestreview-2132699185. That said, over time we could gradually harden the IPC to where the Stratum v2 client can be a very thin wrapper. [^2]: [ProvideMissingTransactions](https://stratumprotocol.org/specification/06-job-declaration-protocol/#647-providemissingtransactions-server-client) and [ProvideMissingTransactions.Success](https://stratumprotocol.org/specification/06-job-declaration-protocol/#648-providemissingtransactionssuccess-client-server)
Sjors (Migrated from github.com) reviewed 2026-07-23 18:31:48 +00:00
Sjors (Migrated from github.com) commented 2026-07-23 18:31:48 +00:00

Two interfaces might require a bunch of code duplication on the Rust client side though? Also several disabled methods could be made to work with external templates, if someone actually needs them.

Two interfaces might require a bunch of code duplication on the Rust client side though? Also several disabled methods _could_ be made to work with external templates, if someone actually needs them.
Sjors (Migrated from github.com) reviewed 2026-07-23 18:32:23 +00:00
Sjors (Migrated from github.com) commented 2026-07-23 18:32:23 +00:00

Added.

Added.
Sjors (Migrated from github.com) reviewed 2026-07-23 18:32:28 +00:00
Sjors (Migrated from github.com) commented 2026-07-23 18:32:28 +00:00

Fixed commit message.

Fixed commit message.
Sjors commented 2026-07-23 18:42:00 +00:00 (Migrated from github.com)

Rebased after and made consistent with #34672. Addressed @ViniciusCestarii's inline comments https://github.com/bitcoin/bitcoin/pull/35671#pullrequestreview-4655098156. Ready for review.

Rebased after and made consistent with #34672. Addressed @ViniciusCestarii's inline comments https://github.com/bitcoin/bitcoin/pull/35671#pullrequestreview-4655098156. Ready for review.
Sjors commented 2026-07-23 19:08:34 +00:00 (Migrated from github.com)

Used a lambda to avoid MakeTemplateInternal, reduced intra-commit churn.

Used a lambda to avoid `MakeTemplateInternal`, reduced intra-commit churn.
ViniciusCestarii (Migrated from github.com) reviewed 2026-07-23 19:54:54 +00:00
ViniciusCestarii (Migrated from github.com) commented 2026-07-23 19:54:54 +00:00

On the duplication concern: extends() gives upcasting, so shared logic that only needs the common subset doesn't need duplicating. Where branching is needed, it's because the type system is now correctly rejecting a call that would've thrown at runtime anyway and that's the point of the split, not an added cost.

On the disabled methods: if they could be implemented for external templates later, they could just as well be added to the split interfaces later too. The split just removes what's currently unclear to a client consuming the interface (methods that appear callable but are guaranteed to throw).

Just my two cents. I'm fine either way

On the duplication concern: `extends()` gives upcasting, so shared logic that only needs the common subset doesn't need duplicating. Where branching is needed, it's because the type system is now correctly rejecting a call that would've thrown at runtime anyway and that's the point of the split, not an added cost. On the disabled methods: if they could be implemented for external templates later, they could just as well be added to the split interfaces later too. The split just removes what's currently unclear to a client consuming the interface (methods that appear callable but are guaranteed to throw). Just my two cents. I'm fine either way
pablomartin4btc (Migrated from github.com) reviewed 2026-07-24 03:49:09 +00:00
pablomartin4btc (Migrated from github.com) left a comment

Concept ACK

Left a few comments.

Concept ACK Left a few comments.
pablomartin4btc (Migrated from github.com) commented 2026-07-24 03:36:52 +00:00

nit: does the m_mutex need to be locked in the constructor? — the object isn't shared until after construction returns, so no concurrent access is possible yet.

nit: does the `m_mutex` need to be locked in the constructor? — the object isn't shared until after construction returns, so no concurrent access is possible yet.
pablomartin4btc (Migrated from github.com) commented 2026-07-24 03:31:01 +00:00

Should the size of wtxids be checked before the loop (e.g. perhaps using existing constants — MAX_BLOCK_WEIGHT / MIN_TRANSACTION_WEIGHT)?

Should the size of `wtxids` be checked before the loop (e.g. perhaps using existing constants — `MAX_BLOCK_WEIGHT / MIN_TRANSACTION_WEIGHT`)?
pablomartin4btc (Migrated from github.com) commented 2026-07-24 03:39:50 +00:00

nit: these invariants are guaranteed by the constructor and the any_of check above — I think Assert would be stronger than Assume here to catch future regressions.

nit: these invariants are guaranteed by the constructor and the `any_of` check above — I think `Assert` would be stronger than `Assume` here to catch future regressions.
Sjors (Migrated from github.com) reviewed 2026-07-24 11:24:56 +00:00
Sjors (Migrated from github.com) commented 2026-07-24 11:24:56 +00:00

Added (similar check as in merkleblock.cpp), along with a test.

I added a similar guard to addMissingTxs(), but for it to be actually useful, we'd need to modify libmultiprocess to enforce things like a maximum param size.

Added (similar check as in `merkleblock.cpp`), along with a test. I added a similar guard to `addMissingTxs()`, but for it to be actually useful, we'd need to modify libmultiprocess to enforce things like a maximum param size.
Sjors (Migrated from github.com) reviewed 2026-07-24 11:24:59 +00:00
Sjors (Migrated from github.com) commented 2026-07-24 11:24:59 +00:00

Dropped

Dropped
Sjors (Migrated from github.com) reviewed 2026-07-24 11:25:03 +00:00
Sjors (Migrated from github.com) commented 2026-07-24 11:25:03 +00:00

More importantly it->second below would crash, so Assert is appropriate. Fixed.

More importantly `it->second` below would crash, so `Assert` is appropriate. Fixed.
Sjors commented 2026-07-24 11:25:05 +00:00 (Migrated from github.com)

Addressed @pablomartin4btc's feedback. This PR grew interface_ipc_mining.py to over 1000 lines and the new tests add significant runtime. So I add interface_ipc_mining_tx_collection.py.

Addressed @pablomartin4btc's feedback. This PR grew `interface_ipc_mining.py` to over 1000 lines and the new tests add significant runtime. So I add `interface_ipc_mining_tx_collection.py`.
DrahtBot commented 2026-07-29 20:45:45 +00:00 (Migrated from github.com)

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

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
enirox001 (Migrated from github.com) reviewed 2026-08-11 14:20:56 +00:00
enirox001 (Migrated from github.com) left a comment

Concept ACK

I do not have much knowledge of compact block relays and would need to look into them further, but this looks like a good improvement.

I did some benchmarking to see how the new interface affects JDS validation. I have not taken a close look at the code yet. I used AI to help put the benchmark code together, then ran and checked the results myself using a local regtest node. Do tell me if i got something wrong here

The benchmark uses sendrawtransaction only as a controlled way to insert a transaction into the JDS node’s mempool. It is not part of the normal JDS flow, the timing therefore measures from local transaction submission to JDS approval, not the complete miner to JDS flow.

For the same workload of 1 to 20 transactions, i got these results

jds approach samples average time from sendrawtransaction to jds approval
v31 mempool mirror 20 995.455 ms
TxCollection 120 across 6 runs 4.446 ms

I also tried a 300 sample TxCollection run where the transaction list grew from 1 to 300 transactions:

part measured average
sendrawtransaction 3.625 ms
collectTxs() and makeTemplate() 3.953 ms
Total 7.578 ms

The benchmark creates and signs each transaction before starting the timer. For transactions already in the mempool, timing starts before sendrawtransaction and stops when the JDS approves the declaration. The missing transaction benchmark measures detecting the missing transaction, supplying it, and validating the completed template.

the benchmark harnesses can be found here

Concept ACK I do not have much knowledge of compact block relays and would need to look into them further, but this looks like a good improvement. I did some benchmarking to see how the new interface affects JDS validation. I have not taken a close look at the code yet. I used AI to help put the benchmark code together, then ran and checked the results myself using a local regtest node. Do tell me if i got something wrong here The benchmark uses `sendrawtransaction` only as a controlled way to insert a transaction into the JDS node’s mempool. It is not part of the normal JDS flow, the timing therefore measures from local transaction submission to JDS approval, not the complete miner to JDS flow. For the same workload of 1 to 20 transactions, i got these results | jds approach | samples | average time from `sendrawtransaction` to jds approval | | --- | ---: | ---: | | v31 mempool mirror | 20 | 995.455 ms | | `TxCollection` | 120 across 6 runs | 4.446 ms | I also tried a 300 sample `TxCollection` run where the transaction list grew from 1 to 300 transactions: | part measured | average | | --- | ---: | | `sendrawtransaction` | 3.625 ms | | `collectTxs()` and `makeTemplate()` | 3.953 ms | | Total | 7.578 ms | The benchmark creates and signs each transaction before starting the timer. For transactions already in the mempool, timing starts before `sendrawtransaction` and stops when the JDS approves the declaration. The missing transaction benchmark measures detecting the missing transaction, supplying it, and validating the completed template. the benchmark harnesses can be found here - [current jds mempool approach](https://github.com/enirox001/sv2-apps/tree/benchmark/jdp-mempool-mirror-baseline) - [TxCollection implementation](https://github.com/enirox001/sv2-apps/tree/benchmark/jdp-txcollection)
enirox001 (Migrated from github.com) reviewed 2026-08-12 16:46:22 +00:00
enirox001 (Migrated from github.com) left a comment

Code Review d0c20776abe1ad14073c3328ef8c64434b0f92c7

I initially intended to benchmark this approach against the existing JDS mempool mirror, but I no longer think that is particularly relevant for evaluating the concept, since the main benefit is architectural rather than necessarily a raw speed improvement.

Reusing Bitcoin Core's mempool avoids duplicating transaction storage and continuous mirror synchronization, transfers only transactions the node is missing, and lets external templates be reconstructed and validated using existing validation logic. I plan to continue reviewing the implementation.

left some questions and nits

Code Review d0c20776abe1ad14073c3328ef8c64434b0f92c7 I initially intended to benchmark this approach against the existing JDS mempool mirror, but I no longer think that is particularly relevant for evaluating the concept, since the main benefit is architectural rather than necessarily a raw speed improvement. Reusing Bitcoin Core's mempool avoids duplicating transaction storage and continuous mirror synchronization, transfers only transactions the node is missing, and lets external templates be reconstructed and validated using existing validation logic. I plan to continue reviewing the implementation. left some questions and nits
enirox001 (Migrated from github.com) commented 2026-08-12 16:22:33 +00:00

In commit https://github.com/bitcoin/bitcoin/pull/35671/changes/d0c20776abe1ad14073c3328ef8c64434b0f92c7 mining: restrict externally generated templates

waitNext is disabled for external templates, but interruptWait is still allowed? Is there a reason for this?

I believe the relationship is that while waitNext executes on a thread, interruptWait can be called to stop the wait. For external clients, waitNext will throw, so even though interruptWait can execute, it seems redundant; a call to it would just set the flag to true and wake unrelated waiters unnecessarily

In commit https://github.com/bitcoin/bitcoin/pull/35671/changes/d0c20776abe1ad14073c3328ef8c64434b0f92c7 _mining: restrict externally generated templates_ `waitNext` is disabled for external templates, but `interruptWait` is still allowed? Is there a reason for this? I believe the relationship is that while `waitNext` executes on a thread, `interruptWait` can be called to stop the wait. For external clients, `waitNext` will throw, so even though `interruptWait` can execute, it seems redundant; a call to it would just set the flag to true and wake unrelated waiters unnecessarily
enirox001 (Migrated from github.com) commented 2026-08-12 09:01:10 +00:00

In commit https://github.com/bitcoin/bitcoin/pull/35671/changes/02ed6eafc42e73cc0637bc3c681ee208487dd2ab ipc: add TxCollection scaffold

nit:

I am a bit confused with the naming here, I initially read m_collected_txs as a transaction container. I assume the name refers to the transactions held internally in m_transactions, since most operations inspect or update them.

But i think this would be better named m_tx_collection, as this would make it read less as a container and more as an object

In commit https://github.com/bitcoin/bitcoin/pull/35671/changes/02ed6eafc42e73cc0637bc3c681ee208487dd2ab _ipc: add TxCollection scaffold_ nit: I am a bit confused with the naming here, I initially read `m_collected_txs` as a transaction container. I assume the name refers to the transactions held internally in `m_transactions`, since most operations inspect or update them. But i think this would be better named `m_tx_collection`, as this would make it read less as a container and more as an object
enirox001 (Migrated from github.com) commented 2026-08-12 10:02:24 +00:00

In commit https://github.com/bitcoin/bitcoin/pull/35671/changes/02ed6eafc42e73cc0637bc3c681ee208487dd2ab ipc: add TxCollection scaffold

Supposing a client passes [A, B, C, A] wtxids. The second A would be rejected as the same transaction is requested twice. The current code here would check and recheck this invalid transaction while the mempool is locked.

I think the constructor could check for duplicates before locking the mempool? As the duplicate is entirely visible from the input. A possible implementation could be

index 5d7440fd90..950d1abe9c 100644
--- a/src/node/miner.cpp
+++ b/src/node/miner.cpp
@@ -66,6 +66,15 @@ TxCollection::TxCollection(std::vector<Wtxid> wtxids, const NodeContext& node)
     if (m_wtxids.size() > MAX_BLOCK_WEIGHT / MIN_TRANSACTION_WEIGHT) {
         throw std::runtime_error(strprintf("too many wtxids (%d > %d)", m_wtxids.size(), MAX_BLOCK_WEIGHT / MIN_TRANSACTION_WEIGHT));
     }
+
+    std::unordered_set<Wtxid, SaltedWtxidHasher> seen;
+
+    for (const auto& wtxid : m_wtxids) {
+        if (!seen.insert(wtxid).second) {
+            throw(std::runtime_error("duplicate wtxid"));
+        }
+    }
+
     CTxMemPool& mempool{*Assert(m_node.mempool)};
     LOCK(mempool.cs);
     for (const auto& wtxid : m_wtxids) {
In commit https://github.com/bitcoin/bitcoin/pull/35671/changes/02ed6eafc42e73cc0637bc3c681ee208487dd2ab _ipc: add TxCollection scaffold_ Supposing a client passes `[A, B, C, A]` wtxids. The second `A` would be rejected as the same transaction is requested twice. The current code here would check and recheck this invalid transaction while the mempool is locked. I think the constructor could check for duplicates before locking the mempool? As the duplicate is entirely visible from the input. A possible implementation could be ```diff --git a/src/node/miner.cpp b/src/node/miner.cpp index 5d7440fd90..950d1abe9c 100644 --- a/src/node/miner.cpp +++ b/src/node/miner.cpp @@ -66,6 +66,15 @@ TxCollection::TxCollection(std::vector<Wtxid> wtxids, const NodeContext& node) if (m_wtxids.size() > MAX_BLOCK_WEIGHT / MIN_TRANSACTION_WEIGHT) { throw std::runtime_error(strprintf("too many wtxids (%d > %d)", m_wtxids.size(), MAX_BLOCK_WEIGHT / MIN_TRANSACTION_WEIGHT)); } + + std::unordered_set<Wtxid, SaltedWtxidHasher> seen; + + for (const auto& wtxid : m_wtxids) { + if (!seen.insert(wtxid).second) { + throw(std::runtime_error("duplicate wtxid")); + } + } + CTxMemPool& mempool{*Assert(m_node.mempool)}; LOCK(mempool.cs); for (const auto& wtxid : m_wtxids) { ```
enirox001 (Migrated from github.com) commented 2026-08-12 10:25:40 +00:00

In commit 02ed6ea ipc: add TxCollection scaffold

Here, the entries are inserted into an unordered_map, this has internal storage that might need to be reallocated depending on the number of entries.

The check above this line helps keep it within the proper limit, but since the collection size is known, we could reserve it before acquiring the mempool lock to avoid the reallocating and rehashing while the mempool is locked

m_transactions.reserve(m_wtxids.size());
In commit 02ed6ea ipc: add TxCollection scaffold Here, the entries are inserted into an `unordered_map`, this has internal storage that might need to be reallocated depending on the number of entries. The check above this line helps keep it within the proper limit, but since the collection size is known, we could reserve it before acquiring the mempool lock to avoid the reallocating and rehashing while the mempool is locked ``` m_transactions.reserve(m_wtxids.size()); ```
enirox001 (Migrated from github.com) commented 2026-08-12 16:38:58 +00:00

In commit https://github.com/bitcoin/bitcoin/pull/35671/changes/f4d53d163615d09650375317faa617eaaf6a07dc mining: add TxCollection addMissingTxs

The transaction passed here can be much larger than the one rejected by the constructor for TxCollection. The check here is against the size, but it does not check the weight. So even though it can reject a million tiny transactions, it can accept 16666 large ones

This would be eventually rejected as oversized in makeTemplate when TestBlockValidity is called, but that is a bit too late.

A way to track the weight of the transactions currently stored in m_transactions and then calculate the weight when adding here could resolve the issue

In commit https://github.com/bitcoin/bitcoin/pull/35671/changes/f4d53d163615d09650375317faa617eaaf6a07dc _mining: add TxCollection addMissingTxs_ The transaction passed here can be much larger than the one rejected by the constructor for `TxCollection`. The check here is against the size, but it does not check the weight. So even though it can reject a million tiny transactions, it can accept 16666 large ones This would be eventually rejected as oversized in `makeTemplate` when `TestBlockValidity` is called, but that is a bit too late. A way to track the weight of the transactions currently stored in `m_transactions` and then calculate the weight when adding here could resolve the issue
enirox001 (Migrated from github.com) commented 2026-08-12 15:57:01 +00:00

In commit https://github.com/bitcoin/bitcoin/pull/35671/changes/a4a3db4577a43578951758406c01aa982452f9c5 mining: make TxCollection create a BlockTemplate

nit:
the commit follows the intended flow for creating a template without using CreateNewBlock but i do have a concern about the commit structure.

In this commit the usual template metadata such as vTxFees, vTxSigOpsCost, m_coinbase_tx are not populated. The next commit addresses this by marking the template as external and causing them to throw. But i think this makes this specific commit a bit incomplete.

Perhaps the sixth commit should be introduced before this one? or together in this commit?

In commit https://github.com/bitcoin/bitcoin/pull/35671/changes/a4a3db4577a43578951758406c01aa982452f9c5 _mining: make TxCollection create a BlockTemplate_ nit: the commit follows the intended flow for creating a template without using `CreateNewBlock` but i do have a concern about the commit structure. In this commit the usual template metadata such as `vTxFees`, `vTxSigOpsCost`, `m_coinbase_tx` are not populated. The next commit addresses this by marking the template as external and causing them to throw. But i think this makes this specific commit a bit incomplete. Perhaps the sixth commit should be introduced before this one? or together in this commit?
enirox001 (Migrated from github.com) commented 2026-08-12 16:03:35 +00:00

In commit a4a3db4 mining: make TxCollection create a BlockTemplate

nit:
It looks like m_mutex is held longer than necessary here? Could we limit its scope to checking completeness and copying the ordered m_transactions into a local vector?

The references remain valid after the lock is released, so block construction and TestBlockValidity would not need to hold the collection mutex. This would also mirror CreateNewBlock, which releases the mempool lock after selecting transactions and before final validation

This is a rough implementation of this

index 5d7440fd90..6f1b47423f 100644
--- a/src/node/miner.cpp
+++ b/src/node/miner.cpp
@@ -121,12 +121,23 @@ std::unique_ptr<CBlockTemplate> TxCollection::MakeTemplate(const uint256& prevha
     debug.clear();

     auto block_template{[&]() -> std::unique_ptr<CBlockTemplate> {
-        LOCK(m_mutex);
-        if (std::ranges::any_of(m_transactions, [](const auto& entry) { return !entry.second; })) {
-            reason = "missing-txs";
-            debug = "collected transaction(s) still missing";
-            return nullptr;
+        std::vector<CTransactionRef> transactions;
+        {
+            LOCK(m_mutex);
+            if (std::ranges::any_of(m_transactions, [](const auto& entry) { return !entry.second; })) {
+                reason = "missing-txs";
+                debug = "collected transaction(s) still missing";
+                return nullptr;
+            }
+            transactions.reserve(m_wtxids.size());
+            for (const auto& wtxid : m_wtxids) {
+                const auto it{m_transactions.find(wtxid)};
+                Assert(it != m_transactions.end());
+                Assert(it->second);
+                transactions.push_back(it->second);
+            }
         }
+
         ChainstateManager& chainman{*Assert(m_node.chainman)};
         LOCK(chainman.GetMutex());
         const auto current_tip{GetTip(chainman)};
@@ -157,11 +168,8 @@ std::unique_ptr<CBlockTemplate> TxCollection::MakeTemplate(const uint256& prevha
         // transactions are added so the witness commitment is current.
         block.vtx.emplace_back();

-        for (const auto& wtxid : m_wtxids) {
-            const auto it{m_transactions.find(wtxid)};
-            Assert(it != m_transactions.end());
-            Assert(it->second);
-            block.vtx.push_back(it->second);
+        for (const auto& tx : transactions) {
+            block.vtx.push_back(tx);
         }

         if (coinbase) {
In commit a4a3db4 _mining: make TxCollection create a BlockTemplate_ nit: It looks like `m_mutex` is held longer than necessary here? Could we limit its scope to checking completeness and copying the ordered `m_transactions` into a local vector? The references remain valid after the lock is released, so block construction and `TestBlockValidity` would not need to hold the collection mutex. This would also mirror `CreateNewBlock`, which releases the mempool lock after selecting transactions and before final validation This is a rough implementation of this ```diff --git a/src/node/miner.cpp b/src/node/miner.cpp index 5d7440fd90..6f1b47423f 100644 --- a/src/node/miner.cpp +++ b/src/node/miner.cpp @@ -121,12 +121,23 @@ std::unique_ptr<CBlockTemplate> TxCollection::MakeTemplate(const uint256& prevha debug.clear(); auto block_template{[&]() -> std::unique_ptr<CBlockTemplate> { - LOCK(m_mutex); - if (std::ranges::any_of(m_transactions, [](const auto& entry) { return !entry.second; })) { - reason = "missing-txs"; - debug = "collected transaction(s) still missing"; - return nullptr; + std::vector<CTransactionRef> transactions; + { + LOCK(m_mutex); + if (std::ranges::any_of(m_transactions, [](const auto& entry) { return !entry.second; })) { + reason = "missing-txs"; + debug = "collected transaction(s) still missing"; + return nullptr; + } + transactions.reserve(m_wtxids.size()); + for (const auto& wtxid : m_wtxids) { + const auto it{m_transactions.find(wtxid)}; + Assert(it != m_transactions.end()); + Assert(it->second); + transactions.push_back(it->second); + } } + ChainstateManager& chainman{*Assert(m_node.chainman)}; LOCK(chainman.GetMutex()); const auto current_tip{GetTip(chainman)}; @@ -157,11 +168,8 @@ std::unique_ptr<CBlockTemplate> TxCollection::MakeTemplate(const uint256& prevha // transactions are added so the witness commitment is current. block.vtx.emplace_back(); - for (const auto& wtxid : m_wtxids) { - const auto it{m_transactions.find(wtxid)}; - Assert(it != m_transactions.end()); - Assert(it->second); - block.vtx.push_back(it->second); + for (const auto& tx : transactions) { + block.vtx.push_back(tx); } if (coinbase) { ```
enirox001 (Migrated from github.com) commented 2026-08-12 14:35:13 +00:00

In commit 02d8f43959 mining: add coinbase transaction helper

This updates the height since the block being created must have a height one greater than its previous block. The ordinary createNewBlock already sets this member, and so does this helper; it is harmless but redundant.

Seems it is needed here because in later commits this helper is called directly on a new BlockAssembler without first calling CreateNewBlock. In that situation, the member might not have been initialized

I think a cleaner approach to this helper would be to have it calculate its own height

const int height{pIndexPrev.nHeight + 1}

and then we use in the code

const CAmount block_reward{
      fees + GetBlockSubsidy(height, chainparams.GetConsensus())
  };

  coinbaseTx.vin[0].scriptSig = CScript() << height;
  coinbaseTx.nLockTime = static_cast<uint32_t>(height - 1);

The difference is that changing nHeight changes the BlockAssembler object even if it is not needer here, while this approach creates a value used only inside this helper. This makes this helper easier to reason about and safer to call independently

In commit 02d8f43959 _mining: add coinbase transaction helper_ This updates the height since the block being created must have a height one greater than its previous block. The ordinary `createNewBlock` already sets this member, and so does this helper; it is harmless but redundant. Seems it is needed here because in later commits this helper is called directly on a new `BlockAssembler` without first calling `CreateNewBlock`. In that situation, the member might not have been initialized I think a cleaner approach to this helper would be to have it calculate its own height ``` const int height{pIndexPrev.nHeight + 1} ``` and then we use in the code ``` const CAmount block_reward{ fees + GetBlockSubsidy(height, chainparams.GetConsensus()) }; coinbaseTx.vin[0].scriptSig = CScript() << height; coinbaseTx.nLockTime = static_cast<uint32_t>(height - 1); ``` The difference is that changing `nHeight` changes the `BlockAssembler` object even if it is not needer here, while this approach creates a value used only inside this helper. This makes this helper easier to reason about and safer to call independently
enirox001 (Migrated from github.com) commented 2026-08-12 14:09:37 +00:00

In commit https://github.com/bitcoin/bitcoin/pull/35671/changes/02d8f439592026975ca6adceb19222adf91976ff mining: add coinbase transaction helper

This method does more than create a basic coinbase transaction, as it also creates the witness commitment.

    m_chainstate.m_chainman.GenerateCoinbaseCommitment(block, &pindexPrev);

And since the witness commitment commits to all transactions in the block, adding a transaction after calling this method would make it outdated?

The current documentation here does not mention that all the transactions must be present before calling this so that this does not happen. An improvement could be

index 43dfa52fea..486534add7 100644
--- a/src/node/miner.h
+++ b/src/node/miner.h
@@ -90,6 +90,9 @@ public:
     /**
      * Create a coinbase transaction and insert it into block.vtx[0].
      *
+     * All non coinbase transactions must already be present so the generated
+     * witness commitment commits to the transaction set
+     *
      * @param[in,out] block       Block whose coinbase transaction is replaced.
      * @param[in]     pindexPrev  Previous block index. Used to derive the
      *                            coinbase height, subsidy, and commitment.
In commit https://github.com/bitcoin/bitcoin/pull/35671/changes/02d8f439592026975ca6adceb19222adf91976ff _mining: add coinbase transaction helper_ This method does more than create a basic coinbase transaction, as it also creates the witness commitment. ``` m_chainstate.m_chainman.GenerateCoinbaseCommitment(block, &pindexPrev); ``` And since the witness commitment commits to all transactions in the block, adding a transaction after calling this method would make it outdated? The current documentation here does not mention that all the transactions must be present before calling this so that this does not happen. An improvement could be ```diff --git a/src/node/miner.h b/src/node/miner.h index 43dfa52fea..486534add7 100644 --- a/src/node/miner.h +++ b/src/node/miner.h @@ -90,6 +90,9 @@ public: /** * Create a coinbase transaction and insert it into block.vtx[0]. * + * All non coinbase transactions must already be present so the generated + * witness commitment commits to the transaction set + * * @param[in,out] block Block whose coinbase transaction is replaced. * @param[in] pindexPrev Previous block index. Used to derive the * coinbase height, subsidy, and commitment. ```
enirox001 (Migrated from github.com) commented 2026-08-12 12:48:08 +00:00

In commit https://github.com/bitcoin/bitcoin/pull/35671/changes/e23f21b5cba0883e5d667321ffb0d5f7dabe87f0 mining: add TxCollection unknownTxPos

I think an improvement to this test would be adding a test to verify the mempool snapshot behavior. such that it tests that after the collection is constructed with a transaction in the mempool, if the transaction is removed from the mempool it does not report it as missing.

a rough implementation would look somehting like

index 83cc2a6462..ced11bbbe5 100755
--- a/test/functional/interface_ipc_mining_tx_collection.py
+++ b/test/functional/interface_ipc_mining_tx_collection.py
@@ -99,8 +99,31 @@ class IPCMiningTxCollectionTest(BitcoinTestFramework):
                         assert_equal(e.description, f"remote exception: std::exception: {method_name} is unavailable for externally generated templates")
                         assert_equal(e.type, "FAILED")

-            self.log.debug("Run the TxCollection workflow")
             remote_wallet.rescan_utxos()
+
+            self.log.debug("TxCollection should retain transactions after they leave the mempool")
+            snapshot_tx = remote_wallet.send_self_transfer(
+                from_node=remote_node,
+                fee_rate=10,
+                confirmed_only=True,
+            )
+            self.sync_mempools()
+            assert snapshot_tx["txid"] in node.getrawmempool()
+
+            async with AsyncExitStack() as snapshot_stack:
+                snapshot_collection = await mining_collect_txs(
+                    mining0,
+                    snapshot_stack,
+                    ctx0,
+                    [snapshot_tx["tx"].wtxid],
+                )
+                assert_equal(await tx_collection_unknown_pos(snapshot_collection, ctx0), [])
+
+                # collection should continue holding its CTransactionRef.
+                self.generate(remote_node, 1)
+                assert snapshot_tx["txid"] not in node.getrawmempool()
+                assert_equal(await tx_collection_unknown_pos(snapshot_collection, ctx0), [])
+
             self.log.debug("Create a transaction that is shared by both mempools before disconnecting")
             shared_tx = remote_wallet.send_self_transfer(
                 from_node=remote_node,
In commit https://github.com/bitcoin/bitcoin/pull/35671/changes/e23f21b5cba0883e5d667321ffb0d5f7dabe87f0 mining: add TxCollection unknownTxPos I think an improvement to this test would be adding a test to verify the mempool snapshot behavior. such that it tests that after the collection is constructed with a transaction in the mempool, if the transaction is removed from the mempool it does not report it as missing. a rough implementation would look somehting like ```diff --git a/test/functional/interface_ipc_mining_tx_collection.py b/test/functional/interface_ipc_mining_tx_collection.py index 83cc2a6462..ced11bbbe5 100755 --- a/test/functional/interface_ipc_mining_tx_collection.py +++ b/test/functional/interface_ipc_mining_tx_collection.py @@ -99,8 +99,31 @@ class IPCMiningTxCollectionTest(BitcoinTestFramework): assert_equal(e.description, f"remote exception: std::exception: {method_name} is unavailable for externally generated templates") assert_equal(e.type, "FAILED") - self.log.debug("Run the TxCollection workflow") remote_wallet.rescan_utxos() + + self.log.debug("TxCollection should retain transactions after they leave the mempool") + snapshot_tx = remote_wallet.send_self_transfer( + from_node=remote_node, + fee_rate=10, + confirmed_only=True, + ) + self.sync_mempools() + assert snapshot_tx["txid"] in node.getrawmempool() + + async with AsyncExitStack() as snapshot_stack: + snapshot_collection = await mining_collect_txs( + mining0, + snapshot_stack, + ctx0, + [snapshot_tx["tx"].wtxid], + ) + assert_equal(await tx_collection_unknown_pos(snapshot_collection, ctx0), []) + + # collection should continue holding its CTransactionRef. + self.generate(remote_node, 1) + assert snapshot_tx["txid"] not in node.getrawmempool() + assert_equal(await tx_collection_unknown_pos(snapshot_collection, ctx0), []) + self.log.debug("Create a transaction that is shared by both mempools before disconnecting") shared_tx = remote_wallet.send_self_transfer( from_node=remote_node, ```
Sjors (Migrated from github.com) reviewed 2026-08-20 10:25:47 +00:00
Sjors (Migrated from github.com) commented 2026-08-20 10:25:47 +00:00

I don't think we should take over too much work that TestBlockValidity() does for us. Duplicating consensus checks could introduce new bugs.

I don't think we should take over too much work that `TestBlockValidity()` does for us. Duplicating consensus checks could introduce new bugs.
Sjors (Migrated from github.com) reviewed 2026-08-20 10:36:34 +00:00
Sjors (Migrated from github.com) commented 2026-08-20 10:36:34 +00:00

Good catch, I probably missed this in a rebase (before I opened the PR).

Good catch, I probably missed this in a rebase (before I opened the PR).
Sjors (Migrated from github.com) reviewed 2026-08-20 10:36:36 +00:00
Sjors (Migrated from github.com) commented 2026-08-20 10:36:36 +00:00

Done

Done
Sjors (Migrated from github.com) reviewed 2026-08-20 10:36:38 +00:00
Sjors (Migrated from github.com) commented 2026-08-20 10:36:38 +00:00

I'd rather not grow the commit, and reversing them makes it hard to test. Going to leave this alone for now. The commits are bisect-safe.

I'd rather not grow the commit, and reversing them makes it hard to test. Going to leave this alone for now. The commits are bisect-safe.
Sjors (Migrated from github.com) reviewed 2026-08-20 10:36:39 +00:00
Sjors (Migrated from github.com) commented 2026-08-20 10:36:39 +00:00

Taken, and made it a const member function.

Taken, and made it a `const` member function.
Sjors (Migrated from github.com) reviewed 2026-08-20 10:36:42 +00:00
Sjors (Migrated from github.com) commented 2026-08-20 10:36:42 +00:00

Taken.

Taken.
Sjors (Migrated from github.com) reviewed 2026-08-20 10:36:44 +00:00
Sjors (Migrated from github.com) reviewed 2026-08-20 10:36:46 +00:00
Sjors (Migrated from github.com) commented 2026-08-20 10:36:46 +00:00

Done

Done
Sjors (Migrated from github.com) reviewed 2026-08-20 10:36:48 +00:00
Sjors (Migrated from github.com) commented 2026-08-20 10:36:48 +00:00

Done, checking duplicates first without a lock now.

Done, checking duplicates first without a lock now.
Sjors (Migrated from github.com) reviewed 2026-08-20 10:36:50 +00:00
Sjors (Migrated from github.com) commented 2026-08-20 10:36:50 +00:00

Renamed.

Renamed.
Sjors commented 2026-08-20 10:36:54 +00:00 (Migrated from github.com)

Rebased and addressed @enirox001's feedback.

Rebased and addressed @enirox001's feedback.
jeanpablojp (Migrated from github.com) reviewed 2026-09-06 14:07:06 +00:00
jeanpablojp (Migrated from github.com) left a comment

Concept ACK

Ran the new tests and the mining suite, and checked the coinbase commit against its parent.

A question about the reject reasons. makeTemplate() reports an ancestor prevhash as stale-prevblk, but Mining::checkBlock() reports that same case as inconclusive-not-best-prevblk, since it lands in TestBlockValidity(), which uses that reason for any prevhash other than the tip. Nothing in the tree used stale-prevblk before this PR. The make TxCollection create a BlockTemplate commit message says this mirrors the getblocktemplate proposal reasons, but the proposal goes out through that same call, unless I'm misreading it. Was that difference deliberate?

Concept ACK Ran the new tests and the mining suite, and checked the coinbase commit against its parent. A question about the reject reasons. `makeTemplate()` reports an ancestor prevhash as `stale-prevblk`, but `Mining::checkBlock()` reports that same case as `inconclusive-not-best-prevblk`, since it lands in `TestBlockValidity()`, which uses that reason for any prevhash other than the tip. Nothing in the tree used `stale-prevblk` before this PR. The `make TxCollection create a BlockTemplate` commit message says this mirrors the `getblocktemplate` proposal reasons, but the proposal goes out through that same call, unless I'm misreading it. Was that difference deliberate?
jeanpablojp (Migrated from github.com) commented 2026-09-06 14:07:07 +00:00

nit: for an externally generated template getCoinbaseTx() throws now, so there is nothing to compare against, and when the client passed a coinbase to makeTemplate() the one in vtx[0] is theirs rather than a dummy. Worth saying which coinbase this returns?

nit: for an externally generated template `getCoinbaseTx()` throws now, so there is nothing to compare against, and when the client passed a coinbase to `makeTemplate()` the one in `vtx[0]` is theirs rather than a dummy. Worth saying which coinbase this returns?
jeanpablojp (Migrated from github.com) commented 2026-09-06 14:07:06 +00:00

nit: the two methods above have @param[in] and @returns, and this one has neither. The constructor also throws when the list goes past MAX_BLOCK_WEIGHT / MIN_TRANSACTION_WEIGHT, and that one is left out, while addMissingTxs() documents all three of its cases.

nit: the two methods above have `@param[in]` and `@returns`, and this one has neither. The constructor also throws when the list goes past `MAX_BLOCK_WEIGHT / MIN_TRANSACTION_WEIGHT`, and that one is left out, while `addMissingTxs()` documents all three of its cases.
jeanpablojp (Migrated from github.com) commented 2026-09-06 14:07:06 +00:00

The amount case is covered, the witness commitment one isn't, and that's the one that pins which transactions the coinbase commits to. I flipped a bit of the commitment and it gives bad-witness-merkle-match. Would a case next to this one be worth it?

                )

                self.log.debug("makeTemplate() rejects a client-provided coinbase whose witness commitment does not match")
                bad_commitment_coinbase = deepcopy(remote_coinbase)
                for out in bad_commitment_coinbase.vout:
                    if out.scriptPubKey[:6] == bytes.fromhex("6a24aa21a9ed"):
                        spk = bytearray(out.scriptPubKey)
                        spk[-1] ^= 0x01
                        out.scriptPubKey = bytes(spk)
                await tx_collection_make_template(
                    tx_collection, stack, ctx0, remote_tip,
                    coinbase=bad_commitment_coinbase.serialize(),
                    reject_reason="bad-witness-merkle-match",
                )
The amount case is covered, the witness commitment one isn't, and that's the one that pins which transactions the coinbase commits to. I flipped a bit of the commitment and it gives `bad-witness-merkle-match`. Would a case next to this one be worth it? ```suggestion ) self.log.debug("makeTemplate() rejects a client-provided coinbase whose witness commitment does not match") bad_commitment_coinbase = deepcopy(remote_coinbase) for out in bad_commitment_coinbase.vout: if out.scriptPubKey[:6] == bytes.fromhex("6a24aa21a9ed"): spk = bytearray(out.scriptPubKey) spk[-1] ^= 0x01 out.scriptPubKey = bytes(spk) await tx_collection_make_template( tx_collection, stack, ctx0, remote_tip, coinbase=bad_commitment_coinbase.serialize(), reject_reason="bad-witness-merkle-match", ) ```
DrahtBot commented 2026-09-24 05:49:11 +00:00 (Migrated from github.com)

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

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
Sjors commented 2026-09-24 15:30:39 +00:00 (Migrated from github.com)

Rebased after #35675. The new BlockTemplateManager creates the collection, but it's still owned by the IPC client. I moved it to node/tx_collection.h.

Added unit tests while slightly reducing functional tests.

Also addressed @jeanpablojp's feedback: switched to inconclusive-not-best-prevblk (https://github.com/bitcoin/bitcoin/pull/35671#pullrequestreview-5125552680), add a check for bad-witness-merkle-match (https://github.com/bitcoin/bitcoin/pull/35671#discussion_r3944180465) and improved docs (other two inline comments).

I also ended up combining template creation and the external restrictions, since there was some discussion about the right sequence earlier. To keep the commit manageable, I split it in a different way.

I have a local branch with a fuzzer, but I prefer to leave that to a followup.

Rebased after #35675. The new `BlockTemplateManager` creates the collection, but it's still owned by the IPC client. I moved it to `node/tx_collection.h`. Added unit tests while slightly reducing functional tests. Also addressed @jeanpablojp's feedback: switched to `inconclusive-not-best-prevblk` (https://github.com/bitcoin/bitcoin/pull/35671#pullrequestreview-5125552680), add a check for `bad-witness-merkle-match` (https://github.com/bitcoin/bitcoin/pull/35671#discussion_r3944180465) and improved docs (other two inline comments). I also ended up combining template creation and the external restrictions, since there was some discussion about the right sequence earlier. To keep the commit manageable, I split it in a different way. I have a local branch with a fuzzer, but I prefer to leave that to a followup.
Sjors (Migrated from github.com) reviewed 2026-09-24 15:30:47 +00:00
Sjors (Migrated from github.com) commented 2026-09-24 15:30:47 +00:00

Done

Done
Sjors (Migrated from github.com) reviewed 2026-09-24 15:30:47 +00:00
Sjors (Migrated from github.com) commented 2026-09-24 15:30:47 +00:00

Added.

Added.
Sjors (Migrated from github.com) reviewed 2026-09-24 15:30:49 +00:00
Sjors (Migrated from github.com) commented 2026-09-24 15:30:49 +00:00

Added such a test.

Added such a test.
First-time contributor

2 additional verified findings in the Review report.

Earlier concerns neither republished nor resolved: 2 suggestions. See the Run archive linked from the Review report for their assessments.

🟠 Minor · External templates retain reconstruction-time nBits on submission

On minimum-difficulty test networks, cross-threshold reconstruction can give submitSolution() the wrong nBits and reject a valid redundant submission; no in-tree caller exercises this timing.

Location: src/node/tx_collection.cpp:175 (head).

🟠 Minor · TxCollection has no retained-transaction weight budget

A trusted IPC client can accumulate more than a block's weight in one TxCollection across addMissingTxs() calls; remote-miner exposure depends on the JDS's own byte budget.

Location: src/node/tx_collection.cpp:99 (head).

🔵 Suggestion · makeTemplate() leaves null-coinbase approval limits undocumented

A successful makeTemplate() call with a null coinbase validates the collected transactions with a subsidy-only dummy, not the coinbase the caller intends to mine.

Location: src/interfaces/mining.h:168 (head).

🔵 Suggestion · makeTemplate() omits the signet-verification exception

makeTemplate() always uses check_pow=false, which also skips signet challenge verification, but its API documentation lists only the proof-of-work and merkle-root exceptions.

Location: src/interfaces/mining.h:156 (head).

🔵 Suggestion · collectTxs() leaves the coinbase exclusion and index mapping implicit

The API does not say that collectTxs() excludes the coinbase or that unknownTxPos() indices refer to the supplied list rather than block.vtx.

Location: src/interfaces/mining.h:286 (head).

🔵 Suggestion · TxCollection tests lack a script-invalid transaction

The negative MakeTemplate() cases reject for non-script reasons, so the current TxCollection assertions could pass even if script authorization checks were skipped.

Location: src/test/tx_collection_tests.cpp:156 (head).

Review coverage was incomplete.


Reviewed: 5094a523f089 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:312ddb2095238aa2ca395a9cc39b05ab5a38a7177afbdb0d69098df9c3e0bef9:9a7f127b15c6116c267953d38288a9f17ec7c7bcd3a975fb71a2db8bfd974dbf --> <!-- ralph-base:2e5d7540a1da07a7e448f339d54cfb40a78dddbc --> <!-- ralph-head:5094a523f089af50aaf4ac41714959dc7e18c99e --> <!-- ralph-case:44df8fb59c2b7abd5bdc0009101f0c7189cde26e66a812a853ab24c116386190 --> [2 additional verified findings in the Review report](<https://review.fish.foo/report/35671-5094a523f089af50aaf4ac41714959dc7e18c99e-3397-8.html>). Earlier concerns neither republished nor resolved: 2 suggestions. See the Run archive linked from the Review report for their assessments. **🟠 Minor · External templates retain reconstruction-time `nBits` on submission** On minimum-difficulty test networks, cross-threshold reconstruction can give `submitSolution()` the wrong `nBits` and reject a valid redundant submission; no in-tree caller exercises this timing. Location: [`src/node/tx_collection.cpp:175`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/5094a523f089af50aaf4ac41714959dc7e18c99e/src/node/tx_collection.cpp#L175>) (head). **🟠 Minor · `TxCollection` has no retained-transaction weight budget** A trusted IPC client can accumulate more than a block's weight in one `TxCollection` across `addMissingTxs()` calls; remote-miner exposure depends on the JDS's own byte budget. Location: [`src/node/tx_collection.cpp:99`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/5094a523f089af50aaf4ac41714959dc7e18c99e/src/node/tx_collection.cpp#L99>) (head). **🔵 Suggestion · `makeTemplate()` leaves null-coinbase approval limits undocumented** A successful `makeTemplate()` call with a null `coinbase` validates the collected transactions with a subsidy-only dummy, not the coinbase the caller intends to mine. Location: [`src/interfaces/mining.h:168`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/5094a523f089af50aaf4ac41714959dc7e18c99e/src/interfaces/mining.h#L168>) (head). **🔵 Suggestion · `makeTemplate()` omits the signet-verification exception** `makeTemplate()` always uses `check_pow=false`, which also skips signet challenge verification, but its API documentation lists only the proof-of-work and merkle-root exceptions. Location: [`src/interfaces/mining.h:156`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/5094a523f089af50aaf4ac41714959dc7e18c99e/src/interfaces/mining.h#L156>) (head). **🔵 Suggestion · `collectTxs()` leaves the coinbase exclusion and index mapping implicit** The API does not say that `collectTxs()` excludes the coinbase or that `unknownTxPos()` indices refer to the supplied list rather than `block.vtx`. Location: [`src/interfaces/mining.h:286`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/5094a523f089af50aaf4ac41714959dc7e18c99e/src/interfaces/mining.h#L286>) (head). **🔵 Suggestion · `TxCollection` tests lack a script-invalid transaction** The negative `MakeTemplate()` cases reject for non-script reasons, so the current `TxCollection` assertions could pass even if script authorization checks were skipped. Location: [`src/test/tx_collection_tests.cpp:156`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/5094a523f089af50aaf4ac41714959dc7e18c99e/src/test/tx_collection_tests.cpp#L156>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`5094a523f089`](<https://git.fish.foo/bitcoin/bitcoin/commit/5094a523f089af50aaf4ac41714959dc7e18c99e>) · [Review report](<https://review.fish.foo/report/35671-5094a523f089af50aaf4ac41714959dc7e18c99e-3397-8.html>) · [Previous reports](<https://review.fish.foo/traces/35671/>) [permalink](<https://review.fish.foo/report/35671-5094a523f089af50aaf4ac41714959dc7e18c99e-3397-8.html>)
average-gary commented 2026-10-08 17:03:55 +00:00 (Migrated from github.com)

Coming from https://github.com/stratum-mining/sv2-spec/discussions/239, where a Job Declaration Server (JDS) validates an externally built template through a Template Provider (TP). On the Core-IPC side (sv2-tp #137) that maps onto collectTxs → addMissingTxs → makeTemplate → checkBlock-style validation, and the one value the TP then has to report that this interface doesn't expose is the block's fee total.

The node computes it during validation (nFees in ConnectBlock, needed for the bad-cb-amount check), and it is the only party that can: the JDS has the transactions but not the input values.

Either of these may work:

  • BlockTemplate::getTxFees() working on templates returned by makeTemplate() instead of throwing (per-tx fees are available in the same loop that produces nFees), or
  • a fees field in the checkBlock result (total only), which would also serve users of checkBlock on an assembled CBlock before TxCollection lands.

Disclaimer: Fable 5.1 assisted but human reviewed/edited.

Coming from https://github.com/stratum-mining/sv2-spec/discussions/239, where a Job Declaration Server (JDS) validates an externally built template through a Template Provider (TP). On the Core-IPC side (sv2-tp #137) that maps onto `collectTxs` → `addMissingTxs` → `makeTemplate` → `checkBlock`-style validation, and the one value the TP then has to report that this interface doesn't expose is the block's fee total. The node computes it during validation (`nFees` in `ConnectBlock`, needed for the `bad-cb-amount` check), and it is the only party that can: the JDS has the transactions but not the input values. Either of these may work: - `BlockTemplate::getTxFees()` working on templates returned by `makeTemplate()` instead of throwing (per-tx fees are available in the same loop that produces `nFees`), or - a `fees` field in the `checkBlock` result (total only), which would also serve users of `checkBlock` on an assembled `CBlock` before `TxCollection` lands. Disclaimer: Fable 5.1 assisted but human reviewed/edited.
Sjors commented 2026-10-13 07:42:28 +00:00 (Migrated from github.com)

@average-gary I might open a separate PR to refactor our mining code so that BlockTemplate::getTxFees() can work with external templates. Currently fee calculation is done as transactions are added to the template. Or to just add a total fees field.

@average-gary I might open a separate PR to refactor our mining code so that `BlockTemplate::getTxFees()` can work with external templates. Currently fee calculation is done as transactions are added to the template. Or to just add a total fees field.
DrahtBot commented 2026-10-14 08:20:07 +00:00 (Migrated from github.com)

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

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
Sjors commented 2026-10-14 09:40:13 +00:00 (Migrated from github.com)

Rebased after #36469.

I wrote:

Or to just add a total fees field.

#36525 introduces getTotalFees(), and an internal variable to track that. If it lands first, I'll take advantage of it in this PR, but otherwise I'll leave that a followup.

Rebased after #36469. I wrote: > Or to just add a total fees field. #36525 introduces `getTotalFees()`, and an internal variable to track that. If it lands first, I'll take advantage of it in this PR, but otherwise I'll leave that a followup.
plebhash commented 2026-10-14 14:16:31 +00:00 (Migrated from github.com)

@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.

apologies for the late reply @Sjors

I'm a bit confused though:

mempool mirror is going away via getTransactionsByWitnessID on v32 (https://github.com/stratum-mining/sv2-apps/pull/911), and my understanding is that TxCollection will only further optimize things (https://github.com/stratum-mining/sv2-apps/issues/609)

so I'm confused about this part:

to see if it actually gets rid of the mirror mempool.

> @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. apologies for the late reply @Sjors I'm a bit confused though: mempool mirror is going away via `getTransactionsByWitnessID` on v32 (https://github.com/stratum-mining/sv2-apps/pull/911), and my understanding is that `TxCollection` will only further optimize things (https://github.com/stratum-mining/sv2-apps/issues/609) so I'm confused about this part: > to see if it actually gets rid of the mirror mempool.
Sjors commented 2026-10-15 00:20:58 +00:00 (Migrated from github.com)

mempool mirror is going away via getTransactionsByWitnessID on v32

Indeed that comment is stale. I 'll updated the description to take v32 for granted, and also to reference the draft spec https://github.com/stratum-mining/sv2-spec/discussions/239.

So the remaining question is if there's anything missing to implement that draft spec / "further optimize things". Gary already brought up that it's useful to know the total fees.

> mempool mirror is going away via `getTransactionsByWitnessID` on v32 Indeed that comment is stale. I ~'ll~ updated the description to take v32 for granted, and also to reference the draft spec https://github.com/stratum-mining/sv2-spec/discussions/239. So the remaining question is if there's anything missing to implement that draft spec / "further optimize things". Gary already brought up that it's useful to know the total fees.
plebhash commented 2026-11-05 23:40:24 +00:00 (Migrated from github.com)

concept ACK here, and I would highly support aiming to get this merged for v33

#34020 allowed us to move away from a rather suboptimal implementation of SRI's Sv2 Job Declarator Server (JDS) based on a "mempool mirror" for v30/v31 (https://github.com/stratum-mining/sv2-apps/pull/911)

but we didn't foresee that looking the declared transactions up twice, before and after the ProvideMissingTransactions round-trip, is prone to races: anything that leaves the mempool in between (e.g. RBF, eviction) is missing on the second lookup, even though the miner was never asked for it

on mainnet that hits about ~1% of round-trips on an idle JDS and ~6% on a loaded one (https://github.com/stratum-mining/sv2-apps/issues/975, https://github.com/stratum-mining/sv2-apps/issues/982).

the current workaround is to ask the miner again, a bounded number of times, and every round fetches the whole declared list over IPC again (which is rather inefficient)

a TxCollection that holds the matched transactions across the round-trip removes the race: at most one round-trip per declaration, and known transactions never cross the IPC boundary

concept ACK here, and I would highly support aiming to get this merged for v33 #34020 allowed us to move away from a rather suboptimal implementation of SRI's Sv2 Job Declarator Server (JDS) based on a "mempool mirror" for v30/v31 (https://github.com/stratum-mining/sv2-apps/pull/911) but we didn't foresee that looking the declared transactions up twice, before and after the `ProvideMissingTransactions` round-trip, is prone to races: anything that leaves the mempool in between (e.g. RBF, eviction) is missing on the second lookup, even though the miner was never asked for it on mainnet that hits about ~1% of round-trips on an idle JDS and ~6% on a loaded one (https://github.com/stratum-mining/sv2-apps/issues/975, https://github.com/stratum-mining/sv2-apps/issues/982). the current workaround is to ask the miner again, a bounded number of times, and every round fetches the whole declared list over IPC again (which is rather inefficient) a `TxCollection` that holds the matched transactions across the round-trip removes the race: at most one round-trip per declaration, and known transactions never cross the IPC boundary
DrahtBot commented 2026-11-12 12:01:18 +00:00 (Migrated from github.com)

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

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
Sjors commented 2026-11-12 14:03:43 +00:00 (Migrated from github.com)

Trivial rebase after #36807.

Trivial rebase after #36807.
DrahtBot commented 2026-11-16 17:23:08 +00:00 (Migrated from github.com)

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

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
Sjors commented 2026-11-18 15:15:24 +00:00 (Migrated from github.com)

Rebased after #36451.

Rebased after #36451.
DrahtBot commented 2026-11-26 17:43:29 +00:00 (Migrated from github.com)

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

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
Sjors commented 2026-12-01 14:51:43 +00:00 (Migrated from github.com)
Rebased after: - #36895 (per commit CI failure is spurious: https://github.com/bitcoin/bitcoin/actions/runs/46670896379/job/142725496969?pr=35671)
DrahtBot commented 2026-12-01 15:27:39 +00:00 (Migrated from github.com)

🚧 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.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `test ancestor commits`: https://github.com/bitcoin/bitcoin/actions/runs/46670896379/job/142725496969</sub> <sub>LLM reason (✨ experimental): intermittent_network: `apt-get install` failed because Ubuntu package repositories repeatedly returned 503s and connection errors while fetching dependencies.</sub> <details><summary>Hints</summary> 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. </details>
DrahtBot commented 2026-12-02 04:24:57 +00:00 (Migrated from github.com)

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

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!35671
No description provided.