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

pull Sjors wants to merge 5 commits into bitcoin:master from Sjors:2026/10/block-template-mutex changing 7 files +264 −88
  1. Sjors commented at 8:43 AM on October 14, 2026: member

    This PR catches two birds with one stone:

    • fixes #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.

  2. DrahtBot added the label Mining on Oct 14, 2026
  3. DrahtBot commented at 8:43 AM on October 14, 2026: contributor

    <!--e57a25ab6845829454e8d69fc972939a-->

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

    <!--006a51241073e994b41acfe9ec718e94-->

    External sites

    <!--021abf342d371248e50ceaed478a90ca-->

    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 <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:

    • #36451 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36451.svg"></sub> (refactor: Use NotNull for CreateNewBlock and pimpls by maflcko)
    • #36356 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36356.svg"></sub> (mining: move getblocktemplate cache into BlockTemplateManager by w0xlt)
    • #35671 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35671.svg"></sub> (mining: add TxCollection to bandwidth-efficiently validate external block templates by Sjors)
    • #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-11-19 10:16:15</sup>

  4. Sjors force-pushed on Oct 14, 2026
  5. DrahtBot added the label CI failed on Oct 14, 2026
  6. DrahtBot removed the label CI failed on Oct 14, 2026
  7. ismaelsadeeq commented at 4:44 AM on October 15, 2026: member

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

  8. Sjors commented at 5:24 AM on October 15, 2026: member

    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.

  9. Sjors commented at 5:58 AM on October 15, 2026: member

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

  10. w0xlt commented at 6:06 AM on October 15, 2026: contributor

    Concept ACK

  11. ismaelsadeeq commented at 7:26 AM on October 15, 2026: 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.

  12. enochaz commented at 9:07 AM on October 15, 2026: contributor

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

  13. Sjors commented at 12:35 AM on October 16, 2026: member

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

    • use timeout_factor to avoid false positive failures
    • improve cleanup
  14. ismaelsadeeq approved
  15. ismaelsadeeq commented at 4:37 AM on October 16, 2026: member

    reACK cbadeff334f182086538d7483dc1146c559859e6

  16. DrahtBot requested review from enochaz on Oct 16, 2026
  17. w0xlt commented at 10:48 PM on October 20, 2026: contributor

    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](/bitcoin-bitcoin/contributor/param/)[in] hash_prev_block Parent block hash of the previous template.
    +     *                            The chain tip must already be set.
          * [@param](/bitcoin-bitcoin/contributor/param/)[in] current_fees Total transaction fees in the previous template, in satoshis.
          * [@param](/bitcoin-bitcoin/contributor/param/)[in] wait_options Timeout and minimum fee increase relative to current_fees.
          * [@param](/bitcoin-bitcoin/contributor/param/)[in] create_options Options used to create the next block template.
    
  18. Sjors commented at 3:54 AM on October 21, 2026: member

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

  19. sedited commented at 9:59 AM on October 21, 2026: contributor

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

  20. ismaelsadeeq commented at 10:25 AM on October 21, 2026: member

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

  21. w0xlt commented at 4:47 PM on October 21, 2026: 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.

  22. Sjors commented at 5:32 AM on October 24, 2026: member

    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.

  23. ismaelsadeeq commented at 6:16 AM on October 25, 2026: member

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

  24. Sjors commented at 10:03 AM on October 25, 2026: member

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

  25. sedited commented at 10:22 AM on October 25, 2026: contributor

    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?

  26. Sjors commented at 4:35 AM on October 26, 2026: member

    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.

  27. sedited commented at 10:05 AM on October 28, 2026: contributor

    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.

  28. Sjors commented at 8:17 AM on October 29, 2026: member

    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.

  29. Sjors commented at 9:19 AM on October 29, 2026: member

    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.

  30. DrahtBot added the label Needs rebase on Nov 5, 2026
  31. Sjors force-pushed on Nov 6, 2026
  32. Sjors commented at 7:49 AM on November 6, 2026: member

    Rebased after #36192.

  33. DrahtBot removed the label Needs rebase on Nov 6, 2026
  34. ViniciusCestarii commented at 2:50 PM on November 10, 2026: contributor

    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.

  35. Sjors commented at 5:03 PM on November 11, 2026: member

    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.

  36. ViniciusCestarii commented at 9:58 PM on November 11, 2026: 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.

  37. ViniciusCestarii commented at 11:08 AM on November 16, 2026: 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](/bitcoin-bitcoin/contributor/0/) (context :Proxy.Context) -> ();
        getBlock [@1](/bitcoin-bitcoin/contributor/1/) (context: Proxy.Context) -> (result: Data);
    }
    
    submitSolution [@10](/bitcoin-bitcoin/contributor/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.

  38. DrahtBot added the label Needs rebase on Nov 16, 2026
  39. Sjors force-pushed on Nov 18, 2026
  40. Sjors commented at 1:00 PM on November 18, 2026: member

    Rebased after #36451. @ViniciusCestarii looking into your approach

  41. DrahtBot removed the label Needs rebase on Nov 18, 2026
  42. test: exercise concurrent IPC block template access
    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 <48946461+ismaelsadeeq@users.noreply.github.com>
    Co-authored-by: ViniciusCestarii <viniciuscestari01@gmail.com>
    ac491a1429
  43. mining: move header and coinbase merkle path to Block
    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.
    4eed0dff2a
  44. Sjors force-pushed on Nov 18, 2026
  45. Sjors renamed this:
    mining: add getTotalFees(), protect m_block_template with mutex
    mining: add Block interface, fix template data race
    on Nov 18, 2026
  46. Sjors commented at 2:53 PM on November 18, 2026: member

    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.

  47. in test/functional/interface_ipc_mining.py:136 in 1f9fcfab45
     131 | @@ -132,7 +132,8 @@ async def build_candidate_block(self, template, ctx, extra_nonce=b""):
     132 |  
     133 |      async def assert_submit_block(self, mining, ctx, block, *, result, reason="", debug=""):
     134 |          submit = await mining.submitBlock(ctx, block.serialize())
     135 | -        assert_equal(submit.result, result)
     136 | +        assert_equal(submit.accepted, result)
     137 | +        assert_equal((await submit.result.data(ctx)).result, block.serialize())
    


    xyzconstant commented at 2:22 AM on November 19, 2026:

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

    nit:

    <details> <summary>result -> accepted</summary>

    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 commented at 10:15 AM on November 19, 2026:

    Taken, thanks.

  48. xyzconstant commented at 2:50 AM on November 19, 2026: contributor

    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.

  49. mining: return Block from submitSolution(), keep template unchanged
    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 #36515.
    
    Co-authored-by: ViniciusCestarii <viniciuscestari01@gmail.com>
    64d07ce0e1
  50. mining: add Block interface, return it from BlockTemplate::block()
    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 <viniciuscestari01@gmail.com>
    8649a6c2ea
  51. mining: return Block from Mining::submitBlock()
    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.
    494b4869e9
  52. Sjors force-pushed on Nov 19, 2026
  53. ismaelsadeeq commented at 11:00 AM on November 19, 2026: member

    Approach ACK

  54. DrahtBot added the label CI failed on Nov 19, 2026
  55. ViniciusCestarii commented at 1:21 PM on November 20, 2026: contributor

    Approach ACK

    Plan to review.


github-metadata-mirror

This is a metadata mirror of the GitHub repository bitcoin/bitcoin. This site is not affiliated with GitHub. Content is generated from a GitHub metadata backup.
generated: 2026-11-20 15:51 UTC

This site is hosted by @0xB10C
More mirrored repositories can be found on mirror.b10c.me