Repository navigation
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
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.
2026-12-01 14:09:11 |
c238689 to
4774cf1
Compare
ismaelsadeeq
left a comment
There was a problem hiding this comment.
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()|
The vector was initially introduced for (internal) compatibility with the
I haven't done an inventory of software out there that uses the fees from We definitely need the internal total. Providing the total and individual via IPC is trivial, so I think we should keep it. |
It works and I'm open to taking it, but failure isn't deterministic (just very likely with the 100 iterations). |
|
Concept ACK |
Indeed, it is not deterministic but is sure to fail at some point. |
There was a problem hiding this comment.
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)
|
Added the test in a new commit, with some adjustments:
|
There was a problem hiding this comment.
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.|
@w0xlt I prefer the existing wording:
The function doesn't know where the caller got its hash. |
|
Might it be preferable to make |
|
AFAICT no, so we could do that and make the template const, that way no race and we copy when mutating for submission. |
I think it's a preferable solution. With no writes after construction there's no race, and since 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 ( |
Yes. Both existing clients call
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. |
|
Could we just return the block copy after applying the solution? |
|
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 That said, I don’t feel strongly about. I am fine with it being a future follow up. |
|
I tried another approach: Benchmarked it and got no performance regression with this approach. Draft: Bitcoin Core diff: ViniciusCestarii@5c7fe8e This gets the immutable template without the regression and without waiting for the libmultiprocess improvements. Happy to open it as a followup PR. |
1e521cb to
9c85ea0
Compare
|
Rebased after #36451. @ViniciusCestarii looking into your approach |
9c85ea0 to
bb7652c
Compare
|
I added a new The 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 I'm keeping The chain interface proposed in #29409 might also be able to use this. I renamed This is a breaking change and I intentionally made 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
left a comment
There was a problem hiding this comment.
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.
| 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()) |
There was a problem hiding this comment.
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",
)bb7652c to
4eed0df
Compare
|
Approach ACK |
ViniciusCestarii
left a comment
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Because block() itself has a get() method which actually gets the block.
There was a problem hiding this comment.
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()?
| } | ||
|
|
||
| private: | ||
| const std::shared_ptr<const CBlock> m_block; |
There was a problem hiding this comment.
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.
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]>
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]>
4eed0df to
283d5ae
Compare
|
Fuzzed 283d5ae through the Mining IPC interface with fuzzamoto (oss-garage/fuzzamoto#164 (comment)), with a scenario ported to the new
The scenario only covers the IPC side, not the RPC paths this PR changes. |

This PR catches two birds with one stone:
m_block_templatemembers #36515Blockinterface, 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'sCBlockfor this.Block interface
submitSolution()no longer modifies the template. It applies the solution to a copy of the template block and returns aBlockhandle for that copy, also when the block is rejected.Mining::submitBlock()andBlockTemplate::block()do the same. The new interface has adata(),header()andcoinbaseMerklePath()method, so these are migrated from theBlockTemplateinterface.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:The extra
block()call costs about 0.15 ms per template for a C++ client. The alternative approach of havingsubmitSolution()return the fullCBlockadded 6ms.Memory
A
Blockhandle keeps the template's memory, including its transactions, allocated until the client destroys the handle. This also applies to handles returned bysubmitSolution()andsubmitBlock(). This doesn't matter much in practice since (the existing) clients don't hold on to aBlocklong.