Skip to content

validation: Ensure Invalid ValidationState has result - #36318

Open
optout21 wants to merge 5 commits into
bitcoin:masterfrom
optout21:2609-invalid-must-have-reason
Open

optout21 wants to merge 5 commits into
bitcoin:masterfrom
optout21:2609-invalid-must-have-reason

Conversation

@optout21

@optout21 optout21 commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

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 #35570 (comment) and #35570 (comment).

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

DrahtBot commented Sep 23, 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
ACK hodlinator, Sjors, mzumsande, l0rinc
Concept ACK sedited
Stale ACK Pranav-error

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.

@optout21

Copy link
Copy Markdown
Contributor Author

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

@hodlinator

Copy link
Copy Markdown
Contributor

From what I deduce the defaulted result enum was suggested in the diff posted by @ryanofsky in #31981 (comment), so he might also be interested in this.

@optout21

Copy link
Copy Markdown
Contributor Author

Undrafting upon clean CI

@hodlinator hodlinator 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 22cf9d5

Good call on making reject_reason required too.

Comment thread src/consensus/validation.h Outdated
Comment on lines +101 to +105
m_result = result;
m_reject_reason = reject_reason;
m_debug_message = debug_message;
if (m_mode != ModeState::M_ERROR) m_mode = ModeState::M_INVALID;
Assume(m_result != Result{} && !m_reject_reason.empty());

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.

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:

Suggested change
m_result = result;
m_reject_reason = reject_reason;
m_debug_message = debug_message;
if (m_mode != ModeState::M_ERROR) m_mode = ModeState::M_INVALID;
Assume(m_result != Result{} && !m_reject_reason.empty());
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;

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.

For completeness: this has been applied earlier.

@optout21
optout21 force-pushed the 2609-invalid-must-have-reason branch from 22cf9d5 to ba0d2b4 Compare November 10, 2026 14:24
@optout21

Copy link
Copy Markdown
Contributor Author

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

git range-diff 22cf9d54b3fd9561b6b3ad057264dcb2ddbfef56...4b8b7bd78f70bd1f2598a0eb0401c0a9bb8be124
git range-diff 22cf9d54b3fd9561b6b3ad057264dcb2ddbfef56...ba0d2b49f526b789ab758bc25f909344b2b092c1

@Sjors

Sjors commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

ACK ba0d2b4

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.

@DrahtBot
DrahtBot requested a review from hodlinator November 11, 2026 10:23

@hodlinator hodlinator left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ACK ba0d2b4

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,

Comment thread src/consensus/validation.h Outdated
BLOCK_TIME_FUTURE, //!< block timestamp was > 2 hours in the future (or our clock is bad)
BLOCK_HEADER_LOW_WORK //!< the block header may be on a too-little-work chain
BLOCK_HEADER_LOW_WORK, //!< the block header may be on a too-little-work chain
BLOCK_INCONCLUSIVE, //!< validity could not be determined (e.g. we don't have the block it's building on)

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.

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)

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.

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

if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {

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

@sedited
sedited requested a review from mzumsande November 12, 2026 14:13
@Pranav-error

Copy link
Copy Markdown

crACK ba0d2b4

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

Copy link
Copy Markdown
Contributor Author

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

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

Copy link
Copy Markdown
Contributor Author

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

Copy link
Copy Markdown
Contributor Author

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

Copy link
Copy Markdown
Contributor

A more specific BLOCK_PREV_NOT_TIP sounds good to me.

@optout21

Copy link
Copy Markdown
Contributor Author

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)

@optout21
optout21 force-pushed the 2609-invalid-must-have-reason branch from ba0d2b4 to be5ff46 Compare November 23, 2026 19:40

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

re-ACK be5ff46

Switched to more precise enum name and added unit test.

@DrahtBot
DrahtBot requested a review from Sjors November 24, 2026 09:34
@optout21

Copy link
Copy Markdown
Contributor Author

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: optout21#32

I'm looking forward for assessments from reviewers.

@Pranav-error

Copy link
Copy Markdown

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

Sjors commented Nov 26, 2026

Copy link
Copy Markdown
Member

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

ACK be5ff46

Comment thread src/test/miner_tests.cpp
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);

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 8d9aed9 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");
    }

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.

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

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.

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");
     }
 }
 

Extend the unit test to check the errors returned from TestBlockValidity().
It records the current usage for stale block, that is being changed
in the next commits.
The goal is to ensure that an Invalid `ValidationState` always has a set result.
However, there is a violating usage in `TestBlockValidity`.
As a preparation, a new value is added to the `BlockValidationResult`
enum, `BLOCK_PREV_NOT_TIP`, representing a result for when
the block being mined is not built on top of the current tip.
In P2P, a `BLOCK_PREV_NOT_TIP` result does not lead to punishing the peer.
A corresponding value is added to the kernel C API
(btck_BlockValidationResult_PREV_NOT_TIP) and its C++ wrapper, though
not returned by current kernel API functions.
The new value is used in a later commit.
The goal is to ensure that an Invalid `ValidationState` always has a set result.
A violating usage in `TestBlockValidity` is being changed: instead of the
default `BLOCK_RESULT_UNSET`, it now uses `BLOCK_PREV_NOT_TIP`.
The result field from `TestBlockValidity` is currently not inspected by callers,
but the constraint "an Invalid state must have a set result"
is satisfied this way.
Also adjust the unit test.
Ensure that an Invalid `ValidationState`, constructed through `Invalid()`,
always has a set result field, by using an `Assume`.
This increases code robustness/security.
In addition to ensuring a set result, also ensure that `reject_reason`
is not empty for an Invalid `ValidationState`.
Also remove its empty default value, as it should never be empty.
Some test-only usages, where empty reject reason was used, are changed
to use a dummy value.
@optout21

Copy link
Copy Markdown
Contributor Author

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
optout21 force-pushed the 2609-invalid-must-have-reason branch from be5ff46 to be10d3d Compare November 27, 2026 07:36

@optout21 optout21 left a comment

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.

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

Comment thread src/test/miner_tests.cpp
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);

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.

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

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

re-ACK be10d3d

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

Comment on lines +98 to +99
const std::string& reject_reason,
const std::string& debug_message = {})

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.

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

Suggested change
const std::string& reject_reason,
const std::string& debug_message = {})
std::string_view reject_reason,
std::string_view debug_message = {})

@DrahtBot
DrahtBot requested a review from Sjors November 30, 2026 09:33
@Sjors

Sjors commented Dec 1, 2026

Copy link
Copy Markdown
Member

ACK be10d3d

@mzumsande mzumsande left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review ACK be10d3d

@Pranav-error

Copy link
Copy Markdown

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

optout21 commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

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

@l0rinc l0rinc left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ACK be10d3d

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.

Comment thread src/test/miner_tests.cpp
invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "bad-diffbits"));
check_result([](CBlock& block) { block.hashMerkleRoot = uint256::ONE; },
invalid(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; },

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.

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

Comment thread src/test/miner_tests.cpp
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);

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.

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");
     }
 }
 

@sedited

sedited commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

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

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