mining: add Block interface, fix template data race #36525

Open
Sjors wants to merge 5 commits from 2026/10/block-template-mutex into master AGit
Sjors commented 2026-10-14 08:43:40 +00:00 (Migrated from github.com)

This PR catches two birds with one stone:

This means a client can still fetch (and store) the block after submitSolution(), but we no longer mutate the template's CBlock for this.

Block interface

submitSolution() no longer modifies the template. It applies the solution to a copy of the template block and returns a Block handle for that copy, also when the block is rejected.

Mining::submitBlock() and BlockTemplate::block() do the same. The new interface has a data(), header() and coinbaseMerklePath() method, so these are migrated from the BlockTemplate interface.

The interface can be expanded later, e.g. to tell whether the block is part of the active chain (or went stale, useful for a miner to know).

This is a breaking change for IPC clients:

  • getBlockHeader() → block().header()
  • getBlock() → block().data()
  • getCoinbaseMerklePath() → block().coinbaseMerklePath()
  • bool submitSolution(..., reason, debug) → Block submitSolution(..., accepted, reason, debug)
  • bool submitBlock(block, reason, debug) → Block submitBlock(block, accepted, reason, debug)

It uses new ordinals and old methods throw.

submitSolution() now throws when the coinbase is null, instead of returning false.

Performance

My agent measured how long after submitSolution() sv2-tp forwards the next template, with master as the baseline and an adapted sv2-tp as the client:

Workload Master This PR Paired median difference (95% CI)
Empty block 1.32 ms 1.40 ms +0.05 ms [−0.11, +0.15]
Near-full block, 3.7 MB 10.11 ms 10.07 ms −0.09 ms [−0.44, +0.28]

The extra block() call costs about 0.15 ms per template for a C++ client. The alternative approach of having submitSolution() return the full CBlock added 6ms.

Memory

A Block handle keeps the template's memory, including its transactions, allocated until the client destroys the handle. This also applies to handles returned by submitSolution() and submitBlock(). This doesn't matter much in practice since (the existing) clients don't hold on to a Block long.

This PR catches two birds with one stone: - fixes https://github.com/bitcoin/bitcoin/issues/36515 - adds a `Block` interface, which lets IPC clients fetch the block data (or its header) This means a client can still fetch (and store) the block after `submitSolution()`, but we no longer mutate the template's `CBlock` for this. ### Block interface `submitSolution()` no longer modifies the template. It applies the solution to a copy of the template block and returns a `Block` handle for that copy, also when the block is rejected. `Mining::submitBlock()` and `BlockTemplate::block()` do the same. The new interface has a `data()`, `header()` and `coinbaseMerklePath()` method, so these are migrated from the `BlockTemplate` interface. The interface can be expanded later, e.g. to tell whether the block is part of the active chain (or went stale, useful for a miner to know). This is a breaking change for IPC clients: - `getBlockHeader()` → `block().header()` - `getBlock()` → `block().data()` - `getCoinbaseMerklePath()` → `block().coinbaseMerklePath()` - `bool submitSolution(..., reason, debug)` → `Block submitSolution(..., accepted, reason, debug)` - `bool submitBlock(block, reason, debug)` → `Block submitBlock(block, accepted, reason, debug)` It uses new ordinals and old methods throw. `submitSolution()` now throws when the coinbase is null, instead of returning false. ### Performance My agent measured how long after `submitSolution()` sv2-tp forwards the next template, with master as the baseline and an adapted sv2-tp as the client: | Workload | Master | This PR | Paired median difference (95% CI) | | --- | ---: | ---: | ---: | | Empty block | 1.32 ms | 1.40 ms | +0.05 ms [−0.11, +0.15] | | Near-full block, 3.7 MB | 10.11 ms | 10.07 ms | −0.09 ms [−0.44, +0.28] | The extra `block()` call costs about 0.15 ms per template for a C++ client. The alternative approach of having `submitSolution()` return the full `CBlock` added 6ms. ### Memory A `Block` handle keeps the template's memory, including its transactions, allocated until the client destroys the handle. This also applies to handles returned by `submitSolution()` and `submitBlock()`. This doesn't matter much in practice since (the existing) clients don't hold on to a `Block` long.
DrahtBot commented 2026-10-14 08:43:49 +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
Approach ACK ismaelsadeeq, ViniciusCestarii
Stale ACK enochaz, w0xlt

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:

  • #36870 (mining: use steady clock for waitNext timeout by ViniciusCestarii)
  • #36852 (test: split CreateNewBlock_validity into independent test cases by yuvicc)
  • #36820 (refactor: remove more dead code by fanquake)
  • #36257 (qa: assert_equal -> assert_true/assert_false by hodlinator)
  • #36156 (mining: include chunks that reach block limits by l0rinc)
  • #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):

  • test/functional/interface_ipc_mining.py: template.submitSolution(ctx, 0, 0, 0, b"")

2026-12-01 14:09:11

<!--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/36525 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36525.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36525#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 | | ---- | --------- | | Approach ACK | [ismaelsadeeq](https://github.com/bitcoin/bitcoin/pull/36525#issuecomment-7007174786), [ViniciusCestarii](https://github.com/bitcoin/bitcoin/pull/36525#pullrequestreview-5993344884) | | Stale ACK | [enochaz](https://github.com/bitcoin/bitcoin/pull/36525#pullrequestreview-5545791068), [w0xlt](https://github.com/bitcoin/bitcoin/pull/36525#pullrequestreview-5592756558) | 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: * [#36870](https://github.com/bitcoin/bitcoin/pull/36870) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36870.svg"></sub> (mining: use steady clock for waitNext timeout by ViniciusCestarii) * [#36852](https://github.com/bitcoin/bitcoin/pull/36852) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36852.svg"></sub> (test: split `CreateNewBlock_validity` into independent test cases by yuvicc) * [#36820](https://github.com/bitcoin/bitcoin/pull/36820) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36820.svg"></sub> (refactor: remove more dead code by fanquake) * [#36257](https://github.com/bitcoin/bitcoin/pull/36257) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36257.svg"></sub> (qa: assert_equal -> assert_true/assert_false by hodlinator) * [#36156](https://github.com/bitcoin/bitcoin/pull/36156) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36156.svg"></sub> (mining: include chunks that reach block limits by l0rinc) * [#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): - `test/functional/interface_ipc_mining.py`: `template.submitSolution(ctx, 0, 0, 0, b"")` <sup>2026-12-01 14:09:11</sup>
First-time contributor

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

🟠 Minor · Failure cleanup can destroy the template during submitSolution()

On failure or timeout, run_concurrent_template_access_test() cancels client awaits without draining the writer worker, so template destruction can race with server-side submitSolution().

Location: test/functional/interface_ipc_mining.py:951 (head).

🔵 Suggestion · Mining IPC migration is missing a release note

The intentional mining IPC break has no release note explaining the replacement methods, accepted results, or the lifetime of returned Block handles.

Location: src/ipc/capnp/mining.capnp:51 (head).

🔵 Suggestion · Submitted Block snapshots are only checked immediately

No test rereads a submitSolution() handle after another submission or template destruction, so it would miss reusable storage changing a previously returned block.

Location: test/functional/interface_ipc_mining.py:609 (head).

🔵 Suggestion · The race test is rewritten in the next commit

The race-test commit adds three getBlockHeader() calls that the next commit immediately rewrites to block().header(), adding avoidable review churn.

Location: test/functional/interface_ipc_mining.py:925 (commit).

Review coverage was incomplete.


Reviewed: 283d5ae4e890 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:312ddb2095238aa2ca395a9cc39b05ab5a38a7177afbdb0d69098df9c3e0bef9:9a7f127b15c6116c267953d38288a9f17ec7c7bcd3a975fb71a2db8bfd974dbf --> <!-- ralph-base:afa492e233868bcf4799bb62943baa28017938f6 --> <!-- ralph-head:283d5ae4e890569818a65d10d97d46c8073a6f55 --> <!-- ralph-case:6e0499d458be1d86c646f98099e12271736be8ca6a35596e91a57a2a98b3b58d --> Earlier concerns neither republished nor resolved: 2 suggestions. See the Run archive linked from the Review report for their assessments. **🟠 Minor · Failure cleanup can destroy the template during `submitSolution()`** On failure or timeout, `run_concurrent_template_access_test()` cancels client awaits without draining the writer worker, so template destruction can race with server-side `submitSolution()`. Location: [`test/functional/interface_ipc_mining.py:951`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/283d5ae4e890569818a65d10d97d46c8073a6f55/test/functional/interface_ipc_mining.py#L951>) (head). **🔵 Suggestion · Mining IPC migration is missing a release note** The intentional mining IPC break has no release note explaining the replacement methods, `accepted` results, or the lifetime of returned `Block` handles. Location: [`src/ipc/capnp/mining.capnp:51`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/283d5ae4e890569818a65d10d97d46c8073a6f55/src/ipc/capnp/mining.capnp#L51>) (head). **🔵 Suggestion · Submitted `Block` snapshots are only checked immediately** No test rereads a `submitSolution()` handle after another submission or template destruction, so it would miss reusable storage changing a previously returned block. Location: [`test/functional/interface_ipc_mining.py:609`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/283d5ae4e890569818a65d10d97d46c8073a6f55/test/functional/interface_ipc_mining.py#L609>) (head). **🔵 Suggestion · The race test is rewritten in the next commit** The race-test commit adds three `getBlockHeader()` calls that the next commit immediately rewrites to `block().header()`, adding avoidable review churn. Location: test/functional/interface_ipc_mining.py:925 (commit). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`283d5ae4e890`](<https://git.fish.foo/bitcoin/bitcoin/commit/283d5ae4e890569818a65d10d97d46c8073a6f55>) · [Review report](<https://review.fish.foo/report/36525-283d5ae4e890569818a65d10d97d46c8073a6f55-3394-13.html>) · [Previous reports](<https://review.fish.foo/traces/36525/>) [permalink](<https://review.fish.foo/report/36525-283d5ae4e890569818a65d10d97d46c8073a6f55-3394-13.html>)
ismaelsadeeq (Migrated from github.com) reviewed 2026-10-15 04:44:50 +00:00
ismaelsadeeq (Migrated from github.com) left a comment

ACK 4774cf1de6

add a new getTotalFees() getter so IPC clients don't have to sum up individual transaction fees

I thought the client needed to access the individual fees, so we return a vector. It makes sense to return it so they don't have to sum them, so the vector one is now redundant?

See minimal test that fails on our tsan functional tests.

diff --git a/test/functional/interface_ipc_mining.py b/test/functional/interface_ipc_mining.py
index c55a8f7a54..a969691596 100755
--- a/test/functional/interface_ipc_mining.py
+++ b/test/functional/interface_ipc_mining.py
@@ -41,6 +41,7 @@ from test_framework.ipc_util import (
     assert_create_new_block_fails,
     destroying,
     load_capnp_modules,
+    make_capnp_init_ctx,
     make_mining_ctx,
     mining_create_block_template,
     mining_get_block,
@@ -799,6 +800,45 @@ class IPCMiningTest(BitcoinTestFramework):

         asyncio.run(capnp.run(async_routine()))

+    def run_concurrent_template_access_test(self):
+        """Reading and submitting a template at the same time must not race."""
+        self.log.info("Running concurrent template access test")
+
+        async def async_routine():
+            # One context runs on one server thread. Two contexts run on two
+            # threads, so the read and the submit can run at the same time and race.
+            reader_ctx, init = await make_capnp_init_ctx(self)
+            writer_ctx = self.capnp_modules['proxy'].Context()
+            writer_ctx.thread = init.construct().threadMap.makeThread("pythread").result
+            mining = init.makeMining(reader_ctx).result
+
+            async with AsyncExitStack() as stack:
+                template = await mining_create_block_template(
+                    mining, stack, reader_ctx, self.default_block_create_options, cooldown=False)
+                assert template is not None
+                block = await mining_get_block(template, reader_ctx)
+                # No witness means every submit is rejected, so the tip never moves.
+                coinbase = block.vtx[0].serialize_without_witness()
+                height = self.nodes[0].getblockcount()
+
+                done = asyncio.Event()
+
+                async def read_loop():
+                    while not done.is_set():
+                        await template.getBlockHeader(reader_ctx)
+                        await template.getBlock(reader_ctx)
+
+                async def submit_loop():
+                    for _ in range(100):
+                        await template.submitSolution(
+                            writer_ctx, block.nVersion, block.nTime, block.nNonce, coinbase)
+                    done.set()
+
+                await asyncio.gather(read_loop(), submit_loop())
+                assert_equal(self.nodes[0].getblockcount(), height)
+
+        asyncio.run(capnp.run(async_routine()))
+
     def run_test(self):
         self.miniwallet = MiniWallet(self.nodes[0])
         # Amount of time in milliseconds the test is allowed to wait or be idle before it should fail.
@@ -815,6 +855,7 @@ class IPCMiningTest(BitcoinTestFramework):
         self.run_block_max_weight_test()
         self.run_ipc_option_override_test()
         self.run_transaction_lookup_test()
+        self.run_concurrent_template_access_test()

         # Needs to run last because it resets the chain.
         self.run_low_height_test()
ACK 4774cf1de6a4670323686bf93beb93035b3f6dad > add a new getTotalFees() getter so IPC clients don't have to sum up individual transaction fees I thought the client needed to access the individual fees, so we return a vector. It makes sense to return it so they don't have to sum them, so the vector one is now redundant? See minimal test that fails on our tsan functional tests. <details> ```diff diff --git a/test/functional/interface_ipc_mining.py b/test/functional/interface_ipc_mining.py index c55a8f7a54..a969691596 100755 --- a/test/functional/interface_ipc_mining.py +++ b/test/functional/interface_ipc_mining.py @@ -41,6 +41,7 @@ from test_framework.ipc_util import ( assert_create_new_block_fails, destroying, load_capnp_modules, + make_capnp_init_ctx, make_mining_ctx, mining_create_block_template, mining_get_block, @@ -799,6 +800,45 @@ class IPCMiningTest(BitcoinTestFramework): asyncio.run(capnp.run(async_routine())) + def run_concurrent_template_access_test(self): + """Reading and submitting a template at the same time must not race.""" + self.log.info("Running concurrent template access test") + + async def async_routine(): + # One context runs on one server thread. Two contexts run on two + # threads, so the read and the submit can run at the same time and race. + reader_ctx, init = await make_capnp_init_ctx(self) + writer_ctx = self.capnp_modules['proxy'].Context() + writer_ctx.thread = init.construct().threadMap.makeThread("pythread").result + mining = init.makeMining(reader_ctx).result + + async with AsyncExitStack() as stack: + template = await mining_create_block_template( + mining, stack, reader_ctx, self.default_block_create_options, cooldown=False) + assert template is not None + block = await mining_get_block(template, reader_ctx) + # No witness means every submit is rejected, so the tip never moves. + coinbase = block.vtx[0].serialize_without_witness() + height = self.nodes[0].getblockcount() + + done = asyncio.Event() + + async def read_loop(): + while not done.is_set(): + await template.getBlockHeader(reader_ctx) + await template.getBlock(reader_ctx) + + async def submit_loop(): + for _ in range(100): + await template.submitSolution( + writer_ctx, block.nVersion, block.nTime, block.nNonce, coinbase) + done.set() + + await asyncio.gather(read_loop(), submit_loop()) + assert_equal(self.nodes[0].getblockcount(), height) + + asyncio.run(capnp.run(async_routine())) + def run_test(self): self.miniwallet = MiniWallet(self.nodes[0]) # Amount of time in milliseconds the test is allowed to wait or be idle before it should fail. @@ -815,6 +855,7 @@ class IPCMiningTest(BitcoinTestFramework): self.run_block_max_weight_test() self.run_ipc_option_override_test() self.run_transaction_lookup_test() + self.run_concurrent_template_access_test() # Needs to run last because it resets the chain. self.run_low_height_test() ``` </details>
Sjors commented 2026-10-15 05:24:06 +00:00 (Migrated from github.com)

The vector was initially introduced for (internal) compatibility with the getblocktemplate RPC, which returns this fee information.

sv2-tp only uses fees (the total) for logging, the SRI implementation doesn't use it at all.

I haven't done an inventory of software out there that uses the fees from getblocktemplate. One use case I could imagine is a miner dashboard that shows the current template you're working on, and a breakdown of fees.

We definitely need the internal total. Providing the total and individual via IPC is trivial, so I think we should keep it.

The vector was initially introduced for (internal) compatibility with the `getblocktemplate` RPC, which returns this fee information. `sv2-tp` only uses fees (the total) for logging, the SRI implementation doesn't use it at all. I haven't done an inventory of software out there that uses the fees from `getblocktemplate`. One use case I could imagine is a miner dashboard that shows the current template you're working on, and a breakdown of fees. We definitely need the internal total. Providing the total and individual via IPC is trivial, so I think we should keep it.
Sjors commented 2026-10-15 05:58:07 +00:00 (Migrated from github.com)

See minimal test that fails on our tsan functional tests.

It works and I'm open to taking it, but failure isn't deterministic (just very likely with the 100 iterations).

> See minimal test that fails on our tsan functional tests. It works and I'm open to taking it, but failure isn't deterministic (just very likely with the 100 iterations).
w0xlt commented 2026-10-15 06:06:24 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
ismaelsadeeq commented 2026-10-15 07:26:19 +00:00 (Migrated from github.com)

It works and I'm open to taking it, but failure isn't deterministic (just very likely with the 100 iterations).

Indeed, it is not deterministic but is sure to fail at some point.

> It works and I'm open to taking it, but failure isn't deterministic (just very likely with the 100 iterations). Indeed, it is not deterministic but is sure to fail at some point.
enirox001 (Migrated from github.com) reviewed 2026-10-15 09:07:11 +00:00
enirox001 (Migrated from github.com) left a comment

ACK 4774cf1de6

This change fixes a data race between ipc calls running on different worker threads, where submitSolution modifies a template while another call reads it. It also adds the getTotalFees IPC method, allowing external clients to retrieve the total fees without summing individual transaction fees.

Ran @ismaelsadeeq's ipc test with tsan, 25 times each with 100, 150, 200 and 300 submissions. without the mutex fix, all 100 runs detected the race. with the fix, all 100 passed with no race reports or timeouts.

I think the test is worth including. even though reproduction depends on scheduling, it consistently caught the regression on my machine (macOS ARM64)

ACK 4774cf1de6a4670323686bf93beb93035b3f6dad This change fixes a data race between ipc calls running on different worker threads, where `submitSolution` modifies a template while another call reads it. It also adds the `getTotalFees` IPC method, allowing external clients to retrieve the total fees without summing individual transaction fees. Ran @ismaelsadeeq's ipc test with tsan, 25 times each with 100, 150, 200 and 300 submissions. without the mutex fix, all 100 runs detected the race. with the fix, all 100 passed with no race reports or timeouts. I think the test is worth including. even though reproduction depends on scheduling, it consistently caught the regression on my machine (macOS ARM64)
Sjors commented 2026-10-16 00:35:43 +00:00 (Migrated from github.com)

Added the test in a new commit, with some adjustments:

  • use timeout_factor to avoid false positive failures
  • improve cleanup
Added the test in a new commit, with some adjustments: - use `timeout_factor` to avoid false positive failures - improve cleanup
ismaelsadeeq (Migrated from github.com) approved these changes 2026-10-16 04:37:47 +00:00
ismaelsadeeq (Migrated from github.com) left a comment

reACK cbadeff334

reACK cbadeff334f182086538d7483dc1146c559859e6
enirox001 (Migrated from github.com) reviewed 2026-10-16 09:34:33 +00:00
enirox001 (Migrated from github.com) left a comment
reACK https://github.com/bitcoin/bitcoin/pull/36525/changes/cbadeff334f182086538d7483dc1146c559859e6
w0xlt (Migrated from github.com) reviewed 2026-10-20 22:48:39 +00:00
w0xlt (Migrated from github.com) left a comment

ACK cbadeff334

nit:

diff --git a/src/node/block_template_manager.cpp b/src/node/block_template_manager.cpp
index f4875ff4f6..310d9726b5 100644
--- a/src/node/block_template_manager.cpp
+++ b/src/node/block_template_manager.cpp
@@ -146,9 +146,9 @@ std::unique_ptr<CBlockTemplate> BlockTemplateManager::WaitAndCreateNewBlock(
             m_notifications.m_tip_block_cv.wait_until(lock, std::min(now + tick, deadline), [&]() EXCLUSIVE_LOCKS_REQUIRED(m_notifications.m_tip_block_mutex) {
                 AssertLockHeld(m_notifications.m_tip_block_mutex);
                 const auto tip_block{m_notifications.TipBlock()};
-                // We assume tip_block is set, because this is an instance
-                // method on BlockTemplate and no template could have been
-                // generated before a tip exists.
+                // We assume tip_block is set, because callers pass the parent
+                // hash of an existing template and no template could have
+                // been generated before a tip exists.
                 tip_changed = Assume(tip_block) && tip_block != hash_prev_block;
                 return tip_changed || m_chainman.m_interrupt || interrupt_wait;
             });
diff --git a/src/node/block_template_manager.h b/src/node/block_template_manager.h
index 88bdef4fa4..880af33293 100644
--- a/src/node/block_template_manager.h
+++ b/src/node/block_template_manager.h
@@ -100,6 +100,7 @@ public:
      * (on testnet3, testnet4, and regtest).
      *
      * @param[in] hash_prev_block Parent block hash of the previous template.
+     *                            The chain tip must already be set.
      * @param[in] current_fees Total transaction fees in the previous template, in satoshis.
      * @param[in] wait_options Timeout and minimum fee increase relative to current_fees.
      * @param[in] create_options Options used to create the next block template.
ACK cbadeff334 nit: ```diff diff --git a/src/node/block_template_manager.cpp b/src/node/block_template_manager.cpp index f4875ff4f6..310d9726b5 100644 --- a/src/node/block_template_manager.cpp +++ b/src/node/block_template_manager.cpp @@ -146,9 +146,9 @@ std::unique_ptr<CBlockTemplate> BlockTemplateManager::WaitAndCreateNewBlock( m_notifications.m_tip_block_cv.wait_until(lock, std::min(now + tick, deadline), [&]() EXCLUSIVE_LOCKS_REQUIRED(m_notifications.m_tip_block_mutex) { AssertLockHeld(m_notifications.m_tip_block_mutex); const auto tip_block{m_notifications.TipBlock()}; - // We assume tip_block is set, because this is an instance - // method on BlockTemplate and no template could have been - // generated before a tip exists. + // We assume tip_block is set, because callers pass the parent + // hash of an existing template and no template could have + // been generated before a tip exists. tip_changed = Assume(tip_block) && tip_block != hash_prev_block; return tip_changed || m_chainman.m_interrupt || interrupt_wait; }); diff --git a/src/node/block_template_manager.h b/src/node/block_template_manager.h index 88bdef4fa4..880af33293 100644 --- a/src/node/block_template_manager.h +++ b/src/node/block_template_manager.h @@ -100,6 +100,7 @@ public: * (on testnet3, testnet4, and regtest). * * @param[in] hash_prev_block Parent block hash of the previous template. + * The chain tip must already be set. * @param[in] current_fees Total transaction fees in the previous template, in satoshis. * @param[in] wait_options Timeout and minimum fee increase relative to current_fees. * @param[in] create_options Options used to create the next block template. ```
Sjors commented 2026-10-21 03:54:37 +00:00 (Migrated from github.com)

@w0xlt I prefer the existing wording:

callers pass the parent hash of an existing template

The function doesn't know where the caller got its hash.

@w0xlt I prefer the existing wording: > callers pass the parent hash of an existing template The function doesn't know where the caller got its hash.
sedited commented 2026-10-21 09:59:08 +00:00 (Migrated from github.com)

Might it be preferable to make m_block_template non-mutating? Do users of the interface even need the mutated template after submitting?

Might it be preferable to make `m_block_template` non-mutating? Do users of the interface even need the mutated template after submitting?
ismaelsadeeq commented 2026-10-21 10:25:51 +00:00 (Migrated from github.com)

AFAICT no, so we could do that and make the template const, that way no race and we copy when mutating for submission.

AFAICT no, so we could do that and make the template const, that way no race and we copy when mutating for submission.
w0xlt commented 2026-10-21 16:47:27 +00:00 (Migrated from github.com)

Might it be preferable to make m_block_template non-mutating?

I think it's a preferable solution. With no writes after construction there's no race, and since submitSolution() already copies the block, calling AddMerkleRootAndCoinbase() on that copy instead of on the template costs nothing.

The documentation and tests would need to be updated too, since the in-place mutation is documented and tested since #33745 (released in v31).

The sv2-tp client apparently relies on that mutation (SaveBlockAsync()), but it may be easy to update.

> Might it be preferable to make m_block_template non-mutating? I think it's a preferable solution. With no writes after construction there's no race, and since `submitSolution()` already copies the block, calling `AddMerkleRootAndCoinbase()` on that copy instead of on the template costs nothing. The documentation and tests would need to be updated too, since the in-place mutation is documented and tested since #33745 (released in v31). The sv2-tp client apparently relies on that mutation (`SaveBlockAsync()`), but it may be easy to update.
Sjors commented 2026-10-24 05:32:17 +00:00 (Migrated from github.com)

Do users of the interface even need the mutated template after submitting?

Yes. Both existing clients call getBlock() after submit to store a copy of the block. This is potentially very useful when debugging a rejected block.

The sv2-tp client apparently relies on that mutation (SaveBlockAsync()), but it may be easy to update.

Clients could download the non-mutated block and re-apply the solution themselves before storing to disk. That's slightly more complicated, so I prefer the existing approach.

> Do users of the interface even need the mutated template after submitting? Yes. Both existing clients call `getBlock()` after submit to store a copy of the block. This is potentially very useful when debugging a rejected block. > The sv2-tp client apparently relies on that mutation (`SaveBlockAsync()`), but it may be easy to update. Clients could download the non-mutated block and re-apply the solution themselves before storing to disk. That's slightly more complicated, so I prefer the existing approach.
ismaelsadeeq commented 2026-10-25 06:16:29 +00:00 (Migrated from github.com)

Could we just return the block copy after applying the solution?

Could we just return the block copy after applying the solution?
Sjors commented 2026-10-25 10:03:53 +00:00 (Migrated from github.com)

@ismaelsadeeq in theory yes, but clients intentionally wait 1 second before requesting it. If the solution is correct, we don't want to "distract" the node from relaying it and from producing the next template.

@ismaelsadeeq in theory yes, but clients intentionally wait 1 second before requesting it. If the solution _is_ correct, we don't want to "distract" the node from relaying it and from producing the next template.
sedited commented 2026-10-25 10:22:19 +00:00 (Migrated from github.com)

If the solution is correct, we don't want to "distract" the node from relaying it and from producing the next template.

I don't understand what you mean here. Doesn't the new valid header get processed synchronously anyway?

> If the solution is correct, we don't want to "distract" the node from relaying it and from producing the next template. I don't understand what you mean here. Doesn't the new valid header get processed synchronously anyway?
Sjors commented 2026-10-26 04:35:00 +00:00 (Migrated from github.com)

A call to getBlock() locks cs_main (briefly). Since sv2-tp typically runs on the same machine, when it saves to disk it also blocks the OS. Creating the new template blocks cs_main. And IIUC so does our p2p code when it announces the new block and handles compact block missing-transaction requests.

That said, I haven't done a very thorough analysis on whether the 1 second delay before getBlock() actually matters.

A call to `getBlock()` locks `cs_main` (briefly). Since `sv2-tp` typically runs on the same machine, when it saves to disk it also blocks the OS. Creating the new template blocks `cs_main`. And IIUC so does our p2p code when it announces the new block and handles compact block missing-transaction requests. That said, I haven't done a very thorough analysis on whether the 1 second delay before `getBlock()` actually matters.
sedited commented 2026-10-28 10:05:26 +00:00 (Migrated from github.com)

A call to getBlock() locks cs_main (briefly). Since sv2-tp typically runs on the same machine, when it saves to disk it also blocks the OS. Creating the new template blocks cs_main. And IIUC so does our p2p code when it announces the new block and handles compact block missing-transaction requests.

That should all be unrelated to copying a block. Or is the concern just that the OS might be something more important in the meantime and this might distract it? I don't think that is a valid concern.

> A call to getBlock() locks cs_main (briefly). Since sv2-tp typically runs on the same machine, when it saves to disk it also blocks the OS. Creating the new template blocks cs_main. And IIUC so does our p2p code when it announces the new block and handles compact block missing-transaction requests. That should all be unrelated to copying a block. Or is the concern just that the OS might be something more important in the meantime and this might distract it? I don't think that is a valid concern.
Sjors commented 2026-10-29 08:17:42 +00:00 (Migrated from github.com)

I wrote:

A call to getBlock() locks cs_main (briefly).

This is not the case.

I benchmarked the approach of making the template block immutable and returning the full block in submitSolution(). The good news is that there's no regression in compact block relay, not even when a transaction is missing.

But it does add a 6ms slowdown to when sv2-tp serves the next template. That's because IPC code still bottlenecks a few things on a single thread (even with multiple connections).

I was able to reduce that by having sv2-tp skip block deserialization (including sha256 hashing), and write the serialized bytes straight to disk (after a 500ms delay). That still left 2.5ms.

Things can be sped up further by:

  1. having another thread copy the result (1ms)
  2. taking advantage of Capnp shared memory support: https://capnproto.org/cxxrpc.html (1ms)
  3. more fundamentally making IPC (response) handling parallel

These require changes to libmultiprocess.

So my preference would be to defer making CBlockTemplate const until after these improvements land. This would be a breaking change for clients, but that's straight-forward to work around.

I wrote: > A call to `getBlock()` locks `cs_main` (briefly). This is not the case. I benchmarked the approach of making the template block immutable and returning the full block in `submitSolution()`. The good news is that there's no regression in compact block relay, not even when a transaction is missing. But it does add a 6ms slowdown to when sv2-tp serves the next template. That's because IPC code still bottlenecks a few things on a single thread (even with multiple connections). I was able to reduce that by having sv2-tp skip block deserialization (including sha256 hashing), and write the serialized bytes straight to disk (after a 500ms delay). That still left 2.5ms. Things can be sped up further by: 1. having another thread copy the result (1ms) 2. taking advantage of Capnp shared memory support: https://capnproto.org/cxxrpc.html (1ms) 3. more fundamentally making IPC (response) handling parallel These require changes to libmultiprocess. So my preference would be to defer making CBlockTemplate const until after these improvements land. This would be a breaking change for clients, but that's straight-forward to work around.
Sjors commented 2026-10-29 09:19:02 +00:00 (Migrated from github.com)

There's another approach, though a bit of a layer violation: we can have submitSolution() defer its response so it comes after waitNext(). But I also prefer doing that as a followup, rather than increase the scope of this PR.

There's another approach, though a bit of a layer violation: we can have `submitSolution()` defer its response so it comes _after_ `waitNext()`. But I also prefer doing that as a followup, rather than increase the scope of this PR.
DrahtBot commented 2026-11-05 17:10:59 +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-06 07:49:35 +00:00 (Migrated from github.com)

Rebased after #36192.

Rebased after #36192.
ViniciusCestarii commented 2026-11-10 14:50:30 +00:00 (Migrated from github.com)

Concept ACK on getTotalFees()

But it does add a 6ms slowdown to when sv2-tp serves the next template. That's because IPC code still bottlenecks a few things on a single thread (even with multiple connections).

Could you share how you benchmarked this? I'd like to reproduce it and it would also be useful for measuring the libmultiprocess improvements later.

IMO 6ms or 2.5ms seems an acceptable cost for an immutable template, especially since it only applies after the miner itself finds a valid block and you've already identified ways to bring it down. Doing it now avoids adding a mutex that would likely be removed later and gives a cleaner interface for users that are currently experimenting with it.

Concept ACK on getTotalFees() > But it does add a 6ms slowdown to when sv2-tp serves the next template. That's because IPC code still bottlenecks a few things on a single thread (even with multiple connections). Could you share how you benchmarked this? I'd like to reproduce it and it would also be useful for measuring the libmultiprocess improvements later. IMO 6ms or 2.5ms seems an acceptable cost for an immutable template, especially since it only applies after the miner itself finds a valid block and you've already identified ways to bring it down. Doing it now avoids adding a mutex that would likely be removed later and gives a cleaner interface for users that are currently experimenting with it.
Sjors commented 2026-11-11 17:03:29 +00:00 (Migrated from github.com)

Could you share how you benchmarked this?

Here you go: https://gist.github.com/Sjors/22182fa24d2cf1337bed19cf70591c4f

IMO 6ms or 2.5ms seems an acceptable cost

One of the selling points of Stratum v2 is lower latency, see e.g. https://stratumprotocol.org/blog/case-study/hashlabs/

SV2 with Job Declaration reduces block propagation time from 96.3 milliseconds (SV1) to just 3.44 milliseconds, making block propagation faster.

I don't know what methodology they used (might be a bit optimistic), but adding 6ms just for a code style improvement, doesn't seem justified in light of those numbers.

> Could you share how you benchmarked this? Here you go: https://gist.github.com/Sjors/22182fa24d2cf1337bed19cf70591c4f > IMO 6ms or 2.5ms seems an acceptable cost One of the selling points of Stratum v2 is lower latency, see e.g. https://stratumprotocol.org/blog/case-study/hashlabs/ > SV2 with Job Declaration reduces block propagation time from 96.3 milliseconds (SV1) to just 3.44 milliseconds, making block propagation faster. I don't know what methodology they used (might be a bit optimistic), but adding 6ms just for a code style improvement, doesn't seem justified in light of those numbers.
ViniciusCestarii commented 2026-11-11 21:58:23 +00:00 (Migrated from github.com)

Thanks @Sjors! I was able to reproduce it on my machine. I got similar results.

The latency measured doens't affect block propagation but "Block Change latency" which is 325 ms for SV1 and 1.42 ms for SV2 with JD. I still consider the 6ms after submitSolution a negligible delay because its average cost per network block is about 6 ms × hashrate share: ~1.8 ms for a 30% pool, ~0.06 ms for a 1% miner.

That said, I don’t feel strongly about. I am fine with it being a future follow up.

Thanks @Sjors! I was able to reproduce it on my machine. I got similar results. The latency measured doens't affect block propagation but "Block Change latency" which is 325 ms for SV1 and 1.42 ms for SV2 with JD. I still consider the 6ms after `submitSolution` a negligible delay because its average cost per network block is about 6 ms × hashrate share: ~1.8 ms for a 30% pool, ~0.06 ms for a 1% miner. That said, I don’t feel strongly about. I am fine with it being a future follow up.
ViniciusCestarii commented 2026-11-16 11:08:18 +00:00 (Migrated from github.com)

I tried another approach: submitSolution() returns a SubmittedBlock capability instead of the block itself, so the client can fetch it later with getBlock(), only if and when it needs it. The template stays immutable and there's no mutex.

interface SubmittedBlock $Proxy.wrap("interfaces::SubmittedBlock") {
    destroy @0 (context :Proxy.Context) -> ();
    getBlock @1 (context: Proxy.Context) -> (result: Data);
}

submitSolution @10 (...) -> (reason: Text, debug: Text, accepted: Bool, result: SubmittedBlock);

Benchmarked it and got no performance regression with this approach.

Draft:

Bitcoin Core diff: github.com/ViniciusCestarii/bitcoin@5c7fe8ee23
sv2-tp diff: github.com/ViniciusCestarii/sv2-tp@7faa751ed1

This gets the immutable template without the regression and without waiting for the libmultiprocess improvements. Happy to open it as a followup PR.

I tried another approach: `submitSolution()` returns a `SubmittedBlock` capability instead of the block itself, so the client can fetch it later with `getBlock()`, only if and when it needs it. The template stays immutable and there's no mutex. ``` interface SubmittedBlock $Proxy.wrap("interfaces::SubmittedBlock") { destroy @0 (context :Proxy.Context) -> (); getBlock @1 (context: Proxy.Context) -> (result: Data); } submitSolution @10 (...) -> (reason: Text, debug: Text, accepted: Bool, result: SubmittedBlock); ``` Benchmarked it and got no performance regression with this approach. Draft: Bitcoin Core diff: https://github.com/ViniciusCestarii/bitcoin/commit/5c7fe8ee23cac873df8645b566150cc864e4c729 sv2-tp diff: https://github.com/ViniciusCestarii/sv2-tp/commit/7faa751ed160e1f210ad4644a1797bfdb62e1388 This gets the immutable template without the regression and without waiting for the libmultiprocess improvements. Happy to open it as a followup PR.
DrahtBot commented 2026-11-16 17:11: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).
Sjors commented 2026-11-18 13:00:42 +00:00 (Migrated from github.com)

Rebased after #36451.

@ViniciusCestarii looking into your approach

Rebased after #36451. @ViniciusCestarii looking into your approach
Sjors commented 2026-11-18 14:53:59 +00:00 (Migrated from github.com)

I added a new Block interface. To keep this PR simple, I'm going to open a fresh PR for getTotalFees(), since it no longer makes sense to combine that feature (requested in https://github.com/bitcoin/bitcoin/pull/35671#issuecomment-6165435275) with the fix for https://github.com/bitcoin/bitcoin/issues/36515. Most review on this PR was focussed on the latter.

The Block interface is returned by submitSolution(), submitBlock() and getBlock(). It starts out with just data(), header() and coinbaseMerklePath(). The latter two are moved out of BlockTemplate.

It could later be expanded later to e.g. say if a block is part of the active chain (very useful for a miner to know).

The coinbaseTx() getter stays on the template, because it does not return the actual coinbase transaction but rather a struct that is only useful for mining software to generate a coinbase transaction.

I'm keeping getTxFees() and getTxSigops() in the template, because they are calculated at template generation time and non-trivial to calculate in other contexts.

The chain interface proposed in #29409 might also be able to use this.

I renamed getBlock() to block(), so clients call block().data() to get the block's data. Note that this takes advantage of Cap’n Proto promise pipelining (see the ipc_util.py change).

This is a breaking change and I intentionally made getBlockOld2, etc fail, because in the past reviewers complained when I made backward compatible changes while the interface is still experimental. This is no problem for sv2-tp and SRI which are pretty good at handling our breaking changes between our major releases. (FWIW my goal is to remove the experimental status after Windows support lands)

I ran the performance benchmark again and there's no regression, so: a better interface, no need for a mutex and it stays fast.

I added a new `Block` interface. To keep this PR simple, I'm going to open a fresh PR for `getTotalFees()`, since it no longer makes sense to combine that feature (requested in https://github.com/bitcoin/bitcoin/pull/35671#issuecomment-6165435275) with the fix for https://github.com/bitcoin/bitcoin/issues/36515. Most review on this PR was focussed on the latter. The `Block` interface is returned by `submitSolution()`, `submitBlock()` and `getBlock()`. It starts out with just `data()`, `header()` and `coinbaseMerklePath()`. The latter two are moved out of `BlockTemplate`. It could later be expanded later to e.g. say if a block is part of the active chain (very useful for a miner to know). The `coinbaseTx()` getter stays on the template, because it does not return the actual coinbase transaction but rather a struct that is only useful for mining software to _generate_ a coinbase transaction. I'm keeping `getTxFees()` and `getTxSigops()` in the template, because they are calculated at template generation time and non-trivial to calculate in other contexts. The chain interface proposed in #29409 might also be able to use this. I renamed `getBlock()` to `block()`, so clients call `block().data()` to get the block's data. Note that this takes advantage of Cap’n Proto promise pipelining (see the `ipc_util.py` change). This is a breaking change and I intentionally made `getBlockOld2`, etc fail, because in the past reviewers complained when I made backward compatible changes while the interface is still experimental. This is no problem for sv2-tp and SRI which are pretty good at handling our breaking changes between our major releases. (FWIW my goal is to remove the experimental status after Windows support lands) I ran the performance benchmark again and there's no regression, so: a better interface, no need for a mutex and it stays fast.
xyzconstant (Migrated from github.com) reviewed 2026-11-19 02:50:05 +00:00
xyzconstant (Migrated from github.com) left a comment

Code review 1f9fcfab45

The approach is sound to me, but now the Block capability served to clients holds references to TXs that might leave the mempool. IPC clients now take responsibility for dropping these block capabilities and as a result freeing up memory on the node (good this is that this is trivial to inspect with the getMemoryLoad method proposed in #33922). This behaviour change should be documented in the PR description and the first commit msg.

Planning to review more.

Code review 1f9fcfab45fa2bdd8296c265dfac2dd206a353bc The approach is sound to me, but now the `Block` capability served to clients holds references to TXs that might leave the mempool. IPC clients now take responsibility for dropping these block capabilities and as a result freeing up memory on the node (good this is that this is trivial to inspect with the `getMemoryLoad` method proposed in #33922). This behaviour change should be documented in the PR description and the first commit msg. Planning to review more.
xyzconstant (Migrated from github.com) commented 2026-11-19 02:22:54 +00:00

In commit 1f9fcfab45 "mining: return Block from Mining::submitBlock()"

nit:

result -> accepted
diff --git a/test/functional/interface_ipc_mining.py b/test/functional/interface_ipc_mining.py
index e0c92c1b93..c6a46df37c 100755
--- a/test/functional/interface_ipc_mining.py
+++ b/test/functional/interface_ipc_mining.py
@@ -130,9 +130,9 @@ class IPCMiningTest(BitcoinTestFramework):
         block.hashMerkleRoot = block.calc_merkle_root()
         return block
 
-    async def assert_submit_block(self, mining, ctx, block, *, result, reason="", debug=""):
+    async def assert_submit_block(self, mining, ctx, block, *, accepted, reason="", debug=""):
         submit = await mining.submitBlock(ctx, block.serialize())
-        assert_equal(submit.accepted, result)
+        assert_equal(submit.accepted, accepted)
         assert_equal((await submit.result.data(ctx)).result, block.serialize())
         assert_equal(submit.reason, reason)
         assert_equal(submit.debug, debug)
@@ -569,7 +569,7 @@ class IPCMiningTest(BitcoinTestFramework):
                     mining2,
                     ctx2,
                     block,
-                    result=False,
+                    accepted=False,
                     reason="bad-version(0x00000000)",
                     debug="rejected nVersion=0x00000000 block",
                 )
@@ -612,7 +612,7 @@ class IPCMiningTest(BitcoinTestFramework):
                     mining2,
                     ctx2,
                     missing_witness_block,
-                    result=False,
+                    accepted=False,
                     reason="bad-witness-nonce-size",
                     debug="CheckWitnessMalleation : invalid witness reserved value size",
                 )
@@ -624,10 +624,10 @@ class IPCMiningTest(BitcoinTestFramework):
                 assert_equal(result.debug, "")
 
                 self.log.debug("Submit a valid complete block through the disconnected node")
-                await self.assert_submit_block(mining2, ctx2, block, result=True)
+                await self.assert_submit_block(mining2, ctx2, block, accepted=True)
                 assert_equal(self.nodes[2].getchaintips()[0]["height"], current_block_height + 1)
                 self.log.debug("submitBlock should reject the duplicate complete block")
-                await self.assert_submit_block(mining2, ctx2, block, result=False, reason="duplicate")
+                await self.assert_submit_block(mining2, ctx2, block, accepted=False, reason="duplicate")
 
             self.log.debug("A Block handle remains usable after its template is destroyed")
             assert_equal((await template_block.data(ctx)).result, block.serialize())
@@ -652,7 +652,7 @@ class IPCMiningTest(BitcoinTestFramework):
             assert_equal(check.result, False)
             assert_equal(check.reason, "inconclusive-not-best-prevblk")
             self.log.debug("submitBlock on the same node should fail with duplicate after submitSolution succeeds")
-            await self.assert_submit_block(mining, ctx, block, result=False, reason="duplicate")
+            await self.assert_submit_block(mining, ctx, block, accepted=False, reason="duplicate")
 
             self.log.debug("submitSolution should return duplicate after submitBlock succeeds")
             async with destroying((await mining2.createNewBlock(ctx2, self.default_block_create_options)).result, ctx2) as template2:
@@ -660,7 +660,7 @@ class IPCMiningTest(BitcoinTestFramework):
                 duplicate_coinbase = duplicate_block.vtx[0]
                 duplicate_block.solve()
                 self.log.debug("Submit a valid complete block before duplicate submitSolution")
-                await self.assert_submit_block(mining2, ctx2, duplicate_block, result=True)
+                await self.assert_submit_block(mining2, ctx2, duplicate_block, accepted=True)
                 self.nodes[2].waitforblockheight(current_block_height + 2)
                 self.log.debug("submitSolution should reject the duplicate block")
                 result = await template2.submitSolution(ctx2, duplicate_block.nVersion, duplicate_block.nTime, duplicate_block.nNonce, duplicate_coinbase.serialize())
@@ -695,7 +695,7 @@ class IPCMiningTest(BitcoinTestFramework):
                 # All three templates share a parent. The first block becomes
                 # active, so the remaining valid blocks are accepted as stale.
                 await self.assert_submit_block(
-                    mining2, ctx2, active_block, result=True)
+                    mining2, ctx2, active_block, accepted=True)
 
                 solution_coinbase = solution_block.vtx[0]
                 result = await solution_template.submitSolution(
@@ -710,7 +710,7 @@ class IPCMiningTest(BitcoinTestFramework):
                 assert_equal(result.debug, "")
 
                 await self.assert_submit_block(
-                    mining2, ctx2, submit_block, result=False, reason="inconclusive")
+                    mining2, ctx2, submit_block, accepted=False, reason="inconclusive")
             self.sync_all()
 
             self.log.debug("Submit the same invalid block twice")
@@ -724,7 +724,7 @@ class IPCMiningTest(BitcoinTestFramework):
                     mining2,
                     ctx2,
                     invalid_block,
-                    result=False,
+                    accepted=False,
                     reason="bad-txns-nonfinal",
                     debug="non-final transaction",
                 )
@@ -733,7 +733,7 @@ class IPCMiningTest(BitcoinTestFramework):
                     mining2,
                     ctx2,
                     invalid_block,
-                    result=False,
+                    accepted=False,
                     reason="duplicate-invalid",
                     debug=f"block {invalid_block.hash_hex} was previously marked invalid",
                 )
In commit 1f9fcfab45fa2bdd8296c265dfac2dd206a353bc "mining: return Block from Mining::submitBlock()" nit: <details> <summary>result -> accepted</summary> ```diff diff --git a/test/functional/interface_ipc_mining.py b/test/functional/interface_ipc_mining.py index e0c92c1b93..c6a46df37c 100755 --- a/test/functional/interface_ipc_mining.py +++ b/test/functional/interface_ipc_mining.py @@ -130,9 +130,9 @@ class IPCMiningTest(BitcoinTestFramework): block.hashMerkleRoot = block.calc_merkle_root() return block - async def assert_submit_block(self, mining, ctx, block, *, result, reason="", debug=""): + async def assert_submit_block(self, mining, ctx, block, *, accepted, reason="", debug=""): submit = await mining.submitBlock(ctx, block.serialize()) - assert_equal(submit.accepted, result) + assert_equal(submit.accepted, accepted) assert_equal((await submit.result.data(ctx)).result, block.serialize()) assert_equal(submit.reason, reason) assert_equal(submit.debug, debug) @@ -569,7 +569,7 @@ class IPCMiningTest(BitcoinTestFramework): mining2, ctx2, block, - result=False, + accepted=False, reason="bad-version(0x00000000)", debug="rejected nVersion=0x00000000 block", ) @@ -612,7 +612,7 @@ class IPCMiningTest(BitcoinTestFramework): mining2, ctx2, missing_witness_block, - result=False, + accepted=False, reason="bad-witness-nonce-size", debug="CheckWitnessMalleation : invalid witness reserved value size", ) @@ -624,10 +624,10 @@ class IPCMiningTest(BitcoinTestFramework): assert_equal(result.debug, "") self.log.debug("Submit a valid complete block through the disconnected node") - await self.assert_submit_block(mining2, ctx2, block, result=True) + await self.assert_submit_block(mining2, ctx2, block, accepted=True) assert_equal(self.nodes[2].getchaintips()[0]["height"], current_block_height + 1) self.log.debug("submitBlock should reject the duplicate complete block") - await self.assert_submit_block(mining2, ctx2, block, result=False, reason="duplicate") + await self.assert_submit_block(mining2, ctx2, block, accepted=False, reason="duplicate") self.log.debug("A Block handle remains usable after its template is destroyed") assert_equal((await template_block.data(ctx)).result, block.serialize()) @@ -652,7 +652,7 @@ class IPCMiningTest(BitcoinTestFramework): assert_equal(check.result, False) assert_equal(check.reason, "inconclusive-not-best-prevblk") self.log.debug("submitBlock on the same node should fail with duplicate after submitSolution succeeds") - await self.assert_submit_block(mining, ctx, block, result=False, reason="duplicate") + await self.assert_submit_block(mining, ctx, block, accepted=False, reason="duplicate") self.log.debug("submitSolution should return duplicate after submitBlock succeeds") async with destroying((await mining2.createNewBlock(ctx2, self.default_block_create_options)).result, ctx2) as template2: @@ -660,7 +660,7 @@ class IPCMiningTest(BitcoinTestFramework): duplicate_coinbase = duplicate_block.vtx[0] duplicate_block.solve() self.log.debug("Submit a valid complete block before duplicate submitSolution") - await self.assert_submit_block(mining2, ctx2, duplicate_block, result=True) + await self.assert_submit_block(mining2, ctx2, duplicate_block, accepted=True) self.nodes[2].waitforblockheight(current_block_height + 2) self.log.debug("submitSolution should reject the duplicate block") result = await template2.submitSolution(ctx2, duplicate_block.nVersion, duplicate_block.nTime, duplicate_block.nNonce, duplicate_coinbase.serialize()) @@ -695,7 +695,7 @@ class IPCMiningTest(BitcoinTestFramework): # All three templates share a parent. The first block becomes # active, so the remaining valid blocks are accepted as stale. await self.assert_submit_block( - mining2, ctx2, active_block, result=True) + mining2, ctx2, active_block, accepted=True) solution_coinbase = solution_block.vtx[0] result = await solution_template.submitSolution( @@ -710,7 +710,7 @@ class IPCMiningTest(BitcoinTestFramework): assert_equal(result.debug, "") await self.assert_submit_block( - mining2, ctx2, submit_block, result=False, reason="inconclusive") + mining2, ctx2, submit_block, accepted=False, reason="inconclusive") self.sync_all() self.log.debug("Submit the same invalid block twice") @@ -724,7 +724,7 @@ class IPCMiningTest(BitcoinTestFramework): mining2, ctx2, invalid_block, - result=False, + accepted=False, reason="bad-txns-nonfinal", debug="non-final transaction", ) @@ -733,7 +733,7 @@ class IPCMiningTest(BitcoinTestFramework): mining2, ctx2, invalid_block, - result=False, + accepted=False, reason="duplicate-invalid", debug=f"block {invalid_block.hash_hex} was previously marked invalid", ) ``` </details>
Sjors (Migrated from github.com) reviewed 2026-11-19 10:15:58 +00:00
Sjors (Migrated from github.com) commented 2026-11-19 10:15:58 +00:00

Taken, thanks.

Taken, thanks.
ismaelsadeeq commented 2026-11-19 11:00:09 +00:00 (Migrated from github.com)

Approach ACK

Approach ACK
ViniciusCestarii (Migrated from github.com) reviewed 2026-11-20 13:21:43 +00:00
ViniciusCestarii (Migrated from github.com) left a comment

Approach ACK

Plan to review.

Approach ACK Plan to review.
ViniciusCestarii (Migrated from github.com) reviewed 2026-11-30 19:54:32 +00:00
ViniciusCestarii (Migrated from github.com) commented 2026-11-30 19:32:36 +00:00

In "mining: add Block interface, return it from BlockTemplate::block()" 8649a6c2ea

Why name block instead of getBlock? The other BlockTemplate accessors all have get as prefix (getTxFees, getTxSigops, getCoinbaseTx) so this makes it the odd one out.

In "mining: add Block interface, return it from BlockTemplate::block()" 8649a6c2ea8f38530ddeef5c0e659d298c0fe30a Why name `block` instead of `getBlock`? The other `BlockTemplate` accessors all have get as prefix (`getTxFees`, `getTxSigops`, `getCoinbaseTx`) so this makes it the odd one out.
ViniciusCestarii (Migrated from github.com) commented 2026-11-30 19:35:26 +00:00

In "mining: add Block interface, return it from BlockTemplate::block()" 8649a6c2ea

nit: its type could be util::NotNullSharedPtr<const CBlock> to make it explicit that it can't be null and also makes it consistent with m_block_template.

In "mining: add Block interface, return it from BlockTemplate::block()" 8649a6c2ea8f38530ddeef5c0e659d298c0fe30a nit: its type could be `util::NotNullSharedPtr<const CBlock>` to make it explicit that it can't be null and also makes it consistent with `m_block_template`.
Sjors (Migrated from github.com) reviewed 2026-12-01 14:01:48 +00:00
Sjors (Migrated from github.com) commented 2026-12-01 14:01:48 +00:00

Because block() itself has a get() method which actually gets the block.

Because `block()` itself has a `get()` method which actually gets the block.
Sjors (Migrated from github.com) reviewed 2026-12-01 14:08:39 +00:00
Sjors (Migrated from github.com) commented 2026-12-01 14:08:39 +00:00

Done.

Done.
ViniciusCestarii (Migrated from github.com) reviewed 2026-12-01 20:39:27 +00:00
ViniciusCestarii (Migrated from github.com) commented 2026-12-01 20:39:27 +00:00

I assume you mean block() has data() that returns the block. So the convention is that methods starting with get return data while handles don't? By that logic shouldn't the block methods be getData(), getHeader(), getCoinbaseMerklePath()?

I assume you mean `block()` has `data()` that returns the block. So the convention is that methods starting with `get` return data while handles don't? By that logic shouldn't the `block` methods be `getData()`, `getHeader()`, `getCoinbaseMerklePath()`?
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!36525
No description provided.