Skip to content

mining: add precious option to IPC block submission - #35300

Open
w0xlt wants to merge 7 commits into
bitcoin:masterfrom
w0xlt:ipc-submit-block-precious
Open

w0xlt wants to merge 7 commits into
bitcoin:masterfrom
w0xlt:ipc-submit-block-precious

Conversation

@w0xlt

@w0xlt w0xlt commented May 16, 2026

Copy link
Copy Markdown
Contributor

This PR adds a precious flag to the IPC Mining submitBlock and submitSolution methods, as suggested in #34644 (comment). Built on top #34644.

With this change, IPC mining clients can submit and prefer a block in one IPC call, instead of submitting it over IPC and then using the preciousblock RPC separately.

By default, same-work side blocks keep the existing behavior: submitBlock reports duplicate/inconclusive cases as failure with a reason, while submitSolution continues to return true when ProcessNewBlock accepts or already knows the block.

Includes unit and IPC functional coverage for default behavior, precious reorgs, active-tip no-op submissions, and invalid-block rejection.

@DrahtBot

DrahtBot commented May 16, 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
Concept ACK Sjors, pablomartin4btc, ViniciusCestarii, johnnyasantoss, enirox001

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:

  • #36469 (refactor: deduplicate block validation state catcher by enirox001)
  • #36097 (mining: replace interrupt methods with cancellation arguments by xyzconstant)
  • #36074 (scripted-diff: [test] Add util/check.h includes for assertions by maflcko)
  • #35671 (mining: add TxCollection to bandwidth-efficiently validate external block templates by Sjors)
  • #33922 (mining: add getMemoryLoad() and track template non-mempool memory footprint by Sjors)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

@w0xlt
w0xlt marked this pull request as draft May 16, 2026 03:23
@w0xlt
w0xlt force-pushed the ipc-submit-block-precious branch from 4573232 to a02e97d Compare May 16, 2026 04:02
@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/25951528963/job/76290253269
LLM reason (✨ experimental): CI failed due to a C++ build error: src/node/miner.cpp would not compile (clang: passing CBlockIndex* where const CBlockIndex& is required in chainman.ActiveChain().Contains).

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

@Sjors

Sjors commented May 16, 2026

Copy link
Copy Markdown
Member

Maybe do this after #34672?

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

Concept ACK

There's some game theory miners should contemplate before using this though:

It's clearly rational to prefer your own block for p2p relay1, but it's less obvious that you should mine the next block on it.

That might be a sunk-cost fallacy. If you saw the other block first, it's a good assumption that the rest of the network also saw it first. If the majority of hash rate is mining on the other side, and if you (the miner, not the pool) can't tip that majority over, it may be a waste of hash power.

In a Job Declaration scenario, the main criterion for which block to build on should be the side of the fork the pool picked. Unfortunately afaik the sv2 protocol doesn't currently communicate that (cc @plebhash).

Footnotes

  1. which could be achieved with some special handling where we briefly switch tip to validate, broadcast and then switch back to the first-seen tip. ↩

Comment thread src/test/miner_tests.cpp Outdated
BOOST_REQUIRE_EQUAL(ActiveTipHash(m_node), side_block.GetHash());

// Re-submitting the active tip with precious=true is a no-op reorg, but
// the block is validated/connected so submitBlock should report success.

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.

In a1f8966 test: cover precious mining submissions: mmm, I don't think precious should change the behavior if the block is duplicate, so just return duplicate?

Similarly, if we already had it, but it wasn't the tip, and we then switch the tip over, duplicate still seems like the correct response.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done. Thanks.

Comment thread src/test/miner_tests.cpp Outdated
// Submitting a brand-new same-work block with precious=true on the first
// try (no prior precious=false store) should still reorg to it. This
// exercises the path where AcceptBlock stores a fresh block and
// PreciousBlock immediately promotes it.

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.

In a1f8966 test: cover precious mining submissions: this seems to be the main use case, so maybe cover it at the start of the test?

In general this test is massive, so maybe split it?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done. Thanks.

Comment thread src/test/miner_tests.cpp Outdated
BOOST_REQUIRE_EQUAL(ActiveTipHash(m_node), tip_before_invalid);
}

BOOST_AUTO_TEST_CASE(SubmitSolution_precious)

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.

In a1f8966 test: cover precious mining submissions: since we expect more or less the same behavior as SubmitBlock, perhaps it's better to interleave the test? (and then have separate tests for each scenario, rather than for each method)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done. Thanks.

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

Concept ACK

Adding precious=true to submitBlock and submitSolution, allows IPC mining clients atomically submit and prefer a same-work block in one go instead of a separate preciousblock RPC call.

The ActivateBestChain_ refactor is a clean prerequisite (so in commit 2 PreciousBlock can call it directly).

Left some nits (none blocking).

Comment thread test/functional/interface_ipc_mining.py Outdated

async def assert_submit_block(self, mining, ctx, block, *, result, reason="", debug=""):
submit = await mining.submitBlock(ctx, block.serialize())
def make_block_variant(self, block, coinbase, extra_nonce):

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.

nit: make_block_variant, assert_chain_tip, and assert_submit_block none of them access self — all should be @staticmethod

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done. Thanks.

Comment thread src/rpc/blockchain.cpp

BlockValidationState state;
chainman.ActiveChainstate().PreciousBlock(state, pblockindex);
bool connected{false};

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.

nit: connected is silently unused. A [[maybe_unused]] attribute or a brief comment (// RPC callers don't need to distinguish connected vs not) would help the next reader I think...

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done. Thanks.

Comment thread src/interfaces/mining.h Outdated
*
* @returns true if the block was accepted as a new block
* @returns true if the block was accepted as a new block. With precious,
* an already-known block may return true if it is connected.

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.

nit: perhaps worth clarifying that this includes blocks that are ancestors of the active tip, not just the tip itself, so callers don't assume result=true implies a reorg occurred? (If I understand it correctly)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done. Thanks.

Comment thread src/interfaces/mining.h Outdated
Comment on lines +185 to +187
* the validation result is inconclusive. With precious,
* an already-known block may return true if it is
* validated/connected.

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.

nit: same as the above.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done. Thanks.

@w0xlt

w0xlt commented Sep 22, 2026

Copy link
Copy Markdown
Contributor Author

Rebased. All suggestions addressed. Ready for review.

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

Concept ACK

Reviewed with @johnnyasantoss.

That might be a sunk-cost fallacy. If you saw the other block first, it's a good assumption that the rest of the network also saw it first. If the majority of hash rate is mining on the other side, and if you (the miner, not the pool) can't tip that majority over, it may be a waste of hash power.

There's no issue with the majority of the hash rate on the other side because a miner (or pool) is always mining against the rest of the network hash rate. So the odds of finding the next block are the same on either side, only the payout differs: 2 blocks on your own tip vs 1 on the other.

@johnnyasantoss

Copy link
Copy Markdown

Concept ACK 22aeff7

I've reviewed the code but I'm not that confident in my cpp skills so I'll refrain from commenting it.


That might be a sunk-cost fallacy. If you saw the other block first, it's a good assumption that the rest of the network also saw it first. If the majority of hash rate is mining on the other side, and if you (the miner, not the pool) can't tip that majority over, it may be a waste of hash power.

cc @Sjors @0xB10C

Ran some thought experiments together with @ViniciusCestarii to understand whether precious=true always would be ideal. Thinking with context from this tweet1 regarding deep reorg viabtc vs. antpool2.

Seems it would be extremely unlikely to lose reward from working on a template on top of your own past work. Given that if the network finds a block the miner would revert to it and switch the template to the new best chain.

image

The miner would have to find an alternative block in the same timing as the rest of the network and then find another subsequent block on right after the network extends the other chain(!) to then get reorg'd and lose work. This seems like a black swan event. Chances of finding a block are related to hashrate and not prevhash so there's no waste in doubling down on your template AFAICT. Your odds at prevhash 0A and 0B are the same.
Electricity spent trying to find 1A and finding 1B would be the same regardless if the network sends you 1B, but on the other side reward finding 1A is roughly twice of that working on 1B.

maybe there's something we are not grasping, but intuitively precious=true makes a lot of sense.

Footnotes

  1. https://x.com/0xB10C/status/1804143652962185531 ↩

  2. https://b10c.me/blog/014-mining-pool-behavior-during-forks/ ↩

@0xB10C

0xB10C commented Sep 29, 2026

Copy link
Copy Markdown
Contributor

I don't have the full context of the PR, but I agree with @johnnyasantoss @ViniciusCestarii here. If you don't mine on your own block, the maximum you can win is the next block. If you mine on your own block, you can win the last and the next block. Chances of finding the next block don't change, in both cases it's equal to your share of network hashrate.

fanquake added a commit that referenced this pull request Oct 3, 2026
15d0926 rpc: clarify preciousblock help text (ViniciusCestarii)

Pull request description:

  The preciousblock help says only "Treats a block as if it were received before others with the same work". This isn't wrong but could be clearer and it also leaves out cases that confuse users, including me (see discussion in #35300):

  - The call has no effect when the block has less work than the current tip, and that includes any ancestor of the tip. A successful return doesn't mean the tip changed. ([code](https://github.com/bitcoin/bitcoin/blob/69142eacd1374925cc9e4ea736c21fcec16307d0/src/validation.cpp#L3504-L3507))
  - It only breaks ties between equal-work chains and doesn't pin the chain. If another chain gains more work, the node switches to it as usual. ([code](https://github.com/bitcoin/bitcoin/blob/69142eacd1374925cc9e4ea736c21fcec16307d0/src/node/blockstorage.cpp#L174-L182))

  This adds both points to the help text and doesn't change any behavior.

ACKs for top commit:
  instagibbs:
    ACK 15d0926
  maflcko:
    lgtm ACK 15d0926

Tree-SHA512: cc2bc740bb0e9ebc442b35b31b59b6f5ec56da23a555352e1491d98684d1722617e18072e05807e95be23b8a14ddd20aed01d67fae42c45cb2c788b1f999dc8a
w0xlt added 7 commits October 8, 2026 16:50
Move the lock-held body of ActivateBestChain() into an internal helper without changing behavior. This allows callers that already hold m_chainstate_mutex to run activation without releasing and reacquiring it.
Hold m_chainstate_mutex while marking a block precious, activating the
best chain, and capturing whether the block is in the active chain.
Use ActivateBestChain_ so this sequence does not release and reacquire
the lock.

Return this status through the connected output so mining submissions
can inspect the result without racing another chain activation.

Adapt the preciousblock RPC and document why it ignores connected,
as suggested by pablomartin4btc.
Add a precious flag to the Mining IPC submitBlock and submitSolution
methods so callers can prefer a submitted block over competing blocks
with the same work.

Use the connected result from PreciousBlock to determine whether a new
block entered the active chain.

Preserve false with reason="duplicate" for already-known blocks, including
when precious changes the active tip, as suggested by Sjors. Report
captured validation failures ahead of the duplicate fallback.

Clarify that a successfully submitted new block may be an ancestor of
the active tip and that success does not imply a reorganization,
addressing pablomartin4btc's review suggestion.

Follow the explicit-error versioning pattern discussed by Sjors and
ryanofsky: use new Cap'n Proto ordinals for the updated methods and
retain the old signatures as deprecated entry points that direct
clients to update. This prevents older servers from silently ignoring
the precious argument.
Exercise submitBlock and submitSolution together in five independent
regtest scenarios, with fresh chain state for each method. Cover first
submission of a new same-work precious block, duplicate submissions,
lower-work blocks, activation failures, and invalid blocks.

Following Sjors's review, put the first-submission scenario at the start
and share scenario assertions across both APIs. Check that known blocks
remain duplicates even when making them precious changes the active tip.

Check the deprecated submitSolution error message as well as the
exception type, following DrahtBot's review suggestion.
Exercise precious submission through both IPC methods, including the
default behavior for side blocks with the same work, first submissions,
duplicate activation, and invalid-block rejection.

Check that already-known blocks report duplicate even when precious
changes the active tip, as requested by Sjors. Make the three stateless
test helpers static methods, as suggested by pablomartin4btc.

Check explicit update errors from both deprecated submission methods,
following the versioning pattern discussed by Sjors and ryanofsky.

Name the precious boolean arguments in the IPC calls, as suggested by
DrahtBot, so the tests make the requested behavior explicit.
Describe the precious option, acceptance of new blocks, and validation
results for IPC mining clients. Document that duplicate submissions
retain reason="duplicate" even when precious changes the active tip,
consistent with Sjors's review.

Document the new method ordinals, regenerated bindings, and explicit
update errors for clients calling the deprecated methods.
@DrahtBot

Copy link
Copy Markdown
Contributor

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

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

Concept ACK

This is nice to have. Did an initial pass through, and I understand how this works and the potential use cases for it. Allowing an ipc mining client to submit a block and request that it be preferred over a competing same work block in one call seems useful, especially when a competing block arrives just before the client submits its own solution. I intend to look into the implementation again.

Although, as discussed above, the incentives for preferring your own block and continuing to mine on it might not be that strong, or at least might depend on the miner’s setup and the pool’s choice of tip.

Are there any downstream clients currently requesting this or that have a clear use for this feature? It would be useful to understand how they intend to use the precious option and whether having it available directly through ipc addresses a limitation they are currently running into.

The change seems fairly small, but it is not entirely free. Both Mining.submitBlock and BlockTemplate.submitSolution move to new ordinals, and the previous methods now return explicit errors directing clients to update. Existing clients would therefore need to regenerate their bindings and update their calls. I think having a concrete downstream use case would help justify that compatibility cost

Left some nits

// Preserve duplicate reporting even if making the block precious
// changed the active tip.
reason = "duplicate";
} else if (!accepted && (!sc->m_found || sc->m_state.IsValid())) {

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 0cd41ab: mining: add precious IPC block submission option

here the code has two separate checks, such that if processing failed or we could not establish that the block connected we report inconclusive, i believe we can combine these into a single check since a check above already handles an invalid captured result

something like this

index 713ae6a04d..0a3b73b823 100644
--- a/src/node/block_template_manager.cpp
+++ b/src/node/block_template_manager.cpp
@@ -121,15 +121,9 @@ bool BlockTemplateManager::SubmitBlock(const std::shared_ptr<const CBlock>& bloc
             // Preserve duplicate reporting even if making the block precious
             // changed the active tip.
             reason = "duplicate";
-        } else if (!accepted && (!sc->m_found || sc->m_state.IsValid())) {
-            // ProcessNewBlock can fail without a validation result, for example
-            // from an activation or system error. It can also fail after a valid
-            // BlockChecked result. In these cases the validation result is
-            // inconclusive.
-            reason = "inconclusive";
-        } else if (!sc->m_found && !precious_connected) {
-            // The block was accepted but not connected, for example if it does
-            // not have more work than the current tip.
+        } else if (!accepted || (!sc->m_found && !precious_connected)) {
+            // Processing failed without a conclusive validation error,
+            // or the block was accepted but not connected.
             reason = "inconclusive";
         }
     }

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants