validation: Ensure Invalid ValidationState has result #36318

pull optout21 wants to merge 5 commits into bitcoin:master from optout21:2609-invalid-must-have-reason changing 11 files +77 −11
  1. optout21 commented at 11:51 AM on September 23, 2026: 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 (review).

    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.
  2. DrahtBot added the label Validation on Sep 23, 2026
  3. DrahtBot commented at 11:51 AM on September 23, 2026: contributor

    <!--e57a25ab6845829454e8d69fc972939a-->

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

    <!--006a51241073e994b41acfe9ec718e94-->

    External sites

    <!--021abf342d371248e50ceaed478a90ca-->

    Reviews

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

    Type Reviewers
    Stale ACK Pranav-error, hodlinator, Sjors

    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 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36852.svg"></sub> (test: split CreateNewBlock_validity into independent test cases by yuvicc)
    • #36156 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36156.svg"></sub> (mining: include chunks that reach block limits by l0rinc)
    • #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-->

  4. optout21 commented at 11:54 AM on September 23, 2026: contributor

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

  5. hodlinator commented at 12:20 PM on September 23, 2026: contributor

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

  6. optout21 commented at 4:00 PM on September 23, 2026: contributor

    Undrafting upon clean CI

  7. optout21 marked this as ready for review on Sep 23, 2026
  8. sedited requested review from hodlinator on Nov 5, 2026
  9. in src/consensus/validation.h:105 in 22cf9d54b3
     102 |      {
     103 |          m_result = result;
     104 |          m_reject_reason = reject_reason;
     105 |          m_debug_message = debug_message;
     106 |          if (m_mode != ModeState::M_ERROR) m_mode = ModeState::M_INVALID;
     107 | +        Assume(m_result != Result{} && !m_reject_reason.empty());
    


    hodlinator commented at 3:44 PM on November 6, 2026:

    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;
    

    optout21 commented at 7:32 AM on November 27, 2026:

    For completeness: this has been applied earlier.

  10. hodlinator commented at 3:47 PM on November 6, 2026: contributor

    Concept ACK 22cf9d54b3fd9561b6b3ad057264dcb2ddbfef56

    Good call on making reject_reason required too.

  11. optout21 force-pushed on Nov 10, 2026
  12. optout21 commented at 2:24 PM on November 10, 2026: contributor

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

    git range-diff 22cf9d54b3fd9561b6b3ad057264dcb2ddbfef56...4b8b7bd78f70bd1f2598a0eb0401c0a9bb8be124
    git range-diff 22cf9d54b3fd9561b6b3ad057264dcb2ddbfef56...ba0d2b49f526b789ab758bc25f909344b2b092c1
    
  13. Sjors commented at 10:23 AM on November 11, 2026: member

    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.

  14. DrahtBot requested review from hodlinator on Nov 11, 2026
  15. in src/consensus/validation.h:75 in ba0d2b49f5
      70 | @@ -70,7 +71,8 @@ enum class BlockValidationResult {
      71 |      BLOCK_MISSING_PREV,      //!< We don't have the previous block the checked one is built on
      72 |      BLOCK_INVALID_PREV,      //!< A block this one builds on is invalid
      73 |      BLOCK_TIME_FUTURE,       //!< block timestamp was > 2 hours in the future (or our clock is bad)
      74 | -    BLOCK_HEADER_LOW_WORK    //!< the block header may be on a too-little-work chain
      75 | +    BLOCK_HEADER_LOW_WORK,   //!< the block header may be on a too-little-work chain
      76 | +    BLOCK_INCONCLUSIVE,      //!< validity could not be determined (e.g. we don't have the block it's building on)
    


    hodlinator commented at 4:19 PM on November 11, 2026:

    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)
    
  16. in src/consensus/validation.h:1 in ba0d2b49f5 outdated


    hodlinator commented at 5:47 PM on November 11, 2026:

    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.

  17. hodlinator commented at 6:41 PM on November 11, 2026: contributor

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

  18. sedited requested review from mzumsande on Nov 12, 2026
  19. Pranav-error commented at 8:27 PM on November 12, 2026: none

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

  20. optout21 commented at 7:27 AM on November 19, 2026: contributor

    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.

  21. mzumsande commented at 6:08 PM on November 19, 2026: contributor

    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?

  22. optout21 commented at 11:16 AM on November 20, 2026: contributor

    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.

  23. optout21 commented at 11:12 AM on November 23, 2026: contributor

    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.

  24. hodlinator commented at 11:46 AM on November 23, 2026: contributor

    A more specific BLOCK_PREV_NOT_TIP sounds good to me.

  25. optout21 commented at 7:40 PM on November 23, 2026: contributor

    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)

  26. optout21 force-pushed on Nov 23, 2026
  27. hodlinator approved
  28. hodlinator commented at 9:34 AM on November 24, 2026: contributor

    re-ACK be5ff46547675d6cd329aad7778a32f4192fe605

    Switched to more precise enum name and added unit test.

  29. DrahtBot requested review from Sjors on Nov 24, 2026
  30. optout21 commented at 12:14 PM on November 24, 2026: contributor

    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.

  31. Pranav-error commented at 4:11 PM on November 24, 2026: none

    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.

  32. Sjors commented at 11:01 AM on November 26, 2026: 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.

  33. in src/test/miner_tests.cpp:984 in 8d9aed91ad outdated
     979 | +        stale_block.hashPrevBlock = genesis_hash;
     980 | +        BOOST_REQUIRE_NE(stale_block.hashPrevBlock, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
     981 | +        const BlockValidationState state{TestBlockValidity(m_node.chainman->ActiveChainstate(), stale_block,
     982 | +                                                           /*check_pow=*/false, /*check_merkle_root=*/false)};
     983 | +        BOOST_CHECK(state.IsInvalid());
     984 | +        BOOST_CHECK_EQUAL(state.GetResult(), BlockValidationResult::BLOCK_PREV_NOT_TIP);
    


    Sjors commented at 11:09 AM on November 26, 2026:

    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:

        {
            // 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 commented at 7:35 AM on November 27, 2026:

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

  34. Sjors approved
  35. Sjors commented at 11:22 AM on November 26, 2026: member

    ACK be5ff46547675d6cd329aad7778a32f4192fe605

  36. test: Check TestBlockValidity() error returns
    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.
    bf0d58d32a
  37. validation: Add BlockValidationResult::BLOCK_PREV_NOT_TIP
    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.
    edab66496e
  38. validation: In TestBlockValidity, use BLOCK_PREV_NOT_TIP
    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.
    a319245e04
  39. validation: Ensure that Invalid ValidationState always has a result
    Ensure that an Invalid `ValidationState`, constructed through `Invalid()`,
    always has a set result field, by using an `Assume`.
    This increases code robustness/security.
    39085d6963
  40. validation: Ensure Invalid ValidationState has non-empty reject_reason
    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.
    be10d3d5cf
  41. optout21 commented at 7:34 AM on November 27, 2026: contributor

    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.

  42. optout21 force-pushed on Nov 27, 2026
  43. optout21 commented at 7:36 AM on November 27, 2026: contributor

    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


github-metadata-mirror

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

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