validation: Ensure Invalid ValidationState has result #36318

Open
optout21 wants to merge 5 commits from 2609-invalid-must-have-reason into master AGit
optout21 commented 2026-09-23 11:51:17 +00:00 (Migrated from github.com)

Block and transaction validation results are represented in ValidationState, and invalid results in "Invalid" states. Invalid validation results have a result, an enum value, and a reject_reason, a structured string.

The change is to ensure that an invalid result always has a set result and reject reason. This increases code robustness/security.

One instance was identified where the result was not set, and is being fixed by a new BLOCK_INCONCLUSIVE result. PR #31981 moved a previous-block check from outside of TestBlockValidity() to inside it, and introduced a new usage of BlockValidationState with unset result. The result field is not checked outside. This instance is changed now to use the newly-introduced BLOCK_INCONCLUSIVE value.

The new enum value is added to the kernel C API and its C++ wrapper. In P2P, a BLOCK_INCONCLUSIVE result does not lead to punishing the peer.

A few test-only instances with empty reject reason are changed to use a dummy value ("dummy-reason").

History: this was found on the side of #35570, but left untouched there; see https://github.com/bitcoin/bitcoin/pull/35570#issuecomment-5739477357 and https://github.com/bitcoin/bitcoin/pull/35570#discussion_r4075379069.

Alternatives considered:

  1. Use a new reject reason enum. This is the cleanest solution, but the cost is the extension of a widely-used validation enum.
  2. Use a different mechanism for returning this specific case from TestBlockValidity(), e.g. using util::Expected, as you discussed. No need to touch the BlockValidationResult enum. However, in the call sites of TestBlockValidity(), the reject reason and debug strings are handled similarly to other non-valid check results, and they would need a special handling.
  3. Reuse an exisiting reject reason enum value in TestBlockValidity(), with the comment "only in this spot it means a little different thing".
  4. Create a special TestBlockValidationResult, "on top of" BlockValidationResult, with the extra value, and a special TestBlockValidationState (ValidationState<TestBlockValidationResult>). Use this in TestBlockValidity(). As this is used only internally, within this methods and at its call sites, the new value+state doesn't have to be exposed. Therefore the change has lower impact.
Block and transaction validation results are represented in `ValidationState`, and invalid results in "Invalid" states. Invalid validation results have a `result`, an enum value, and a `reject_reason`, a structured string. The change is to ensure that an __invalid result always has a set result and reject reason__. This increases code robustness/security. One instance was identified where the result was not set, and is being fixed by a new `BLOCK_INCONCLUSIVE` result. PR #31981 moved a previous-block check from outside of `TestBlockValidity()` to inside it, and introduced a new usage of `BlockValidationState` with unset result. The result field is not checked outside. This instance is changed now to use the newly-introduced `BLOCK_INCONCLUSIVE` value. The new enum value is added to the kernel C API and its C++ wrapper. In P2P, a `BLOCK_INCONCLUSIVE` result does not lead to punishing the peer. A few test-only instances with empty reject reason are changed to use a dummy value ("dummy-reason"). History: this was found on the side of #35570, but left untouched there; see https://github.com/bitcoin/bitcoin/pull/35570#issuecomment-5739477357 and https://github.com/bitcoin/bitcoin/pull/35570#discussion_r4075379069. Alternatives considered: 1. Use a new reject reason enum. This is the cleanest solution, but the cost is the extension of a widely-used validation enum. 2. Use a different mechanism for returning this specific case from `TestBlockValidity()`, e.g. using `util::Expected`, as you discussed. No need to touch the `BlockValidationResult` enum. However, in the call sites of `TestBlockValidity()`, the reject reason and debug strings are handled similarly to other non-valid check results, and they would need a special handling. 3. Reuse an exisiting reject reason enum value in `TestBlockValidity()`, with the comment "only in this spot it means a little different thing". 4. Create a special `TestBlockValidationResult`, "on top of" `BlockValidationResult`, with the extra value, and a special `TestBlockValidationState` (`ValidationState<TestBlockValidationResult>`). Use this in `TestBlockValidity()`. As this is used only internally, within this methods and at its call sites, the new value+state doesn't have to be exposed. Therefore the change has lower impact.
DrahtBot commented 2026-09-23 11:51:26 +00:00 (Migrated from github.com)

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

External sites

Reviews

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

Type Reviewers
Concept ACK sedited
Stale ACK Pranav-error, hodlinator, Sjors, mzumsande, l0rinc

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:

  • #36852 (test: split CreateNewBlock_validity into independent test cases by yuvicc)
  • #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.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/36318 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36318.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36318#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | Concept ACK | [sedited](https://github.com/bitcoin/bitcoin/pull/36318#issuecomment-7381018541) | | Stale ACK | [Pranav-error](https://github.com/bitcoin/bitcoin/pull/36318#issuecomment-6835084024), [hodlinator](https://github.com/bitcoin/bitcoin/pull/36318#pullrequestreview-6109623463), [Sjors](https://github.com/bitcoin/bitcoin/pull/36318#issuecomment-7307901627), [mzumsande](https://github.com/bitcoin/bitcoin/pull/36318#pullrequestreview-6134485812), [l0rinc](https://github.com/bitcoin/bitcoin/pull/36318#pullrequestreview-6153292331) | 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: * [#36852](https://github.com/bitcoin/bitcoin/pull/36852) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36852.svg"></sub> (test: split `CreateNewBlock_validity` into independent test cases by yuvicc) * [#36156](https://github.com/bitcoin/bitcoin/pull/36156) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36156.svg"></sub> (mining: include chunks that reach block limits by l0rinc) * [#33922](https://github.com/bitcoin/bitcoin/pull/33922) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/33922.svg"></sub> (mining: add getMemoryLoad() and track template non-mempool memory footprint by Sjors) If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. <!--5faf32d7da4f0f540f40219e4f7537a3-->
optout21 commented 2026-09-23 11:54:07 +00:00 (Migrated from github.com)

CC: @Sjors (author of #31981), @hodlinator (reviewer of #35570).

CC: @Sjors (author of #31981), @hodlinator (reviewer of #35570).
hodlinator commented 2026-09-23 12:20:56 +00:00 (Migrated from github.com)

From what I deduce the defaulted result enum was suggested in the diff posted by @ryanofsky in https://github.com/bitcoin/bitcoin/pull/31981#discussion_r2087339443, so he might also be interested in this.

From what I deduce the defaulted result enum was suggested in the diff posted by @ryanofsky in https://github.com/bitcoin/bitcoin/pull/31981#discussion_r2087339443, so he might also be interested in this.
optout21 commented 2026-09-23 16:00:10 +00:00 (Migrated from github.com)

Undrafting upon clean CI

Undrafting upon clean CI
First-time contributor

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

🔵 Suggestion · TestBlockValidity() result tests do not distinguish invalid states from errors

The new TestBlockValidity() assertions would still pass if an invalid result became an error, despite the different getblocktemplate proposal response.

Location: src/test/miner_tests.cpp:987 (head).

🔵 Suggestion · PR description still names BLOCK_INCONCLUSIVE

The PR description identifies the new result as BLOCK_INCONCLUSIVE, but the code adds and uses BLOCK_PREV_NOT_TIP.

Location: src/consensus/validation.h:76 (head).

Review coverage was incomplete.


Reviewed: ba6f5df60ba8 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:e1a29e5e677c47d383756f0fcf8f3760725c91d1104dd3ccb2f333b6217eba26:47880f5569fd2047d249266f337c4f2a509adf7d96c3ccb1c7644c2c2a650bff --> <!-- ralph-base:2f3f6397bb92beccaccce16742f0574d1617fb3e --> <!-- ralph-head:ba6f5df60ba88b46a3c2dd01bbaae0373901e1e2 --> <!-- ralph-case:68e61772029e4b01b6ec4a4c23f9fddb074597772a7530644cef8bd05e0132a8 --> Earlier concerns neither republished nor resolved: 2 suggestions. See the Run archive linked from the Review report for their assessments. **🔵 Suggestion · `TestBlockValidity()` result tests do not distinguish invalid states from errors** The new `TestBlockValidity()` assertions would still pass if an invalid result became an error, despite the different `getblocktemplate` proposal response. Location: [`src/test/miner_tests.cpp:987`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/ba6f5df60ba88b46a3c2dd01bbaae0373901e1e2/src/test/miner_tests.cpp#L987>) (head). **🔵 Suggestion · PR description still names `BLOCK_INCONCLUSIVE`** The PR description identifies the new result as `BLOCK_INCONCLUSIVE`, but the code adds and uses `BLOCK_PREV_NOT_TIP`. Location: [`src/consensus/validation.h:76`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/ba6f5df60ba88b46a3c2dd01bbaae0373901e1e2/src/consensus/validation.h#L76>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`ba6f5df60ba8`](<https://git.fish.foo/bitcoin/bitcoin/commit/ba6f5df60ba88b46a3c2dd01bbaae0373901e1e2>) · [Review report](<https://review.fish.foo/report/36318-ba6f5df60ba88b46a3c2dd01bbaae0373901e1e2-3520-6.html>) · [Previous reports](<https://review.fish.foo/traces/36318/>) [permalink](<https://review.fish.foo/report/36318-ba6f5df60ba88b46a3c2dd01bbaae0373901e1e2-3520-6.html>)
hodlinator (Migrated from github.com) reviewed 2026-11-06 15:47:44 +00:00
hodlinator (Migrated from github.com) left a comment

Concept ACK 22cf9d54b3

Good call on making reject_reason required too.

Concept ACK 22cf9d54b3fd9561b6b3ad057264dcb2ddbfef56 Good call on making `reject_reason` required too.
hodlinator (Migrated from github.com) commented 2026-11-06 15:44:50 +00:00

nit: Rather than having postconditions for the function, it seems slightly better to have preconditions upon entering, and separate them so it's easier to pinpoint failures:

        Assume(result != Result{});
        Assume(!reject_reason.empty());
        m_result = result;
        m_reject_reason = reject_reason;
        m_debug_message = debug_message;
        if (m_mode != ModeState::M_ERROR) m_mode = ModeState::M_INVALID;
nit: Rather than having postconditions for the function, it seems slightly better to have preconditions upon entering, and separate them so it's easier to pinpoint failures: ```suggestion Assume(result != Result{}); Assume(!reject_reason.empty()); m_result = result; m_reject_reason = reject_reason; m_debug_message = debug_message; if (m_mode != ModeState::M_ERROR) m_mode = ModeState::M_INVALID; ```
optout21 commented 2026-11-10 14:24:26 +00:00 (Migrated from github.com)

Applied nit from review comment -- thanks!
Also rebased (no invalidated reviews)

git range-diff 22cf9d54b3fd9561b6b3ad057264dcb2ddbfef56...4b8b7bd78f70bd1f2598a0eb0401c0a9bb8be124
git range-diff 22cf9d54b3fd9561b6b3ad057264dcb2ddbfef56...ba0d2b49f526b789ab758bc25f909344b2b092c1
Applied nit from review comment -- thanks! Also rebased (no invalidated reviews) ``` git range-diff 22cf9d54b3fd9561b6b3ad057264dcb2ddbfef56...4b8b7bd78f70bd1f2598a0eb0401c0a9bb8be124 git range-diff 22cf9d54b3fd9561b6b3ad057264dcb2ddbfef56...ba0d2b49f526b789ab758bc25f909344b2b092c1 ```
Sjors commented 2026-11-11 10:23:45 +00:00 (Migrated from github.com)

ACK ba0d2b49f5

The mining (validity check) code has no use for the BlockValidationResult enum so it was easy to ignore. The new Assume statements should ensure we don't do that again.

ACK ba0d2b49f526b789ab758bc25f909344b2b092c1 The mining (validity check) code has no use for the `BlockValidationResult` enum so it was easy to ignore. The new `Assume` statements should ensure we don't do that again.
hodlinator (Migrated from github.com) reviewed 2026-11-11 18:41:07 +00:00
hodlinator (Migrated from github.com) left a comment

ACK ba0d2b49f5

Alternative solution

Instead of expanding BlockValidationResult one could wrap the return value of TestBlockValidity() with util::Expected since it's the only function that returns this error. On the other hand, BlockValidationState is already quite diverse in it's various states. Not sure which one is preferable, I lean towards to the current PR approach.

Diff which would avoid need to add BlockValidationResult::INCONCLUSIVE, seems to pass unit and functional tests
diff --git a/src/node/interfaces.cpp b/src/node/interfaces.cpp
index 87084833c6..18114e665c 100644
--- a/src/node/interfaces.cpp
+++ b/src/node/interfaces.cpp
@@ -1001,10 +1001,15 @@ public:
     bool checkBlock(const CBlock& block, const node::BlockCheckOptions& options, std::string& reason, std::string& debug) override
     {
         LOCK(chainman().GetMutex());
-        BlockValidationState state{TestBlockValidity(chainman().ActiveChainstate(), block, /*check_pow=*/options.check_pow, /*check_merkle_root=*/options.check_merkle_root)};
-        reason = state.GetRejectReason();
-        debug = state.GetDebugMessage();
-        return state.IsValid();
+        util::Expected<BlockValidationState, std::string> state{TestBlockValidity(chainman().ActiveChainstate(), block, /*check_pow=*/options.check_pow, /*check_merkle_root=*/options.check_merkle_root)};
+        if (state) {
+            reason = state->GetRejectReason();
+            debug = state->GetDebugMessage();
+            return state->IsValid();
+        } else {
+            reason = state.error();
+            return false;
+        }
     }
 
     bool submitBlock(const CBlock& block_in, std::string& reason, std::string& debug) override
diff --git a/src/node/miner.cpp b/src/node/miner.cpp
index 3f4bd37115..5d4ce084ac 100644
--- a/src/node/miner.cpp
+++ b/src/node/miner.cpp
@@ -229,8 +229,9 @@ std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock()
     pblock->nNonce         = 0;
 
     if (m_options.test_block_validity) {
-        if (BlockValidationState state{TestBlockValidity(m_chainstate, *pblock, /*check_pow=*/false, /*check_merkle_root=*/false)}; !state.IsValid()) {
-            throw std::runtime_error(strprintf("TestBlockValidity failed: %s", state.ToString()));
+        util::Expected<BlockValidationState, std::string> state{TestBlockValidity(m_chainstate, *pblock, /*check_pow=*/false, /*check_merkle_root=*/false)};
+        if (!state || !state->IsValid()) {
+            throw std::runtime_error(strprintf("TestBlockValidity failed: %s", state ? state->ToString() : state.error()));
         }
     }
     const auto time_2{SteadyClock::now()};
diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp
index 4f375a90f2..fcd8876fad 100644
--- a/src/rpc/mining.cpp
+++ b/src/rpc/mining.cpp
@@ -419,8 +419,9 @@ static RPCMethod generateblock()
         block.vtx.insert(block.vtx.end(), txs.begin(), txs.end());
         RegenerateCommitments(block, chainman);
 
-        if (BlockValidationState state{TestBlockValidity(chainman.ActiveChainstate(), block, /*check_pow=*/false, /*check_merkle_root=*/false)}; !state.IsValid()) {
-            throw JSONRPCError(RPC_VERIFY_ERROR, strprintf("TestBlockValidity failed: %s", state.ToString()));
+        util::Expected<BlockValidationState, std::string> state{TestBlockValidity(chainman.ActiveChainstate(), block, /*check_pow=*/false, /*check_merkle_root=*/false)};
+        if (!state || !state->IsValid()) {
+            throw JSONRPCError(RPC_VERIFY_ERROR, strprintf("TestBlockValidity failed: %s", state ? state->ToString() : state.error()));
         }
     }
 
@@ -780,7 +781,9 @@ static RPCMethod getblocktemplate()
                 return "duplicate-inconclusive";
             }
 
-            return BIP22ValidationResult(TestBlockValidity(chainman.ActiveChainstate(), block, /*check_pow=*/false, /*check_merkle_root=*/true));
+            util::Expected<BlockValidationState, std::string> state{TestBlockValidity(chainman.ActiveChainstate(), block, /*check_pow=*/false, /*check_merkle_root=*/true)};
+            if (!state) return state.error();
+            return BIP22ValidationResult(*state);
         }
 
         const UniValue& aClientRules = oparam.find_value("rules");
diff --git a/src/validation.cpp b/src/validation.cpp
index 5fd5954860..a02d34d5bf 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -50,6 +50,7 @@
 #include <undo.h>
 #include <util/byte_units.h>
 #include <util/check.h>
+#include <util/expected.h>
 #include <util/fs.h>
 #include <util/fs_helpers.h>
 #include <util/hasher.h>
@@ -4548,7 +4549,7 @@ MempoolAcceptResult ChainstateManager::ProcessTransaction(const CTransactionRef&
 }
 
 
-BlockValidationState TestBlockValidity(
+util::Expected<BlockValidationState, std::string> TestBlockValidity(
     Chainstate& chainstate,
     const CBlock& block,
     const bool check_pow,
@@ -4563,8 +4564,7 @@ BlockValidationState TestBlockValidity(
     CBlockIndex* tip{Assert(chainstate.m_chain.Tip())};
 
     if (block.hashPrevBlock != *Assert(tip->phashBlock)) {
-        state.Invalid(BlockValidationResult::BLOCK_INCONCLUSIVE, "inconclusive-not-best-prevblk");
-        return state;
+        return util::Unexpected{"inconclusive-not-best-prevblk"};
     }
 
     // For signets CheckBlock() verifies the challenge iff fCheckPow is set.
diff --git a/src/validation.h b/src/validation.h
index 68c1f7e0a4..104b12d5f8 100644
--- a/src/validation.h
+++ b/src/validation.h
@@ -31,6 +31,7 @@
 #include <uint256.h>
 #include <util/byte_units.h>
 #include <util/check.h>
+#include <util/expected.h>
 #include <util/fs.h>
 #include <util/hasher.h>
 #include <util/result.h>
@@ -407,7 +408,7 @@ bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensu
  *
  * For signets the challenge verification is skipped when check_pow is false.
  */
-BlockValidationState TestBlockValidity(
+util::Expected<BlockValidationState, std::string> TestBlockValidity(
     Chainstate& chainstate,
     const CBlock& block,
     bool check_pow,
ACK ba0d2b49f526b789ab758bc25f909344b2b092c1 #### Alternative solution Instead of expanding `BlockValidationResult` one could wrap the return value of `TestBlockValidity()` with `util::Expected` since it's the only function that returns this error. On the other hand, `BlockValidationState` is already quite diverse in it's various states. Not sure which one is preferable, I lean towards to the current PR approach. <details><summary>Diff which would avoid need to add BlockValidationResult::INCONCLUSIVE, seems to pass unit and functional tests</summary> ```diff diff --git a/src/node/interfaces.cpp b/src/node/interfaces.cpp index 87084833c6..18114e665c 100644 --- a/src/node/interfaces.cpp +++ b/src/node/interfaces.cpp @@ -1001,10 +1001,15 @@ public: bool checkBlock(const CBlock& block, const node::BlockCheckOptions& options, std::string& reason, std::string& debug) override { LOCK(chainman().GetMutex()); - BlockValidationState state{TestBlockValidity(chainman().ActiveChainstate(), block, /*check_pow=*/options.check_pow, /*check_merkle_root=*/options.check_merkle_root)}; - reason = state.GetRejectReason(); - debug = state.GetDebugMessage(); - return state.IsValid(); + util::Expected<BlockValidationState, std::string> state{TestBlockValidity(chainman().ActiveChainstate(), block, /*check_pow=*/options.check_pow, /*check_merkle_root=*/options.check_merkle_root)}; + if (state) { + reason = state->GetRejectReason(); + debug = state->GetDebugMessage(); + return state->IsValid(); + } else { + reason = state.error(); + return false; + } } bool submitBlock(const CBlock& block_in, std::string& reason, std::string& debug) override diff --git a/src/node/miner.cpp b/src/node/miner.cpp index 3f4bd37115..5d4ce084ac 100644 --- a/src/node/miner.cpp +++ b/src/node/miner.cpp @@ -229,8 +229,9 @@ std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock() pblock->nNonce = 0; if (m_options.test_block_validity) { - if (BlockValidationState state{TestBlockValidity(m_chainstate, *pblock, /*check_pow=*/false, /*check_merkle_root=*/false)}; !state.IsValid()) { - throw std::runtime_error(strprintf("TestBlockValidity failed: %s", state.ToString())); + util::Expected<BlockValidationState, std::string> state{TestBlockValidity(m_chainstate, *pblock, /*check_pow=*/false, /*check_merkle_root=*/false)}; + if (!state || !state->IsValid()) { + throw std::runtime_error(strprintf("TestBlockValidity failed: %s", state ? state->ToString() : state.error())); } } const auto time_2{SteadyClock::now()}; diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index 4f375a90f2..fcd8876fad 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -419,8 +419,9 @@ static RPCMethod generateblock() block.vtx.insert(block.vtx.end(), txs.begin(), txs.end()); RegenerateCommitments(block, chainman); - if (BlockValidationState state{TestBlockValidity(chainman.ActiveChainstate(), block, /*check_pow=*/false, /*check_merkle_root=*/false)}; !state.IsValid()) { - throw JSONRPCError(RPC_VERIFY_ERROR, strprintf("TestBlockValidity failed: %s", state.ToString())); + util::Expected<BlockValidationState, std::string> state{TestBlockValidity(chainman.ActiveChainstate(), block, /*check_pow=*/false, /*check_merkle_root=*/false)}; + if (!state || !state->IsValid()) { + throw JSONRPCError(RPC_VERIFY_ERROR, strprintf("TestBlockValidity failed: %s", state ? state->ToString() : state.error())); } } @@ -780,7 +781,9 @@ static RPCMethod getblocktemplate() return "duplicate-inconclusive"; } - return BIP22ValidationResult(TestBlockValidity(chainman.ActiveChainstate(), block, /*check_pow=*/false, /*check_merkle_root=*/true)); + util::Expected<BlockValidationState, std::string> state{TestBlockValidity(chainman.ActiveChainstate(), block, /*check_pow=*/false, /*check_merkle_root=*/true)}; + if (!state) return state.error(); + return BIP22ValidationResult(*state); } const UniValue& aClientRules = oparam.find_value("rules"); diff --git a/src/validation.cpp b/src/validation.cpp index 5fd5954860..a02d34d5bf 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -50,6 +50,7 @@ #include <undo.h> #include <util/byte_units.h> #include <util/check.h> +#include <util/expected.h> #include <util/fs.h> #include <util/fs_helpers.h> #include <util/hasher.h> @@ -4548,7 +4549,7 @@ MempoolAcceptResult ChainstateManager::ProcessTransaction(const CTransactionRef& } -BlockValidationState TestBlockValidity( +util::Expected<BlockValidationState, std::string> TestBlockValidity( Chainstate& chainstate, const CBlock& block, const bool check_pow, @@ -4563,8 +4564,7 @@ BlockValidationState TestBlockValidity( CBlockIndex* tip{Assert(chainstate.m_chain.Tip())}; if (block.hashPrevBlock != *Assert(tip->phashBlock)) { - state.Invalid(BlockValidationResult::BLOCK_INCONCLUSIVE, "inconclusive-not-best-prevblk"); - return state; + return util::Unexpected{"inconclusive-not-best-prevblk"}; } // For signets CheckBlock() verifies the challenge iff fCheckPow is set. diff --git a/src/validation.h b/src/validation.h index 68c1f7e0a4..104b12d5f8 100644 --- a/src/validation.h +++ b/src/validation.h @@ -31,6 +31,7 @@ #include <uint256.h> #include <util/byte_units.h> #include <util/check.h> +#include <util/expected.h> #include <util/fs.h> #include <util/hasher.h> #include <util/result.h> @@ -407,7 +408,7 @@ bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensu * * For signets the challenge verification is skipped when check_pow is false. */ -BlockValidationState TestBlockValidity( +util::Expected<BlockValidationState, std::string> TestBlockValidity( Chainstate& chainstate, const CBlock& block, bool check_pow, ``` </details>
hodlinator (Migrated from github.com) commented 2026-11-11 17:47:34 +00:00

Searched for cases where we might be skipping over testing for BLOCK_INCONCLUSIVE such as:

github.com/bitcoin/bitcoin@232cb5410a/src/validation.cpp (L1984)

But all 3 similar cases I could find had not called into TestBlockValidity(), so shouldn't need to account for that.

Searched for cases where we might be skipping over testing for `BLOCK_INCONCLUSIVE` such as: https://github.com/bitcoin/bitcoin/blob/232cb5410a139de15ac1f6233aab1e89ba2a408f/src/validation.cpp#L1984 But all 3 similar cases I could find had not called into `TestBlockValidity()`, so shouldn't need to account for that.
hodlinator (Migrated from github.com) commented 2026-11-11 16:19:27 +00:00

Saw inconclusive-not-best-prevblk is covered in 2 functional tests. Not sure if it would add anything to also have a unit test covering the enum.

--- a/src/test/miner_tests.cpp
+++ b/src/test/miner_tests.cpp
@@ -965,6 +965,21 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
     TestPrioritisedMining(scriptPubKey, txFirst);
 
     TestSigOpsAdjustedWeightChunkLimit(scriptPubKey, txFirst);
+
+    {
+        const std::unique_ptr<BlockTemplate> inconclusive_template{
+            mining->createNewBlock(options, /*cooldown=*/false)};
+        BOOST_REQUIRE(inconclusive_template);
+        CBlock inconclusive_block{inconclusive_template->getBlock()};
+        // Make sure that we are further along than height 1.
+        const auto& genesis_hash{m_node.chainman->GetParams().GetConsensus().hashGenesisBlock};
+        BOOST_REQUIRE_NE(inconclusive_block.hashPrevBlock, genesis_hash);
+        // Reset us to height 1.
+        inconclusive_block.hashPrevBlock = genesis_hash;
+        BlockValidationState state{TestBlockValidity(m_node.chainman->ActiveChainstate(),
+            inconclusive_block, /*check_pow=*/true, /*check_merkle_root=*/true)};
+        BOOST_CHECK_EQUAL(state.GetResult(), BlockValidationResult::BLOCK_INCONCLUSIVE);
+    }
 }
 
 BOOST_AUTO_TEST_CASE(block_template_manager)
Saw `inconclusive-not-best-prevblk` is covered in 2 functional tests. Not sure if it would add anything to also have a unit test covering the enum. ```diff --- a/src/test/miner_tests.cpp +++ b/src/test/miner_tests.cpp @@ -965,6 +965,21 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) TestPrioritisedMining(scriptPubKey, txFirst); TestSigOpsAdjustedWeightChunkLimit(scriptPubKey, txFirst); + + { + const std::unique_ptr<BlockTemplate> inconclusive_template{ + mining->createNewBlock(options, /*cooldown=*/false)}; + BOOST_REQUIRE(inconclusive_template); + CBlock inconclusive_block{inconclusive_template->getBlock()}; + // Make sure that we are further along than height 1. + const auto& genesis_hash{m_node.chainman->GetParams().GetConsensus().hashGenesisBlock}; + BOOST_REQUIRE_NE(inconclusive_block.hashPrevBlock, genesis_hash); + // Reset us to height 1. + inconclusive_block.hashPrevBlock = genesis_hash; + BlockValidationState state{TestBlockValidity(m_node.chainman->ActiveChainstate(), + inconclusive_block, /*check_pow=*/true, /*check_merkle_root=*/true)}; + BOOST_CHECK_EQUAL(state.GetResult(), BlockValidationResult::BLOCK_INCONCLUSIVE); + } } BOOST_AUTO_TEST_CASE(block_template_manager) ```
Pranav-error commented 2026-11-12 20:27:52 +00:00 (Migrated from github.com)

crACK ba0d2b49f5

Reviewed the invariant change and its blast radius:

  • Enum exhaustiveness / net handling: MaybePunishNodeForBlock's switch (net_processing.cpp:538) has no default:, so BLOCK_INCONCLUSIVE had to be handled explicitly — the added case ... break; (no punishment) is right: the only producer is TestBlockValidity() (block-template/submitblock validity testing, not network-received blocks), so a peer should never be punished for it, and break keeps nDoS at 0. Matches @Sjors' point that the validity path doesn't consume the enum.
  • reject_reason now required + Assume(!reject_reason.empty()): checked the callers that passed "" — the fuzz targets txdownloadman.cpp:223/357/420 and the txdownload_tests.cpp cases. These matter because Assume is fatal under a fuzz build, so an un-updated Invalid(result, "") would abort the fuzzer; the PR updates all of them to "dummy-reason", so the invariant is complete.
  • The real fix (TestBlockValidity: Invalid({}, ...) → Invalid(BLOCK_INCONCLUSIVE, ...)) removes the one unset-result path.

Nit (non-blocking): the BLOCK_INCONCLUSIVE comment — "...e.g. we don't have the block it's building on" — reads close to BLOCK_MISSING_PREV and doesn't match the actual use (hashPrevBlock != tip, "inconclusive-not-best-prevblk": builds on a non-tip block we may well have). Maybe "...the block it builds on is not the current tip" to disambiguate.

Code-review only (didn't build/run).

crACK ba0d2b49f526b789ab758bc25f909344b2b092c1 Reviewed the invariant change and its blast radius: - **Enum exhaustiveness / net handling:** `MaybePunishNodeForBlock`'s `switch` (net_processing.cpp:538) has no `default:`, so `BLOCK_INCONCLUSIVE` had to be handled explicitly — the added `case ... break;` (no punishment) is right: the only producer is `TestBlockValidity()` (block-template/`submitblock` validity testing, not network-received blocks), so a peer should never be punished for it, and `break` keeps `nDoS` at 0. Matches @Sjors' point that the validity path doesn't consume the enum. - **`reject_reason` now required + `Assume(!reject_reason.empty())`:** checked the callers that passed `""` — the fuzz targets `txdownloadman.cpp:223/357/420` and the `txdownload_tests.cpp` cases. These matter because `Assume` is **fatal under a fuzz build**, so an un-updated `Invalid(result, "")` would abort the fuzzer; the PR updates all of them to `"dummy-reason"`, so the invariant is complete. - The real fix (`TestBlockValidity`: `Invalid({}, ...)` → `Invalid(BLOCK_INCONCLUSIVE, ...)`) removes the one unset-result path. Nit (non-blocking): the `BLOCK_INCONCLUSIVE` comment — "...e.g. we don't have the block it's building on" — reads close to `BLOCK_MISSING_PREV` and doesn't match the actual use (`hashPrevBlock != tip`, "inconclusive-not-best-prevblk": builds on a *non-tip* block we may well have). Maybe "...the block it builds on is not the current tip" to disambiguate. Code-review only (didn't build/run).
optout21 commented 2026-11-19 07:27:45 +00:00 (Migrated from github.com)

Nit (non-blocking): the BLOCK_INCONCLUSIVE comment ...

I acknowledge this, indeed the example could be closer to the current usage. I think it's very minor, as this is only an example in the comment. Not changing now (I don't want to invalidate existing acks), but will change if I need to touch for other reason.

> Nit (non-blocking): the `BLOCK_INCONCLUSIVE` comment ... I acknowledge this, indeed the example could be closer to the current usage. I think it's very minor, as this is only an example in the comment. Not changing now (I don't want to invalidate existing acks), but will change if I need to touch for other reason.
mzumsande (Migrated from github.com) reviewed 2026-11-19 18:08:23 +00:00
mzumsande (Migrated from github.com) left a comment

I acknowledge this, indeed the example could be closer to the current usage. I think it's very minor, as this is only an example in the comment.

I'd agree if this was a random test file, but comments in consensus/validation.h should be clear in my opinion - e.g. just from reading the file it wouldn't be clear which of the two enum values a block with a missing prev would get.

More generally, I find the state of the enum kind of confusing:
The preexisting BLOCK_MISSING_PREV , BLOCK_HEADER_LOW_WORK (and to some extent BLOCK_TIME_FUTURE) all describe specific inconclusive scenarios (we don't know if it is valid, refuse to validate, or it may become valid in the future), so it's not clear to me what a BLOCK_INCONCLUSIVE category should cover. Is this meant to become a kitchen-sink category for "all the rest"? Otherwise wouldn't it be more in line with the existing approach to call it BLOCK_PREV_NOT_TIP or similar?

> I acknowledge this, indeed the example could be closer to the current usage. I think it's very minor, as this is only an example in the comment. I'd agree if this was a random test file, but comments in `consensus/validation.h` should be clear in my opinion - e.g. just from reading the file it wouldn't be clear which of the two enum values a block with a missing prev would get. More generally, I find the state of the enum kind of confusing: The preexisting `BLOCK_MISSING_PREV` , `BLOCK_HEADER_LOW_WORK` (and to some extent `BLOCK_TIME_FUTURE`) all describe specific inconclusive scenarios (we don't know if it is valid, refuse to validate, or it may become valid in the future), so it's not clear to me what a `BLOCK_INCONCLUSIVE` category should cover. Is this meant to become a kitchen-sink category for "all the rest"? Otherwise wouldn't it be more in line with the existing approach to call it `BLOCK_PREV_NOT_TIP` or similar?
optout21 commented 2026-11-20 11:16:43 +00:00 (Migrated from github.com)

Thinking about it more, I agree that reject reasons should be specific: a generic BLOCK_INCONCLUSIVE is not much better than leaving the result unset, which is what this PR tries to eliminate. It's also exposed in the kernel API, so the name should be precise.

Given the background on how TestBlockValidity() is used, the options I see are:

  • Add a new specific value, namely BLOCK_PREV_NOT_TIP (replacing BLOCK_INCONCLUSIVE), with the auxiliary costs (e.g. exposing through kernel API).

  • Don't add a new value, but reuse an existing one, e.g. BLOCK_MISSING_PREV, with a comment explaining the mismatch. Callers of TestBlockValidity() only look at the reject reason string, so the enum value isn't used there. (BLOCK_INVALID_PREV doesn't fit: it means the block is definitely invalid, and net_processing punishes peers for it.)

I lean towards the first option and will rename unless there are objections.

Thinking about it more, I agree that reject reasons should be specific: a generic BLOCK_INCONCLUSIVE is not much better than leaving the result unset, which is what this PR tries to eliminate. It's also exposed in the kernel API, so the name should be precise. Given the background on how `TestBlockValidity()` is used, the options I see are: - Add a new specific value, namely BLOCK_PREV_NOT_TIP (replacing BLOCK_INCONCLUSIVE), with the auxiliary costs (e.g. exposing through kernel API). - Don't add a new value, but reuse an existing one, e.g. BLOCK_MISSING_PREV, with a comment explaining the mismatch. Callers of `TestBlockValidity()` only look at the reject reason string, so the enum value isn't used there. (BLOCK_INVALID_PREV doesn't fit: it means the block is definitely invalid, and net_processing punishes peers for it.) I lean towards the first option and will rename unless there are objections.
optout21 commented 2026-11-23 11:12:44 +00:00 (Migrated from github.com)

Instead of expanding BlockValidationResult one could wrap the return value of TestBlockValidity() with util::Expected ...

That's also a potential solution, I agree. I categorize these approaches:

  1. Use a new reject reason enum. This is the cleanest solution, but the cost is the extension of a widely-used validation enum.
  2. Use a different mechanism for returning this specific case from TestBlockValidity(), e.g. using util::Expected, as you discussed. No need to touch the BlockValidationResult enum. However, in the call sites of TestBlockValidity(), the reject reason and debug strings are handled similarly to other non-valid check results, and they would need a special handling.
  3. Reuse an exisiting reject reason enum value in TestBlockValidity(), with the comment "only in this spot it means a little different thing".

The latter two introduce inconsistencies in the code (a bit "hacky"), therefore I chose 1.

> Instead of expanding `BlockValidationResult` one could wrap the return value of `TestBlockValidity()` with `util::Expected` ... That's also a potential solution, I agree. I categorize these approaches: 1. Use a new reject reason enum. This is the cleanest solution, but the cost is the extension of a widely-used validation enum. 2. Use a different mechanism for returning this specific case from `TestBlockValidity()`, e.g. using `util::Expected`, as you discussed. No need to touch the `BlockValidationResult` enum. However, in the call sites of `TestBlockValidity()`, the reject reason and debug strings are handled similarly to other non-valid check results, and they would need a special handling. 3. Reuse an exisiting reject reason enum value in `TestBlockValidity()`, with the comment "only in this spot it means a little different thing". The latter two introduce inconsistencies in the code (a bit "hacky"), therefore I chose 1.
hodlinator commented 2026-11-23 11:46:45 +00:00 (Migrated from github.com)

A more specific BLOCK_PREV_NOT_TIP sounds good to me.

A more specific `BLOCK_PREV_NOT_TIP` sounds good to me.
optout21 commented 2026-11-23 19:40:01 +00:00 (Migrated from github.com)

Changes applied:

  • Renamed the new reject reason enum value to the more specific BLOCK_PREV_NOT_TIP (from BLOCK_INCONCLUSIVE), as suggested by @mzumsande
  • Added a unit test for the reject reason returned by TestBlockValidity(), as suggested by @hodlinator

(git range-diff ba0d2b49f526b789ab758bc25f909344b2b092c1...be5ff46547675d6cd329aad7778a32f4192fe605)

Changes applied: - Renamed the new reject reason enum value to the more specific `BLOCK_PREV_NOT_TIP` (from `BLOCK_INCONCLUSIVE`), as suggested by @mzumsande - Added a unit test for the reject reason returned by `TestBlockValidity()`, as suggested by @hodlinator (`git range-diff ba0d2b49f526b789ab758bc25f909344b2b092c1...be5ff46547675d6cd329aad7778a32f4192fe605`)
hodlinator (Migrated from github.com) approved these changes 2026-11-24 09:34:01 +00:00
hodlinator (Migrated from github.com) left a comment

re-ACK be5ff46547

Switched to more precise enum name and added unit test.

re-ACK be5ff46547675d6cd329aad7778a32f4192fe605 Switched to more precise enum name and added unit test.
optout21 commented 2026-11-24 12:14:45 +00:00 (Migrated from github.com)

I've came up with another solution alternative:

  1. Create a special TestBlockValidationResult, "on top of" BlockValidationResult, with the extra value, and a special TestBlockValidationState (ValidationState<TestBlockValidationResult>). Use this in TestBlockValidity(). As this is used only internally, within this methods and at its call sites, the new value+state doesn't have to be exposed. Therefore the change has lower impact.

I've added this (and other alternatives) to the description.
I'm testing this solution, it seems better because it has less impact. Currently it can be seen here: https://github.com/optout21/bitcoin/pull/32

I'm looking forward for assessments from reviewers.

I've came up with another solution alternative: 4. Create a special `TestBlockValidationResult`, "on top of" `BlockValidationResult`, with the extra value, and a special `TestBlockValidationState` (`ValidationState<TestBlockValidationResult>`). Use this in `TestBlockValidity()`. As this is used only internally, within this methods and at its call sites, the new value+state doesn't have to be exposed. Therefore the change has lower impact. I've added this (and other alternatives) to the description. I'm testing this solution, it seems better because it has less impact. Currently it can be seen here: https://github.com/optout21/bitcoin/pull/32 I'm looking forward for assessments from reviewers.
Pranav-error commented 2026-11-24 16:11:38 +00:00 (Migrated from github.com)

The change looks good from the tests I ran. miner_tests and txdownload_tests pass on the PR head, and reverting the validation.cpp change reproduces the failure in miner_tests.cpp:984 (BLOCK_PREV_NOT_TIP expected, but 0 returned). Restoring the change makes the test pass again as i saw , confirming the regression test covers the behavior introduced by this PR.

The change looks good from the tests I ran. miner_tests and txdownload_tests pass on the PR head, and reverting the validation.cpp change reproduces the failure in miner_tests.cpp:984 (BLOCK_PREV_NOT_TIP expected, but 0 returned). Restoring the change makes the test pass again as i saw , confirming the regression test covers the behavior introduced by this PR.
Sjors commented 2026-11-26 11:01:18 +00:00 (Migrated from github.com)

I've came up with another solution alternative:

Create a special TestBlockValidationResult [...]

Adding a whole new TestBlockValidationResult enum just for one value seems overkill.

If I understand correctly:

  • BLOCK_PREV_NOT_TIP means: it's not the tip, I didn't check the index
  • BLOCK_MISSING_PREV means: it's not in the index (and therefore not the tip)

It's true that current p2p code doesn't use BLOCK_PREV_NOT_TIP, and probably never needs it because it always looks through the headers. But it's still the result of validation.

> I've came up with another solution alternative: >> Create a special TestBlockValidationResult [...] Adding a whole new `TestBlockValidationResult` enum just for one value seems overkill. If I understand correctly: - `BLOCK_PREV_NOT_TIP` means: it's not the tip, I didn't check the index - `BLOCK_MISSING_PREV` means: it's not in the index (and therefore not the tip) It's true that current p2p code doesn't use `BLOCK_PREV_NOT_TIP`, and probably never needs it because it always looks through the headers. But it's still the _result of validation_.
Sjors (Migrated from github.com) approved these changes 2026-11-26 11:22:38 +00:00
Sjors (Migrated from github.com) left a comment
ACK be5ff46547675d6cd329aad7778a32f4192fe605
Sjors (Migrated from github.com) commented 2026-11-26 11:09:58 +00:00

In 8d9aed91ad validation: In TestBlockValidity, use PREV_NOT_TIP nit: you could introduce this test before the change, so it's clear only state.GetResult() changes.

That commit could cover the other enum results too, which don't change in this PR. Something like:

    {
        // Each kind of failure in TestBlockValidity sets its own result
        const std::unique_ptr<BlockTemplate> block_template{mining->createNewBlock(options, /*cooldown=*/false)};
        BOOST_REQUIRE(block_template);
        const CBlock template_block{block_template->getBlock()};
        const auto check_result{[&](auto mutate, BlockValidationResult result, const std::string& reason, bool check_merkle_root = false) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
            CBlock block{template_block};
            mutate(block);
            const BlockValidationState state{TestBlockValidity(m_node.chainman->ActiveChainstate(), block,
                                                               /*check_pow=*/false, check_merkle_root)};
            BOOST_CHECK_EQUAL(state.GetResult(), result);
            BOOST_CHECK_EQUAL(state.GetRejectReason(), reason);
        }};
        check_result([](CBlock&) {}, BlockValidationResult::BLOCK_RESULT_UNSET, "");
        check_result([](CBlock& block) { block.vtx.push_back(block.vtx.at(0)); },
                     BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-multiple");
        check_result([](CBlock& block) { block.nBits ^= 1; },
                     BlockValidationResult::BLOCK_INVALID_HEADER, "bad-diffbits");
        check_result([](CBlock& block) { block.hashMerkleRoot = uint256::ONE; },
                     BlockValidationResult::BLOCK_MUTATED, "bad-txnmrklroot", /*check_merkle_root=*/true);
        check_result([](CBlock& block) { block.nTime = TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()) + MAX_FUTURE_BLOCK_TIME + 1; },
                     BlockValidationResult::BLOCK_TIME_FUTURE, "time-too-new");
    }
In 8d9aed91ade2dfcbc7354865a65cc6903ca655b6 _validation: In TestBlockValidity, use PREV_NOT_TIP_ nit: you could introduce this test before the change, so it's clear only `state.GetResult()` changes. That commit could cover the other enum results too, which don't change in this PR. Something like: ```cpp { // Each kind of failure in TestBlockValidity sets its own result const std::unique_ptr<BlockTemplate> block_template{mining->createNewBlock(options, /*cooldown=*/false)}; BOOST_REQUIRE(block_template); const CBlock template_block{block_template->getBlock()}; const auto check_result{[&](auto mutate, BlockValidationResult result, const std::string& reason, bool check_merkle_root = false) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { CBlock block{template_block}; mutate(block); const BlockValidationState state{TestBlockValidity(m_node.chainman->ActiveChainstate(), block, /*check_pow=*/false, check_merkle_root)}; BOOST_CHECK_EQUAL(state.GetResult(), result); BOOST_CHECK_EQUAL(state.GetRejectReason(), reason); }}; check_result([](CBlock&) {}, BlockValidationResult::BLOCK_RESULT_UNSET, ""); check_result([](CBlock& block) { block.vtx.push_back(block.vtx.at(0)); }, BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-multiple"); check_result([](CBlock& block) { block.nBits ^= 1; }, BlockValidationResult::BLOCK_INVALID_HEADER, "bad-diffbits"); check_result([](CBlock& block) { block.hashMerkleRoot = uint256::ONE; }, BlockValidationResult::BLOCK_MUTATED, "bad-txnmrklroot", /*check_merkle_root=*/true); check_result([](CBlock& block) { block.nTime = TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()) + MAX_FUTURE_BLOCK_TIME + 1; }, BlockValidationResult::BLOCK_TIME_FUTURE, "time-too-new"); } ```
optout21 (Migrated from github.com) reviewed 2026-11-27 07:32:24 +00:00
optout21 (Migrated from github.com) commented 2026-11-27 07:32:24 +00:00

For completeness: this has been applied earlier.

For completeness: this has been applied earlier.
optout21 commented 2026-11-27 07:34:12 +00:00 (Migrated from github.com)

Adding a whole new TestBlockValidationResult enum just for one value seems overkill.

Thanks @hodlinator and @Sjors for sharing feedback on the proposed alternative, I also reached a similar conclusion, and discarded the alternative.

> Adding a whole new `TestBlockValidationResult` enum just for one value seems overkill. Thanks @hodlinator and @Sjors for sharing feedback on the proposed alternative, I also reached a similar conclusion, and discarded the alternative.
optout21 (Migrated from github.com) reviewed 2026-11-27 07:36:51 +00:00
optout21 (Migrated from github.com) left a comment

I've applied @Sjors's suggestions for the test:

  • The unit test check for TestBlockValidity() returns in the stale block case has been moved earlier.
  • The unit test has been extended with checks for other error cases (slightly extended, with check for validity as well).

git range-diff be5ff46..be10d3d

I've applied @Sjors's suggestions for the test: - The unit test check for `TestBlockValidity()` returns in the stale block case has been moved earlier. - The unit test has been extended with checks for other error cases (slightly extended, with check for validity as well). `git range-diff be5ff46..be10d3d`
optout21 (Migrated from github.com) commented 2026-11-27 07:35:25 +00:00

Applied, slightly extended, with check for validity as well.
Thanks for the ready-prepared snippet!

Applied, slightly extended, with check for validity as well. Thanks for the ready-prepared snippet!
hodlinator (Migrated from github.com) approved these changes 2026-11-30 09:33:53 +00:00
hodlinator (Migrated from github.com) left a comment

re-ACK be10d3d5cf

Nice to see increased unit test coverage of other enum values.

re-ACK be10d3d5cf58ebe6dbdb7cc64e7416b57a5c9fdb Nice to see increased unit test coverage of other enum values.
hodlinator (Migrated from github.com) commented 2026-11-30 09:26:42 +00:00

nanonit: If you touch again for some other reason, this is better form, avoiding allocations in cases small string optimization doesn't cover it (although in this case it doesn't affect performance):

                 std::string_view reject_reason,
                 std::string_view debug_message = {})
nanonit: If you touch again for some other reason, this is better form, avoiding allocations in cases small string optimization doesn't cover it (although in this case it doesn't affect performance): ```suggestion std::string_view reject_reason, std::string_view debug_message = {}) ```
Sjors commented 2026-12-01 10:15:10 +00:00 (Migrated from github.com)
ACK be10d3d5cf58ebe6dbdb7cc64e7416b57a5c9fdb
mzumsande (Migrated from github.com) reviewed 2026-12-01 15:33:50 +00:00
mzumsande (Migrated from github.com) left a comment

Code Review ACK be10d3d5cf

Code Review ACK be10d3d5cf58ebe6dbdb7cc64e7416b57a5c9fdb
Pranav-error commented 2026-12-02 09:25:48 +00:00 (Migrated from github.com)

Retested the latest head (be10d3d5cf)

  • Passed 5/5 runs
  • Reverting the fix gets caught
  • Two wrong result code mutations also get caught
  • Test only commit passes independently

One thing: the new Assume only aborts in Debug builds, so my RelWithDebInfo run doesn't verify that assertion

Debug, fuzz, test_kernel and functional tests are still pending

Retested the latest head (`be10d3d5cf`) - Passed 5/5 runs - Reverting the fix gets caught - Two wrong result code mutations also get caught - Test only commit passes independently One thing: the new `Assume` only aborts in Debug builds, so my RelWithDebInfo run doesn't verify that assertion Debug, fuzz, test_kernel and functional tests are still pending
optout21 commented 2026-12-02 13:30:15 +00:00 (Migrated from github.com)

Thanks for the (re)reviews! RFM? Or need to call in more reviewers?

Thanks for the (re)reviews! RFM? Or need to call in more reviewers?
l0rinc (Migrated from github.com) approved these changes 2026-12-02 15:01:52 +00:00
l0rinc (Migrated from github.com) left a comment

ACK be10d3d5cf

Requiring a set result and a non-empty reject reason gives invalid validation states a consistent contract, and BLOCK_PREV_NOT_TIP makes it clear why TestBlockValidity rejects a stale template.

I'm fine with merging as is, but what do you think about adding FakeNodeClock to the BLOCK_TIME_FUTURE test? If the wall clock crosses a second boundary between setting block.nTime and checking it, the timestamp can fall within the allowed window and the test can fail.

The stale-parent case could also share the template and assertions with the other cases. The PR description still needs to be updated from BLOCK_INCONCLUSIVE to BLOCK_PREV_NOT_TIP.

I'd also take hodlinator's std::string_view suggestion.
I'd be happy to re-review if you do.

ACK be10d3d5cf58ebe6dbdb7cc64e7416b57a5c9fdb Requiring a set result and a non-empty reject reason gives invalid validation states a consistent contract, and `BLOCK_PREV_NOT_TIP` makes it clear why `TestBlockValidity` rejects a stale template. I'm fine with merging as is, but what do you think about adding `FakeNodeClock` to the `BLOCK_TIME_FUTURE` test? If the wall clock crosses a second boundary between setting `block.nTime` and checking it, the timestamp can fall within the allowed window and the test can fail. The stale-parent case could also share the template and assertions with the other cases. The PR description still needs to be updated from `BLOCK_INCONCLUSIVE` to `BLOCK_PREV_NOT_TIP`. I'd also take [hodlinator's `std::string_view` suggestion](https://github.com/bitcoin/bitcoin/pull/36318#discussion_r4737135503). I'd be happy to re-review if you do.
l0rinc (Migrated from github.com) commented 2026-12-02 14:57:24 +00:00

bf0d58d test: Check TestBlockValidity() error returns:

The test rounds down the current time before setting nTime. If the clock ticks over before validation, the timestamp falls within the allowed window. Can we freeze NodeClock for these checks?

Example patch
diff --git a/src/test/miner_tests.cpp b/src/test/miner_tests.cpp
index d5651546ff..23be18c556 100644
--- a/src/test/miner_tests.cpp
+++ b/src/test/miner_tests.cpp
@@ -953,6 +953,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
 
     {
         // Each kind of failure in TestBlockValidity sets its own result
+        FakeNodeClock clock{};
         const std::unique_ptr<BlockTemplate> block_template{mining->createNewBlock(options, /*cooldown=*/false)};
         BOOST_REQUIRE(block_template);
         const CBlock template_block{block_template->getBlock()};
> [bf0d58d](https://github.com/bitcoin/bitcoin/pull/36318/changes/bf0d58d32a2ac25c96a7ee6b22b7de9069bd26a9) _test: Check TestBlockValidity() error returns_: The test rounds down the current time before setting `nTime`. If the clock ticks over before validation, the timestamp falls within the allowed window. Can we freeze `NodeClock` for these checks? <details><summary>Example patch</summary> ```diff diff --git a/src/test/miner_tests.cpp b/src/test/miner_tests.cpp index d5651546ff..23be18c556 100644 --- a/src/test/miner_tests.cpp +++ b/src/test/miner_tests.cpp @@ -953,6 +953,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) { // Each kind of failure in TestBlockValidity sets its own result + FakeNodeClock clock{}; const std::unique_ptr<BlockTemplate> block_template{mining->createNewBlock(options, /*cooldown=*/false)}; BOOST_REQUIRE(block_template); const CBlock template_block{block_template->getBlock()}; ``` </details>
l0rinc (Migrated from github.com) commented 2026-12-02 14:57:34 +00:00

The new tests are a bit excessive. The stale-parent case could use this helper too and share the template and assertions. Passing the expected result and reason directly lets the first commit check BLOCK_RESULT_UNSET on that row, so the fix only needs to update the expected result.

Example patch after freezing the clock
diff --git a/src/test/miner_tests.cpp b/src/test/miner_tests.cpp
index 23be18c556..953f33a51c 100644
--- a/src/test/miner_tests.cpp
+++ b/src/test/miner_tests.cpp
@@ -952,52 +952,30 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
     TestSigOpsAdjustedWeightChunkLimit(scriptPubKey, txFirst);
 
     {
-        // Each kind of failure in TestBlockValidity sets its own result
         FakeNodeClock clock{};
         const std::unique_ptr<BlockTemplate> block_template{mining->createNewBlock(options, /*cooldown=*/false)};
         BOOST_REQUIRE(block_template);
         const CBlock template_block{block_template->getBlock()};
-        const auto invalid{[](BlockValidationResult result, const std::string& reason) {
-            BlockValidationState state;
-            state.Invalid(result, reason);
-            return state;
-        }};
-        const auto check_result{[&](auto mutate, const BlockValidationState& expected, bool check_merkle_root = false) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
+        const auto check_result{[&](auto mutate, BlockValidationResult expected_result, const std::string& expected_reason, bool check_merkle_root = false) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
             CBlock block{template_block};
             mutate(block);
             const BlockValidationState state{TestBlockValidity(m_node.chainman->ActiveChainstate(), block,
                                                                /*check_pow=*/false, check_merkle_root)};
-            BOOST_CHECK_EQUAL(state.IsValid(), expected.IsValid());
-            BOOST_CHECK_EQUAL(state.GetResult(), expected.GetResult());
-            BOOST_CHECK_EQUAL(state.GetRejectReason(), expected.GetRejectReason());
+            BOOST_CHECK(expected_reason.empty() ? state.IsValid() : state.IsInvalid());
+            BOOST_CHECK_EQUAL(state.GetResult(), expected_result);
+            BOOST_CHECK_EQUAL(state.GetRejectReason(), expected_reason);
         }};
-        check_result([](CBlock&) {}, BlockValidationState{});
+        check_result([](CBlock&) {}, BlockValidationResult::BLOCK_RESULT_UNSET, "");
         check_result([](CBlock& block) { block.vtx.push_back(block.vtx.at(0)); },
-                     invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-multiple"));
+                     BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-multiple");
         check_result([](CBlock& block) { block.nBits ^= 1; },
-                     invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "bad-diffbits"));
+                     BlockValidationResult::BLOCK_INVALID_HEADER, "bad-diffbits");
         check_result([](CBlock& block) { block.hashMerkleRoot = uint256::ONE; },
-                     invalid(BlockValidationResult::BLOCK_MUTATED, "bad-txnmrklroot"), /*check_merkle_root=*/true);
+                     BlockValidationResult::BLOCK_MUTATED, "bad-txnmrklroot", /*check_merkle_root=*/true);
         check_result([](CBlock& block) { block.nTime = TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()) + MAX_FUTURE_BLOCK_TIME + 1; },
-                     invalid(BlockValidationResult::BLOCK_TIME_FUTURE, "time-too-new"));
-    }
-
-    {
-        // A block whose parent is not the current tip is rejected by TestBlockValidity
-        const std::unique_ptr<BlockTemplate> stale_template{mining->createNewBlock(options, /*cooldown=*/false)};
-        BOOST_REQUIRE(stale_template);
-        CBlock stale_block{stale_template->getBlock()};
-        // Ensure the tip is not genesis
-        const auto& genesis_hash{m_node.chainman->GetParams().GetConsensus().hashGenesisBlock};
-        BOOST_REQUIRE_NE(stale_block.hashPrevBlock, genesis_hash);
-        // Point the block at genesis, so its parent is not the tip
-        stale_block.hashPrevBlock = genesis_hash;
-        BOOST_REQUIRE_NE(stale_block.hashPrevBlock, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
-        const BlockValidationState state{TestBlockValidity(m_node.chainman->ActiveChainstate(), stale_block,
-                                                           /*check_pow=*/false, /*check_merkle_root=*/false)};
-        BOOST_CHECK(state.IsInvalid());
-        BOOST_CHECK_EQUAL(state.GetResult(), BlockValidationResult::BLOCK_PREV_NOT_TIP);
-        BOOST_CHECK_EQUAL(state.GetRejectReason(), "inconclusive-not-best-prevblk");
+                     BlockValidationResult::BLOCK_TIME_FUTURE, "time-too-new");
+        check_result([&](CBlock& block) { block.hashPrevBlock = m_node.chainman->GetConsensus().hashGenesisBlock; },
+                     BlockValidationResult::BLOCK_PREV_NOT_TIP, "inconclusive-not-best-prevblk");
     }
 }
 
The new tests are a bit excessive. The stale-parent case could use this helper too and share the template and assertions. Passing the expected result and reason directly lets the first commit check `BLOCK_RESULT_UNSET` on that row, so the fix only needs to update the expected result. <details><summary>Example patch after freezing the clock</summary> ```diff diff --git a/src/test/miner_tests.cpp b/src/test/miner_tests.cpp index 23be18c556..953f33a51c 100644 --- a/src/test/miner_tests.cpp +++ b/src/test/miner_tests.cpp @@ -952,52 +952,30 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) TestSigOpsAdjustedWeightChunkLimit(scriptPubKey, txFirst); { - // Each kind of failure in TestBlockValidity sets its own result FakeNodeClock clock{}; const std::unique_ptr<BlockTemplate> block_template{mining->createNewBlock(options, /*cooldown=*/false)}; BOOST_REQUIRE(block_template); const CBlock template_block{block_template->getBlock()}; - const auto invalid{[](BlockValidationResult result, const std::string& reason) { - BlockValidationState state; - state.Invalid(result, reason); - return state; - }}; - const auto check_result{[&](auto mutate, const BlockValidationState& expected, bool check_merkle_root = false) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { + const auto check_result{[&](auto mutate, BlockValidationResult expected_result, const std::string& expected_reason, bool check_merkle_root = false) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { CBlock block{template_block}; mutate(block); const BlockValidationState state{TestBlockValidity(m_node.chainman->ActiveChainstate(), block, /*check_pow=*/false, check_merkle_root)}; - BOOST_CHECK_EQUAL(state.IsValid(), expected.IsValid()); - BOOST_CHECK_EQUAL(state.GetResult(), expected.GetResult()); - BOOST_CHECK_EQUAL(state.GetRejectReason(), expected.GetRejectReason()); + BOOST_CHECK(expected_reason.empty() ? state.IsValid() : state.IsInvalid()); + BOOST_CHECK_EQUAL(state.GetResult(), expected_result); + BOOST_CHECK_EQUAL(state.GetRejectReason(), expected_reason); }}; - check_result([](CBlock&) {}, BlockValidationState{}); + check_result([](CBlock&) {}, BlockValidationResult::BLOCK_RESULT_UNSET, ""); check_result([](CBlock& block) { block.vtx.push_back(block.vtx.at(0)); }, - invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-multiple")); + BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-multiple"); check_result([](CBlock& block) { block.nBits ^= 1; }, - invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "bad-diffbits")); + BlockValidationResult::BLOCK_INVALID_HEADER, "bad-diffbits"); check_result([](CBlock& block) { block.hashMerkleRoot = uint256::ONE; }, - invalid(BlockValidationResult::BLOCK_MUTATED, "bad-txnmrklroot"), /*check_merkle_root=*/true); + BlockValidationResult::BLOCK_MUTATED, "bad-txnmrklroot", /*check_merkle_root=*/true); check_result([](CBlock& block) { block.nTime = TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()) + MAX_FUTURE_BLOCK_TIME + 1; }, - invalid(BlockValidationResult::BLOCK_TIME_FUTURE, "time-too-new")); - } - - { - // A block whose parent is not the current tip is rejected by TestBlockValidity - const std::unique_ptr<BlockTemplate> stale_template{mining->createNewBlock(options, /*cooldown=*/false)}; - BOOST_REQUIRE(stale_template); - CBlock stale_block{stale_template->getBlock()}; - // Ensure the tip is not genesis - const auto& genesis_hash{m_node.chainman->GetParams().GetConsensus().hashGenesisBlock}; - BOOST_REQUIRE_NE(stale_block.hashPrevBlock, genesis_hash); - // Point the block at genesis, so its parent is not the tip - stale_block.hashPrevBlock = genesis_hash; - BOOST_REQUIRE_NE(stale_block.hashPrevBlock, m_node.chainman->ActiveChain().Tip()->GetBlockHash()); - const BlockValidationState state{TestBlockValidity(m_node.chainman->ActiveChainstate(), stale_block, - /*check_pow=*/false, /*check_merkle_root=*/false)}; - BOOST_CHECK(state.IsInvalid()); - BOOST_CHECK_EQUAL(state.GetResult(), BlockValidationResult::BLOCK_PREV_NOT_TIP); - BOOST_CHECK_EQUAL(state.GetRejectReason(), "inconclusive-not-best-prevblk"); + BlockValidationResult::BLOCK_TIME_FUTURE, "time-too-new"); + check_result([&](CBlock& block) { block.hashPrevBlock = m_node.chainman->GetConsensus().hashGenesisBlock; }, + BlockValidationResult::BLOCK_PREV_NOT_TIP, "inconclusive-not-best-prevblk"); } } ``` </details>
sedited commented 2026-12-03 14:10:46 +00:00 (Migrated from github.com)

Concept ACK

I think the various items that @l0rinc flagged should be fixed before this is merged.

Concept ACK I think the various items that @l0rinc flagged should be fixed before this is merged.
optout21 (Migrated from github.com) reviewed 2026-12-04 10:27:46 +00:00
optout21 (Migrated from github.com) left a comment

Changed miner_tests.cpp test, appied simplification suggestions from @l0rinc.

git range-diff be10d3d...be64cc

Changed `miner_tests.cpp` test, appied simplification suggestions from @l0rinc. `git range-diff be10d3d...be64cc`
optout21 (Migrated from github.com) commented 2026-12-04 10:22:49 +00:00

Thanks, they can be done as the other tests. Changed, it's more consistent and compact this way.

Thanks, they can be done as the other tests. Changed, it's more consistent and compact this way.
optout21 (Migrated from github.com) commented 2026-12-04 10:20:41 +00:00

Taken

Taken
optout21 commented 2026-12-04 14:15:19 +00:00 (Migrated from github.com)

Additionally applied @hodlinator's string_view nanonit as well.
git range-diff be10d3d...ba6f5df

Additionally applied @hodlinator's `string_view` nanonit as well. `git range-diff be10d3d...ba6f5df`
DrahtBot commented 2026-12-04 15:05:00 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/47351991714/job/145106542860
LLM reason (✨ experimental): iwyu_fail: IWYU reports incorrect includes in minisketch.h and removes an unnecessary include from tx_check.cpp, leaving a diff that causes the check to fail.

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.

  • Intermittent network issues can occur; re-run CI for now, and report the issue if they keep happening.

  • A functional or integration test failure may be intermittent or unrelated to this pull request.
    If no dedicated issue thread exists, create a new one to track it.

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

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `iwyu`: https://github.com/bitcoin/bitcoin/actions/runs/47351991714/job/145106542860</sub> <sub>LLM reason (✨ experimental): iwyu_fail: IWYU reports incorrect includes in minisketch.h and removes an unnecessary include from tx_check.cpp, leaving a diff that causes the check to fail.</sub> <details><summary>Hints</summary> 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. * Intermittent network issues can occur; re-run CI for now, and report the issue if they keep happening. * A functional or integration test failure may be intermittent or unrelated to this pull request. If no dedicated issue thread exists, create a new one to track it. Leave a comment here, if you need help tracking down a confusing failure. </details>
Sign in to join this conversation.
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!36318
No description provided.