mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 16:02:38 +00:00
validation: Ensure Invalid ValidationState has result #36318
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!36318
Loading…
Reference in a new issue
No description provided.
Delete branch "2609-invalid-must-have-reason"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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 https://github.com/bitcoin/bitcoin/pull/35570#issuecomment-5739477357 and https://github.com/bitcoin/bitcoin/pull/35570#discussion_r4075379069.
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.The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.
External sites
Reviews
See the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste
<!--meta-tag:bot-skip-->into the comment that the bot should ignore.Conflicts
Reviewers, this pull request conflicts with the following ones:
CreateNewBlock_validityinto independent test cases by yuvicc)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 https://github.com/bitcoin/bitcoin/pull/31981#discussion_r2087339443, so he might also be interested in this.
Undrafting upon clean CI
Earlier concerns neither republished nor resolved: 2 suggestions. See the Run archive linked from the Review report for their assessments.
🔵 Suggestion ·
TestBlockValidity()result tests do not distinguish invalid states from errorsThe new
TestBlockValidity()assertions would still pass if an invalid result became an error, despite the differentgetblocktemplateproposal response.Location:
src/test/miner_tests.cpp:987(head).🔵 Suggestion · PR description still names
BLOCK_INCONCLUSIVEThe PR description identifies the new result as
BLOCK_INCONCLUSIVE, but the code adds and usesBLOCK_PREV_NOT_TIP.Location:
src/consensus/validation.h:76(head).Review coverage was incomplete.
Reviewed:
ba6f5df60ba8· Review report · Previous reportspermalink
Concept ACK
22cf9d54b3Good call on making
reject_reasonrequired too.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:
Applied nit from review comment -- thanks!
Also rebased (no invalidated reviews)
ACK
ba0d2b49f5The mining (validity check) code has no use for the
BlockValidationResultenum so it was easy to ignore. The newAssumestatements should ensure we don't do that again.ACK
ba0d2b49f5Alternative solution
Instead of expanding
BlockValidationResultone could wrap the return value ofTestBlockValidity()withutil::Expectedsince it's the only function that returns this error. On the other hand,BlockValidationStateis 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
Searched for cases where we might be skipping over testing for
BLOCK_INCONCLUSIVEsuch as:github.com/bitcoin/bitcoin@232cb5410a/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.Saw
inconclusive-not-best-prevblkis covered in 2 functional tests. Not sure if it would add anything to also have a unit test covering the enum.crACK
ba0d2b49f5Reviewed the invariant change and its blast radius:
MaybePunishNodeForBlock'sswitch(net_processing.cpp:538) has nodefault:, soBLOCK_INCONCLUSIVEhad to be handled explicitly — the addedcase ... break;(no punishment) is right: the only producer isTestBlockValidity()(block-template/submitblockvalidity testing, not network-received blocks), so a peer should never be punished for it, andbreakkeepsnDoSat 0. Matches @Sjors' point that the validity path doesn't consume the enum.reject_reasonnow required +Assume(!reject_reason.empty()): checked the callers that passed""— the fuzz targetstxdownloadman.cpp:223/357/420and thetxdownload_tests.cppcases. These matter becauseAssumeis fatal under a fuzz build, so an un-updatedInvalid(result, "")would abort the fuzzer; the PR updates all of them to"dummy-reason", so the invariant is complete.TestBlockValidity:Invalid({}, ...)→Invalid(BLOCK_INCONCLUSIVE, ...)) removes the one unset-result path.Nit (non-blocking): the
BLOCK_INCONCLUSIVEcomment — "...e.g. we don't have the block it's building on" — reads close toBLOCK_MISSING_PREVand 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).
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.
I'd agree if this was a random test file, but comments in
consensus/validation.hshould 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 extentBLOCK_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 aBLOCK_INCONCLUSIVEcategory 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 itBLOCK_PREV_NOT_TIPor 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
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.
That's also a potential solution, I agree. I categorize these approaches:
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".The latter two introduce inconsistencies in the code (a bit "hacky"), therefore I chose 1.
A more specific
BLOCK_PREV_NOT_TIPsounds good to me.Changes applied:
BLOCK_PREV_NOT_TIP(fromBLOCK_INCONCLUSIVE), as suggested by @mzumsandeTestBlockValidity(), as suggested by @hodlinator(
git range-diff ba0d2b49f526b789ab758bc25f909344b2b092c1...be5ff46547675d6cd329aad7778a32f4192fe605)re-ACK
be5ff46547Switched to more precise enum name and added unit test.
I've came up with another solution alternative:
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.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.
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
TestBlockValidationResultenum just for one value seems overkill.If I understand correctly:
BLOCK_PREV_NOT_TIPmeans: it's not the tip, I didn't check the indexBLOCK_MISSING_PREVmeans: 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.ACK
be5ff46547In
8d9aed91advalidation: In TestBlockValidity, use PREV_NOT_TIP nit: you could introduce this test before the change, so it's clear onlystate.GetResult()changes.That commit could cover the other enum results too, which don't change in this PR. Something like:
For completeness: this has been applied earlier.
Thanks @hodlinator and @Sjors for sharing feedback on the proposed alternative, I also reached a similar conclusion, and discarded the alternative.
I've applied @Sjors's suggestions for the test:
TestBlockValidity()returns in the stale block case has been moved earlier.git range-diff be5ff46..be10d3dApplied, slightly extended, with check for validity as well.
Thanks for the ready-prepared snippet!
re-ACK
be10d3d5cfNice to see increased unit test coverage of other enum values.
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):
ACK
be10d3d5cfCode Review ACK
be10d3d5cfRetested the latest head (
be10d3d5cf)One thing: the new
Assumeonly aborts in Debug builds, so my RelWithDebInfo run doesn't verify that assertionDebug, fuzz, test_kernel and functional tests are still pending
Thanks for the (re)reviews! RFM? Or need to call in more reviewers?
ACK
be10d3d5cfRequiring a set result and a non-empty reject reason gives invalid validation states a consistent contract, and
BLOCK_PREV_NOT_TIPmakes it clear whyTestBlockValidityrejects a stale template.I'm fine with merging as is, but what do you think about adding
FakeNodeClockto theBLOCK_TIME_FUTUREtest? If the wall clock crosses a second boundary between settingblock.nTimeand 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_INCONCLUSIVEtoBLOCK_PREV_NOT_TIP.I'd also take hodlinator's
std::string_viewsuggestion.I'd be happy to re-review if you do.
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 freezeNodeClockfor these checks?Example patch
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_UNSETon that row, so the fix only needs to update the expected result.Example patch after freezing the clock
Concept ACK
I think the various items that @l0rinc flagged should be fixed before this is merged.
Changed
miner_tests.cpptest, appied simplification suggestions from @l0rinc.git range-diff be10d3d...be64ccThanks, they can be done as the other tests. Changed, it's more consistent and compact this way.
Taken
Additionally applied @hodlinator's
string_viewnanonit as well.git range-diff be10d3d...ba6f5df🚧 At least one of the CI tasks failed.
Task
iwyu: https://github.com/bitcoin/bitcoin/actions/runs/47351991714/job/145106542860LLM reason (✨ experimental): iwyu_fail: IWYU reports incorrect includes in minisketch.h and removes an unnecessary include from tx_check.cpp, leaving a diff that causes the check to fail.
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.
Intermittent network issues can occur; re-run CI for now, and report the issue if they keep happening.
A functional or integration test failure may be intermittent or unrelated to this pull request.
If no dedicated issue thread exists, create a new one to track it.
Leave a comment here, if you need help tracking down a confusing failure.