Repository navigation
test: Add block validation unit tests - #35000
ismaelsadeeq wants to merge 3 commits into
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. Code Coverage & BenchmarksFor details see: https://corecheck.dev/bitcoin/bitcoin/pulls/35000. ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste LLM Linter (✨ experimental)Possible places where named args for integral literals may be used (e.g.
2026-06-05 16:54:23 |
|
have you seen #34651 btw? from a quick skim, this fuzz test looks similar. it uses a wrapper around |
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 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 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
left a comment
There was a problem hiding this comment.
Built and ran all four new test suites locally (header, stateless, contextual, stateful), 49/49 pass. Two things inline.
e911573 to
f1d2302
Compare
|
Forced pushed from e9115735a45289a783b561fe482ab1540b03d076 to f1d2302ecc9abe72f15197f5ce40ed0ed46686a9 compare
|
TestBlockValidityTestBlockValidity
|
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, |
|
Thanks for taking a look at this @marcofleon 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. |
f1d2302 to
26b1e0b
Compare
TestBlockValidity|
Concept ACK |
|
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 Can we add the same checks through As an addition I would also be interested in calling 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. |
26b1e0b to
5ae4c0c
Compare
5ae4c0c to
8e556cd
Compare
|
I appreciate the review so far. I will spend some time to complete this by incorporating more tests beyond |
8e556cd to
0d73f0d
Compare
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
0d73f0d to
c9d6eb5
Compare
|
I forced pushed from 8e556cdf59db04bb604554e7fb9b8a2ce345f2a3 to c9d6eb5d9d1db6d6c0ffc9096932d40b121b2875 compare_diff
These tests are added now
Done in the recent push.
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 |
w0xlt
left a comment
There was a problem hiding this comment.
ACK c9d6eb5d9d1db6d6c0ffc9096932d40b121b2875
Some non-blocking nits:
c9d6eb5 to
ccfc344
Compare
|
Forced pushed from c9d6eb5d9d1db6d6c0ffc9096932d40b121b2875 to ccfc344 compare diff
|
sedited
left a comment
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
| /** | ||
| * ValidationBlockValidityTestingSetup relies on TestChain100Setup, which | ||
| * mines 100 blocks during initialization. | ||
| */ |
There was a problem hiding this comment.
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. */ |
There was a problem hiding this comment.
Is this comment outdated? Looks like it is returning a block now, not a template.
| 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 {}; |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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); | ||
| } | ||
|
|
There was a problem hiding this comment.
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)"; |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
Could this be extended with a check for chains of transactions within a block?
| CheckBlockValid(TestValidity(block)); | ||
| } | ||
|
|
||
| BOOST_AUTO_TEST_SUITE_END() |
There was a problem hiding this comment.
Can you add a case here that exercises the SequenceLocks failure ("contains a non-BIP68-final transasction")?
|
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. |
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,ProcessNewBlockandConnectBlockOpen 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?.