Skip to content

test: Add block validation unit tests - #35000

Draft
ismaelsadeeq wants to merge 3 commits into
bitcoin:masterfrom
ismaelsadeeq:04-2026-test-block-validity
Draft

ismaelsadeeq wants to merge 3 commits into
bitcoin:masterfrom
ismaelsadeeq:04-2026-test-block-validity

Conversation

@ismaelsadeeq

@ismaelsadeeq ismaelsadeeq commented Apr 4, 2026 •

Copy link
Copy Markdown
Member

Motivation

Recent work on exposing the Bitcoin kernel C header API, the usage of API, has increased demand for certain changes to block validation, e,g an ongoing effort to modularise block validation #32317. However, validation, especially block, is very critical and changes to it demand the utmost scrutiny and a high bar. Which is most of the time slow and careful code review and testing.
As noticeable during review of #32317, a subtle issue (#32317 (comment)) went unnoticed for some time, which suggests that the current test coverage around block validation paths is not sufficiently comprehensive.
We have a comprehensive block validation functional test but that is not enough because
Block validation today is exercised through multiple entry points, such as TestBlockValidity, ProcessNewBlock, ConnectTip, VerifyDB, so having a structured test suite that targets malformed blocks across those validation paths/simulated ones, and testing invariants to ensure subtle regressions do not slip through review is important.

This PR aims to improve confidence in validation changes by introducing a structured set of unit tests that target specific consensus failure modes, The goal is not to fully de-risk validation changes, but to significantly improve the likelihood of catching subtle bugs early in CI.

Changes

  • This pr introduces block validation unit tests that are split into header, stateless, contextual, and stateful validation cases.

  • The header tests exercise failures related purely to block headers by constructing otherwise valid blocks and mutating header fields, ensuring that header-level checks fail with the expected validation results and reject reasons.

  • The stateless tests include malformed block structures such as missing or multiple coinbase transactions, invalid merkle roots, and duplicate transactions. They also cover transaction-level structural issues such as empty inputs or outputs, invalid output values including negative or overflowing amounts, and duplicate inputs within a transaction. Each test constructs a minimally valid block and then applies targeted mutations to trigger specific consensus failures, verifying both the validation result and the exact reject reason string.

  • The contextual tests cover rules that depend on chain context. These include enforcing correct coinbase height encoding, detecting coinbase overpayment, preventing premature spending of coinbase outputs, and checking transaction finality conditions. These tests rely on the active chain state and ensure that contextual validation correctly rejects blocks that violate consensus rules tied to block height or historical state.

  • The stateful tests construct blocks that spend from UTXO sets and then introduce failures such as missing or already spent inputs, input value overflows, and cases where total inputs are less than total outputs. Script validation failures are also covered by creating real spends that fail script execution under consensus rules. These tests verify that stateful validation correctly enforces value conservation and script correctness.

  • To support these tests, reusable helpers are introduced in test/util/block_validity.h. These helpers centralize the invocation of TestBlockValidity and standardize assertions on validation results, reject reasons, and debug messages. They also provide utilities for constructing spendable UTXOs, which simplifies the creation of stateful test scenarios and improves readability and consistency across tests. The aim is to also add other block validation paths in this util that can be easily invoked by this mutated blocks.

  • These mutated blocks are passed to TestBlockValidity, ProcessNewBlock and ConnectBlock

Open questions

The unit tests added here cover a substantial portion of consensus rules and some soft fork logic, they are not exhaustive. What is considered sufficient?.

@DrahtBot DrahtBot added the Tests label Apr 4, 2026
@DrahtBot

DrahtBot commented Apr 4, 2026 •

Copy link
Copy Markdown
Contributor

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

Code Coverage & Benchmarks

For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/35000.

Reviews

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

Type Reviewers
Approach ACK sedited
Stale ACK w0xlt

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

LLM Linter (✨ experimental)

Possible places where named args for integral literals may be used (e.g. func(x, /*named_arg=*/0) in C++, and func(x, named_arg=0) in Python):

  • SignatureHash(multisig, mtx, 0, SIGHASH_ALL, 1 * COIN, SigVersion::BASE) in src/test/validation_block_stateful_tests.cpp
  • SignatureHash(p2wpkh_script, mtx, 0, SIGHASH_ALL, wrong_value, SigVersion::WITNESS_V0) in src/test/validation_block_stateful_tests.cpp

2026-06-05 16:54:23

@stratospher

Copy link
Copy Markdown
Contributor

have you seen #34651 btw? from a quick skim, this fuzz test looks similar. it uses a wrapper around ConnectBlock instead of calling it directly. or am I missing something?

@ismaelsadeeq

ismaelsadeeq commented Apr 7, 2026 •

Copy link
Copy Markdown
Member Author

have you seen #34651 btw? from a quick skim, this fuzz test looks similar. it uses a wrapper around ConnectBlock instead of calling it directly. Or am I missing something?

Thanks for pointing that out. I wasn’t aware of it. #34651 and the second commit in this PR, e9115735a45289a783b561fe482ab1540b03d076 have a lot in common: both generate a valid block and then mutate its contents.

However, there are some differences. My focus here is on e2e block validity testing, whereas that PR only tests ConnectBlock, which skips ContextualCheckBlock and ContextualCheckBlockHeader.

If we expose something via the kernel (e.g., block validation with external coins), we already have a framework in place for A/B testing. i.e, if TestBlockValidityWithSpentTxOuts is given the same coins and uses a valid known chain index, the output should correlate; otherwise, they may diverge, that kind of thing.

But it would also be useful to have shared utilities for some of the things we have in common, so that we don't repeat ourselves.

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

Built and ran all four new test suites locally (header, stateless, contextual, stateful), 49/49 pass. Two things inline.

@ismaelsadeeq
ismaelsadeeq force-pushed the 04-2026-test-block-validity branch from e911573 to f1d2302 Compare April 7, 2026 19:18
@ismaelsadeeq

Copy link
Copy Markdown
Member Author

Forced pushed from e9115735a45289a783b561fe482ab1540b03d076 to f1d2302ecc9abe72f15197f5ce40ed0ed46686a9 compare

@ismaelsadeeq ismaelsadeeq changed the title test: Add block validation unit tests + fuzz target for TestBlockValidity test: Add block validation unit tests + fuzz harness for TestBlockValidity Apr 10, 2026
@marcofleon

Copy link
Copy Markdown
Contributor

I agree that the fuzz test looks a bit redundant with #34651. And I'm not sure it's worth having this PR's harness only as a way to cover the contextual checks.

Here is some validation coverage to compare:

validation_block_validity from this PR

connect_block from 34651

full coverage from all fuzz tests on master

Looking at the coverage, connect_block reaches a lot of the same lines as validation_block_validity does wrt to the ConnectBlock path and it also provides more diverse inputs. And then the contextual checks seem already pretty well covered by our existing fuzz tests (assuming we have strong oracles scattered throughout validation). I think it could make sense to drop the fuzz target here and focus on the unit tests, which look well-written to me.

@ismaelsadeeq

Copy link
Copy Markdown
Member Author

Thanks for taking a look at this @marcofleon
To reiterate, when I pushed this, I did know about #34651. My rationale is explained in the description and this comment #35000 (comment)

But I agree, it will be better to spend more effort on #34651 since it has received a couple of review rounds already. I will review that PR and make some suggestions that will make #35000 (comment) achievable there.

In the meantime, I will remove the fuzz commit here, even if we move forward in this direction, you can argue that the fuzz test deserve it's own PR.

@ismaelsadeeq
ismaelsadeeq force-pushed the 04-2026-test-block-validity branch from f1d2302 to 26b1e0b Compare April 10, 2026 16:11
@ismaelsadeeq ismaelsadeeq changed the title test: Add block validation unit tests + fuzz harness for TestBlockValidity test: Add block validation unit tests Apr 10, 2026
@ismaelsadeeq

Copy link
Copy Markdown
Member Author

Forced pushed from f1d2302 to 26b1e0b

Pruned the fuzz harness added here in favour of the one in #34651

@w0xlt

w0xlt commented Apr 12, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

@sedited

sedited commented Apr 22, 2026

Copy link
Copy Markdown
Contributor

Approach ACK

This looks like a good place to start - having all these cases is valuable. I think the current scope is fine, but I would call these TestBlockValidity unit tests, and not "block validation". These skip some checks that run in the Accept* functions and don't necessarily reflect the validation steps executed by the actual hot validation path. As far as I can tell the tests here don't exercise BLOCK_MISSING_PREV and BLOCK_INVALID_PREV.

Can we add the same checks through ProcessNewBlock by subscribing to the BlockChecked validation interface event?

As an addition I would also be interested in calling ConnectBlock directly with these invalid blocks. I think that would require some re-plumbing though to catch the various errors and validation states.

The distinction into the separate validation classes makes sense to me. Instead of splitting them up into separate tests I am wondering if we could tag them with an enum and then pass them to various entry points of validation (i.e. TestBlockValidity, ProcessNewBlock, ConnectBlock). The tests can then react to their failures based on their assigned validation variant, i.e. for contextual checks ConnectBlock does not expect failures, but other validation functions do.

@ismaelsadeeq
ismaelsadeeq force-pushed the 04-2026-test-block-validity branch from 26b1e0b to 5ae4c0c Compare April 23, 2026 12:22
@ismaelsadeeq
ismaelsadeeq force-pushed the 04-2026-test-block-validity branch from 5ae4c0c to 8e556cd Compare April 28, 2026 18:25
@ismaelsadeeq

Copy link
Copy Markdown
Member Author

I appreciate the review so far. I will spend some time to complete this by incorporating more tests beyond TestBlockValidity. In the meantime, I will move this to draft.

@ismaelsadeeq
ismaelsadeeq marked this pull request as draft April 28, 2026 18:58
@ismaelsadeeq
ismaelsadeeq force-pushed the 04-2026-test-block-validity branch from 8e556cd to 0d73f0d Compare May 27, 2026 14:15
@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/26516809572/job/78098993428
LLM reason (✨ experimental): CI failed due to a C++ build error in test_bitcoin (block_validity.h/cpp): node::BlockAssembler has no Options type (leading to multiple compiler errors).

Hints

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

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

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

  • An intermittent issue.

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

@ismaelsadeeq
ismaelsadeeq force-pushed the 04-2026-test-block-validity branch from 0d73f0d to c9d6eb5 Compare May 28, 2026 14:43
@ismaelsadeeq
ismaelsadeeq marked this pull request as ready for review May 28, 2026 16:55
@ismaelsadeeq

Copy link
Copy Markdown
Member Author

I forced pushed from 8e556cdf59db04bb604554e7fb9b8a2ce345f2a3 to c9d6eb5d9d1db6d6c0ffc9096932d40b121b2875 compare_diff

These skip some checks that run in the Accept* functions and don't necessarily reflect the validation steps executed by the actual hot validation path. As far as I can tell the tests here don't exercise BLOCK_MISSING_PREV and BLOCK_INVALID_PREV.

These tests are added now

Can we add the same checks through ProcessNewBlock by subscribing to the BlockChecked validation interface event?

Done in the recent push.

Instead of splitting them up into separate tests I am wondering if we could tag them with an enum and then pass them to various entry points of validation (i.e. TestBlockValidity, ProcessNewBlock, ConnectBlock). The tests can then react to their failures based on their assigned validation variant, i.e. for contextual checks ConnectBlock does not expect failures, but other validation functions do.

Hmm, won't this be more involved? I would like to keep it simple as it is currently, if you don't feel strongly about this.

Also, I limit this to just TestBlockValidity, ProcessNewBlock and ConnectBlock. I think this suffices for now;
The block validation parts VerifyDB and ConnectTip just call ConnectBlock anyway, so independent calls of connectBlock added recently due to @sedited suggestion should cover them.

@w0xlt w0xlt 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 c9d6eb5d9d1db6d6c0ffc9096932d40b121b2875

Some non-blocking nits:

@DrahtBot
DrahtBot requested a review from sedited June 4, 2026 01:10
@ismaelsadeeq
ismaelsadeeq force-pushed the 04-2026-test-block-validity branch from c9d6eb5 to ccfc344 Compare June 5, 2026 16:53
@ismaelsadeeq

Copy link
Copy Markdown
Member Author

Forced pushed from c9d6eb5d9d1db6d6c0ffc9096932d40b121b2875 to ccfc344 compare diff

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

After all the discussions we had about moving towards a more declarative testing style that avoids CMutableTransaction, I tried to imagine how this suite of tests could look if they were implemented in that way. I think it would get us pretty close to the existing test declarations for the script and interpreter tests. However, for the rests written as they are now, I don't think that provides any meaningful value.

If we want to add way more cases for exercising edge cases and boundary conditions, then I could see the benefits for a more declarative, vectorized style. What are your thought on this?

/** Create a new block template using the provided options. */
CBlock MakeBlock(node::BlockCreateOptions options = {});
/** Reset all cached validity flags (fChecked, m_checked_merkle_root, m_checked_witness_commitment). */
void ResetBlock(CBlock& block);

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.

Could ResetBlock, MakeBlock, and AddCoin better fit as standalone functions in util/mining.h? Maybe SolveBlockPow could be moved over there as well and be called in MineBlock and some of the other blaces where we are mining in the tests.

Comment on lines +12 to +15
/**
* ValidationBlockValidityTestingSetup relies on TestChain100Setup, which
* mines 100 blocks during initialization.
*/

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.

This comment seems redundant, inheriting from TestChain100Setup seems enough of an explainer to me.

Chainstate& m_chainstate{m_node.chainman->ActiveChainstate()};
const Consensus::Params& m_params{m_node.chainman->GetParams().GetConsensus()};

/** Create a new block template using the provided options. */

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.

Is this comment outdated? Looks like it is returning a block now, not a template.

Comment on lines +34 to +44
const int max_trials{5};
for (int trial_idx = 0; trial_idx < max_trials; ++trial_idx) {
COutPoint outpoint{Txid::FromUint256(m_rng.rand256()), 0};
LOCK(cs_main);
if (m_chainstate.CoinsTip().AccessCoin(outpoint).IsSpent()) {
m_chainstate.CoinsTip().AddCoin(outpoint, Coin(CTxOut(amount, script_pub_key), 1, false), true);
return outpoint;
}
}
BOOST_REQUIRE_MESSAGE(false, "AddCoin: failed to find an unused outpoint");
return {};

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.

A collision seems unlikely to me given we are streaming 256 bits from the chacha keystream. Even if so, would trying again five times really help? The possible_overwrite argument could also be set to false (and should get a /*=*/ arg comment).

*/
BOOST_FIXTURE_TEST_SUITE(validation_block_contextual_tests, ValidationBlockValidityTestingSetup)

BOOST_AUTO_TEST_CASE(tbv_immature_coinbase)

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'm a bit confused about what exactly should be in this file. The comment says this should cover ContextualCheckBlock, but some of these are only called in ConnectBlock, like this one and bad-cb-amount, and others like the witness malleation checks are in another file.

const auto debug = "block timestamp too far in the future";
CheckBlockInvalid(TestValidity(block), BlockValidationResult::BLOCK_TIME_FUTURE, reason, debug);
}

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.

Do you want to add a test for timewarp?

mtx.vout[0].nValue = 49 * COIN;
block.vtx.emplace_back(MakeTransactionRef(std::move(mtx)));
RegenerateCommitments(block, *m_node.chainman);
const auto reason = "block-script-verify-flag-failed (Script evaluated without error but finished with a false/empty top stack element)";

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.

Isn't one case exercising the block-script-verify-flag-failed failure enough? The other script failure cases should already be covered exhaustively in the interpreter tests.

CheckBlockInvalid(TestValidity(block), BlockValidationResult::BLOCK_CONSENSUS, reason, debug);
}

BOOST_AUTO_TEST_CASE(tbv_bad_cb_amount)

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.

Might it be interesting to add another test that checks coinbase amounts for a block with some fees and multiple coinbase outputs?

CheckBlockInvalid(TestValidity(block), BlockValidationResult::BLOCK_CONSENSUS, reason, debug);
}

BOOST_AUTO_TEST_CASE(tbv_bad_txns_inputs_missingorspent)

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.

Could this be extended with a check for chains of transactions within a block?

CheckBlockValid(TestValidity(block));
}

BOOST_AUTO_TEST_SUITE_END()

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.

Can you add a case here that exercises the SequenceLocks failure ("contains a non-BIP68-final transasction")?

@ismaelsadeeq
ismaelsadeeq marked this pull request as draft September 24, 2026 12:44
@ismaelsadeeq

Copy link
Copy Markdown
Member Author

re: #35000 (review)

Drafted, while I evaluate and attempt recent feedback from @sedited, declarative unit testing would be ideally better here.

I will get back to this soon, for now my focus is on something else. Thanks for the feedback.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants