Skip to content

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

Open
Sjors wants to merge 5 commits into
bitcoin:masterfrom
Sjors:2026/10/block-template-mutex
Open

Sjors wants to merge 5 commits into
bitcoin:masterfrom
Sjors:2026/10/block-template-mutex

Conversation

@Sjors

@Sjors Sjors commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

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.

@DrahtBot

DrahtBot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

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

External sites

Reviews

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

Type Reviewers
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

@ismaelsadeeq ismaelsadeeq left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK 4774cf1

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 --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()

@Sjors

Sjors commented Oct 15, 2026 •

Copy link
Copy Markdown
Member Author

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

Sjors commented Oct 15, 2026

Copy link
Copy Markdown
Member Author

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

w0xlt commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

@ismaelsadeeq

Copy link
Copy Markdown
Member

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.

@enochaz enochaz left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK 4774cf1

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, repeating each submission setting (100, 150, 200 and 300) 25 times. Without the mutex fix, every run detected the race. With the fix, every run 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 arm)

@Sjors

Sjors commented Oct 16, 2026

Copy link
Copy Markdown
Member Author

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

  • use timeout_factor to avoid false positive failures
  • improve cleanup

@ismaelsadeeq ismaelsadeeq left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reACK cbadeff

@DrahtBot
DrahtBot requested a review from enochaz October 16, 2026 04:37

@enochaz enochaz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reACK cbadeff

@w0xlt w0xlt left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK cbadeff

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.

@Sjors

Sjors commented Oct 21, 2026

Copy link
Copy Markdown
Member Author

@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

sedited commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

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

@ismaelsadeeq

Copy link
Copy Markdown
Member

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

@w0xlt

w0xlt commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

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

Sjors commented Oct 24, 2026 •

Copy link
Copy Markdown
Member Author

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

Copy link
Copy Markdown
Member

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

@ViniciusCestarii

Copy link
Copy Markdown
Contributor

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

Copy link
Copy Markdown
Contributor

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: ViniciusCestarii@5c7fe8e
sv2-tp diff: ViniciusCestarii/sv2-tp@7faa751

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

@Sjors
Sjors force-pushed the 2026/10/block-template-mutex branch from 1e521cb to 9c85ea0 Compare November 18, 2026 13:00
@Sjors

Sjors commented Nov 18, 2026 •

Copy link
Copy Markdown
Member Author

Rebased after #36451.

@ViniciusCestarii looking into your approach

Add Block::header() and Block::coinbaseMerklePath(), replacing
BlockTemplate::getBlockHeader() and getCoinbaseMerklePath().

In mining.capnp the old ordinals, BlockTemplate @1 and @6, become
getBlockHeaderOld1 and getCoinbaseMerklePathOld6, deprecated stubs that
return an error.
@Sjors
Sjors force-pushed the 2026/10/block-template-mutex branch from 9c85ea0 to bb7652c Compare November 18, 2026 14:51
@Sjors Sjors changed the title mining: add getTotalFees(), protect m_block_template with mutex mining: add Block interface, fix template data race Nov 18, 2026
@Sjors

Sjors commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

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 #35671 (comment)) with the fix for #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.

@nullfail nullfail left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review 1f9fcfa

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.

Comment thread test/functional/interface_ipc_mining.py Outdated
Comment on lines +133 to +136
async def assert_submit_block(self, mining, ctx, block, *, result, reason="", debug=""):
submit = await mining.submitBlock(ctx, block.serialize())
assert_equal(submit.result, result)
assert_equal(submit.accepted, result)
assert_equal((await submit.result.data(ctx)).result, block.serialize())

@nullfail nullfail Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In commit 1f9fcfa "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",
                 )

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Taken, thanks.

@Sjors
Sjors force-pushed the 2026/10/block-template-mutex branch from bb7652c to 4eed0df Compare November 19, 2026 10:15
@ismaelsadeeq

Copy link
Copy Markdown
Member

Approach ACK

@ViniciusCestarii ViniciusCestarii left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approach ACK

Plan to review.

submitSolution @10 (context: Proxy.Context, version: UInt32, timestamp: UInt32, nonce: UInt32, coinbase :Data) -> (reason: Text, debug: Text, result: Bool);
waitNext @8 (context: Proxy.Context, options: BlockWaitOptions) -> (result: BlockTemplate);
interruptWait @9() -> ();
block @11 (context: Proxy.Context) -> (result: Block);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()?

Comment thread src/node/interfaces.cpp Outdated
}

private:
const std::shared_ptr<const CBlock> m_block;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Sjors and others added 4 commits December 1, 2026 05:06
Add interfaces::Block, a handle to a block whose data() method returns
the full block. BlockTemplate::block() returns such a handle and
replaces getBlock().

In mining.capnp block() takes a new ordinal, @11. The old ordinal, @2,
becomes getBlockOld2, a deprecated stub that returns an error.

The handle shares the block with its template, so it reflects
modifications made by submitSolution(). A later commit will stop
submitSolution() from modifying the template.

A Block handle keeps the template's memory, including its transactions,
allocated until the client destroys the handle.

Co-authored-by: ViniciusCestarii <[email protected]>
submitBlock() returns a handle to the submitted block, also when the
block is rejected, and reports acceptance through a new accepted output.

In mining.capnp the new signature takes a new ordinal, @10. The old
ordinal, @7, becomes submitBlockOld7, a deprecated stub that returns an
error.
submitSolution() applies the solution to a copy of the template block
instead of modifying the template. It returns a handle to that copy,
also when the block is rejected, and reports acceptance through a new
accepted output. A null coinbase now throws instead of returning false.

The template no longer changes after creation, so IPC calls on
different worker threads can't race when one of them submits a solution.

In mining.capnp the new signature takes a new ordinal, @12. The old
ordinal, @10, becomes submitSolutionOld10, a deprecated stub that
returns an error.

Fixes bitcoin#36515.

Co-authored-by: ViniciusCestarii <[email protected]>
Read a template while submitting solutions through a separate IPC worker
thread to cover races between the getters and submitSolution(), and
check that the template header and block never change. Repeat
submissions to increase the chance of detecting a race under
ThreadSanitizer.

Bound the scenario and template cleanup using timeout_factor, and cancel
and await both concurrent tasks before destroying the template.

Co-authored-by: Abubakar Sadiq Ismail <[email protected]>
Co-authored-by: ViniciusCestarii <[email protected]>
@ryanofsky

Copy link
Copy Markdown
Contributor

Fuzzed 283d5ae through the Mining IPC interface with fuzzamoto (oss-garage/fuzzamoto#164 (comment)), with a scenario ported to the new Block interface (https://github.com/ryanofsky/fuzzamoto/commits/ipc-mining-36525.1), and found no problems:

  • 2 hours of TSan and 2 hours of ASan with no reports. On master the same scenario finds #36515 in about 30 minutes, including a second form where two submitSolution calls race on the coinbase shared_ptr; with this PR the fuzzing corpus reaches the pattern that raced 159 times without a report.
  • Block objects stay usable after their template is destroyed, calls after Block.destroy() fail cleanly, and destroy() during other calls is rejected, both by the existing libmultiprocess checks.
  • Mining works through the new API: 302 inputs in the corpus mine a block through the new submitSolution.

The scenario only covers the IPC side, not the RPC paths this PR changes.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ipc: data race on m_block_template members

9 participants