Repository navigation
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
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. |
|
CC: @Sjors (author of #31981), @hodlinator (reviewer of #35570). |
|
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. |
|
Undrafting upon clean CI |
hodlinator
left a comment
There was a problem hiding this comment.
Concept ACK 22cf9d5
Good call on making reject_reason required too.
| 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()); |
There was a problem hiding this comment.
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:
| 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; |
There was a problem hiding this comment.
For completeness: this has been applied earlier.
22cf9d5 to
ba0d2b4
Compare
|
Applied nit from review comment -- thanks! |
|
ACK ba0d2b4 The mining (validity check) code has no use for the |
hodlinator
left a comment
There was a problem hiding this comment.
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,| 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) |
There was a problem hiding this comment.
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)There was a problem hiding this comment.
Searched for cases where we might be skipping over testing for BLOCK_INCONCLUSIVE such as:
Line 1984 in 232cb54
But all 3 similar cases I could find had not called into TestBlockValidity(), so shouldn't need to account for that.
|
crACK ba0d2b4 Reviewed the invariant change and its blast radius:
Nit (non-blocking): the Code-review only (didn't build/run). |
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
left a comment
There was a problem hiding this comment.
I acknowledge this, indeed the example could be closer to the current usage. I think it's very minor, as this is only an example in the comment.
I'd agree if this was a random test file, but comments in consensus/validation.h should be clear in my opinion - e.g. just from reading the file it wouldn't be clear which of the two enum values a block with a missing prev would get.
More generally, I find the state of the enum kind of confusing:
The preexisting BLOCK_MISSING_PREV , BLOCK_HEADER_LOW_WORK (and to some extent BLOCK_TIME_FUTURE) all describe specific inconclusive scenarios (we don't know if it is valid, refuse to validate, or it may become valid in the future), so it's not clear to me what a BLOCK_INCONCLUSIVE category should cover. Is this meant to become a kitchen-sink category for "all the rest"? Otherwise wouldn't it be more in line with the existing approach to call it BLOCK_PREV_NOT_TIP or similar?
|
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
I lean towards the first option and will rename unless there are objections. |
That's also a potential solution, I agree. I categorize these approaches:
The latter two introduce inconsistencies in the code (a bit "hacky"), therefore I chose 1. |
|
A more specific |
|
Changes applied:
( |
ba0d2b4 to
be5ff46
Compare
hodlinator
left a comment
There was a problem hiding this comment.
re-ACK be5ff46
Switched to more precise enum name and added unit test.
|
I've came up with another solution alternative:
I've added this (and other alternatives) to the description. I'm looking forward for assessments from reviewers. |
|
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. |
Adding a whole new If I understand correctly:
It's true that current p2p code doesn't use |
| 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); |
There was a problem hiding this comment.
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");
}There was a problem hiding this comment.
Applied, slightly extended, with check for validity as well.
Thanks for the ready-prepared snippet!
There was a problem hiding this comment.
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.
Thanks @hodlinator and @Sjors for sharing feedback on the proposed alternative, I also reached a similar conclusion, and discarded the alternative. |
be5ff46 to
be10d3d
Compare
optout21
left a comment
There was a problem hiding this comment.
I've applied @Sjors's suggestions for the test:
- The unit test check for
TestBlockValidity()returns in the stale block case has been moved earlier. - The unit test has been extended with checks for other error cases (slightly extended, with check for validity as well).
git range-diff be5ff46..be10d3d
| 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); |
There was a problem hiding this comment.
Applied, slightly extended, with check for validity as well.
Thanks for the ready-prepared snippet!
hodlinator
left a comment
There was a problem hiding this comment.
re-ACK be10d3d
Nice to see increased unit test coverage of other enum values.
| const std::string& reject_reason, | ||
| const std::string& debug_message = {}) |
There was a problem hiding this comment.
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):
| const std::string& reject_reason, | |
| const std::string& debug_message = {}) | |
| std::string_view reject_reason, | |
| std::string_view debug_message = {}) |
|
ACK be10d3d |
|
Retested the latest head (
One thing: the new Debug, fuzz, test_kernel and functional tests are still pending |
|
Thanks for the (re)reviews! RFM? Or need to call in more reviewers? |
There was a problem hiding this comment.
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.
| 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; }, |
There was a problem hiding this comment.
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()};| 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); |
There was a problem hiding this comment.
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");
}
}
|
Concept ACK I think the various items that @l0rinc flagged should be fixed before this is merged. |

Block and transaction validation results are represented in
ValidationState, and invalid results in "Invalid" states. Invalid validation results have aresult, an enum value, and areject_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_INCONCLUSIVEresult. PR #31981 moved a previous-block check from outside ofTestBlockValidity()to inside it, and introduced a new usage ofBlockValidationStatewith unset result. The result field is not checked outside. This instance is changed now to use the newly-introducedBLOCK_INCONCLUSIVEvalue.The new enum value is added to the kernel C API and its C++ wrapper. In P2P, a
BLOCK_INCONCLUSIVEresult 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:
TestBlockValidity(), e.g. usingutil::Expected, as you discussed. No need to touch theBlockValidationResultenum. However, in the call sites ofTestBlockValidity(), the reject reason and debug strings are handled similarly to other non-valid check results, and they would need a special handling.TestBlockValidity(), with the comment "only in this spot it means a little different thing".TestBlockValidationResult, "on top of"BlockValidationResult, with the extra value, and a specialTestBlockValidationState(ValidationState<TestBlockValidationResult>). Use this inTestBlockValidity(). 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.