mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:47:36 +00:00
refactor: Change some validation.cpp methods to return BlockValidationState #35570
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!35570
Loading…
Reference in a new issue
No description provided.
Delete branch "2605-validation-state-return"
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?
Summary. Refactor validation result to be a return value instead of an output parameter in several
validation.cppmethods.Motivation. The benefits of the change are:
stateare inconsistentThis has grown out from #33856, mentioned in comment here and here.
Details. Many methods follow the scheme where the validation state is returned in an output parameter (
BlockValidationState& state), and and additionalboolreturn value indicating success. In success case the convention is thatstate.IsValid()and the return value are both true. After the change there is only aBlockValidationStatereturn value, which is either success (state.IsValid() == true), or an invalid/error case.This change is a highly localized refactor, but touching a sensitive file.
Relevant methods called by
ProcessNewBlockHeadersandAcceptBlock(directly and indirectly) are touched.Changes are separated into commits by touched methods, ordered by bottom-to-top in the call hierarchy.
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:
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.
LLM Linter (✨ experimental)
Possible places where named args for integral literals may be used (e.g.
func(x, /*named_arg=*/0)in C++, andfunc(x, named_arg=0)in Python):src/bench/duplicate_inputs.cpp:CheckBlock(block, chainparams.GetConsensus(), false, false)src/test/baseindex_tests.cpp:AcceptBlock(new_block, &new_block_index, true, nullptr, nullptr, true)src/validation.cpp:AcceptBlock(pblock, nullptr, true, dbp, nullptr, true)src/validation.cpp:AcceptBlock(pblockrecursive, nullptr, true, &it->second, nullptr, true)2026-11-24 22:47:15
🚧 At least one of the CI tasks failed.
Task
tidy: https://github.com/bitcoin/bitcoin/actions/runs/27862735029/job/82461396003LLM reason (✨ experimental): CI failed because clang-tidy reported
readability-const-return-typeerrors insrc/validation.cpp(e.g.,static const BlockValidationState ...return types), causing the clang-tidy step to exit with failure.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.
While working on this PR, one instance was identified where the invariant
return_value == state.IsValid()was not guaranteed:At the end of
ChainstateManager::AcceptBlock(),FlushStateToDisk()was called, and its return value discarded, but it could have a side effect instate. In turn, this could make a difference inChainstateManager::LoadExternalBlockFile().Options to resolve this:
A. Since the return value is ignored, ignore the
statereturned as well.B. Handle the error from
FlushStateToDisk(), and pass the error.The ignoring of flush result (A.) is also proposed in #29700 (cc: @ryanofsky ).
The minor behavior-change could be also omitted from this PR, limiting strictly to a no-behavior-change refactor:
AcceptBlock, keep the dual value & state return valuesConcept ACK
Concept ACK. Preferring the return value over output parameters is a useful and I would say necessary improment.
But could we avoid using
BlockValidationStateas a state machine, or mutable local variable? That means, instead of code like:I would prefer something like:
I fully agree, shorter-scoped variables mean less chance of potential interplay between calls, less complexity. I did change this in several places, but not everywhere. In some places there was a real chance for interaction between subsequent calls (e.g. error reason is set conditional of already set value), and I kept it to be safe (w.r.t. behavior changes). But I should review and change it more aggressively.
Applied some improvements:
BlockValidationState statevariables, use only restricted scope state variables, optimally in"if (const auto state = Xxx; !state.IsValid())"construct. Thanks @purpleKarrot for the emphasis!InvalidStatestatic helper to create invalidBlockValidationStateinstance. In error branches, instead of 3 statements (declaration, setting, and return) now one is enough (return&construction). Added as new first commit.concept ACK 8207ac1bb79f76c9005e8e2d695b725539b3c5c0
Looks good overall. I'd push this one step further and use
util::Expectedhere, it's a natural fit and follows the PR's own motivation. The PR already cleans up thebool+stateout-param inconsistency by making state the return value;util::Expected<T, BlockValidationState>does the same thing but at the type level instead of by convention. Success and failure become distinct alternatives of the type.Concretely, a bare
BlockValidationStatestill carries all three modes (M_VALID/M_INVALID/M_ERROR) in the return value even thoughM_VALIDis now redundant with "the call succeeded". Withutil::Expectedthat mode collapses intohas_value()and is no longer stored, the failure modes move to the error channel, and out-params likeppindexfold into the success channel.util/result.halso explicitly steers low-level functions towardutil::Expected.One open question (happy to leave it as discussion): where does
M_INVALIDfit best? Above I put it in the error channel next toM_ERROR, but it's arguably a successful, expected outcome of validation, the function did run and produced a verdict ("this block is invalid"), whereasM_ERRORis a genuine runtime failure that prevented producing a result. So an alternative split would keep Valid/Invalid in the value channel and reserve the error channel for runtime errors only. I don't have a strong preference.Concept ACK
There is a thread in #33856 where this was also brought up. I included a POC in the last comment of that thread which keeps the value channel for
M_VALID/M_INVALIDand the error channel forM_ERROR, which I think makes more sense as you're suggesting:M_INVALIDis not an operation failure.In general, I think stripping the runtime failure from
BlockValidationStatecould also leave the door open for preferring exceptions over error values in the future. That said, this should be orthogonal to this PR and could be addressed in a follow-up if desired.I think both approaches are ok, though I slightly prefer
util::Expected<CBlockIndex*, BlockValidationError>, an invalid block is an error in the same way a hardware failure causes validation to fail. That said, I understand the distinction behindutil::Expected<BlockValidationState, std::string>, where the value represents logical state (valid or not) and the error is something unrelated to the function's logic. I'd accept either.I completely disagree that this is orthogonal to the PR. This is a fundamentally different refactor, it differs not just internals but the API and its callers in a critical section of the code. I don't think it's correct to keep returning state through an value of the
BlockValidationStatewhen we already haveutil::Expectedin the codebase for exactly this purpose.On top of that, I don't think it's a good idea to keep touching this section of the code without a clear long-term direction changes that are purely stylistic or for maintainability, only to refactor everything again later when
util::Expectedgets introduced. This PR is already proposing a structural change to error handling here, it should go all the way rather than leave a half-finished migration that will need to be revisited.The way I see it, the main thing we achieve with the current refactor is the ability to reason about things more locally, by not having to pass state around and absorb it across a chain of operations. This seems like a separate objective from making
BlockValidationStateno longer absorb runtime errors or changing it toBlockValidationError. Even if reviewers would prefer seeing both goals addressed in a single batch/PR, I think it would be valuable to have a kind of separation between them through distinct commits.Agree, this is a relevant topic alone to be merged, and my concerns should not be a blocker, however i feel that would be the correct way to implement this and fits inside the PR. I will continue the discussion when more changes or reviews are submitted to not flood the thread
@arejula27: very valuable suggestion using
util::Expected, I will explore this idea. The current PR doesn't change the content of theBlockValidationStatereturned, only how it is returned, there is no behavior change (except the special case 9965489e243143fdbba6e8f379e598c92368d45c), the changes in the commits are relatively localized scope. Nonetheless, I will explore theutil::Expectedsuggestion, and apply it, or not (in that case I will mention it as an alternative considered).Another idea related to this: some methods return only Valid or Invalid, but not Error -- I've documented this in the header comments in a few places for more visibility. This is by convention, and not enforced. Maybe this could be enforced (maybe by the return value used).
re: https://github.com/bitcoin/bitcoin/pull/35570#issuecomment-4758227624
Really nice catch. I think it would make sense to open a separate PR to fix this, so this PR can just be a refactoring and not change behavior. One approach could be: 78100ea27d076e9c76f444364dfd8fbaf719fefc
Thanks, I'll do this. Thanks for the prepared commit as well.
Update:
Concept ACK
Following up on the discussion above about
util::Expectedbeing the long term refactor, I've opened an RFC #35646 which might be the direction where this could end.re-concept-ACK 014f2774b9
Second pass focused on correctness and the new signatures, nothing significant to flag
nit: could be const (only IsValid() is called), like the fuzz/block.cpp temporaries this PR already made const.
nit: could be const (only const methods are called on it).
nit: state is dead after this line, so create(std::move(state)) avoids copy-constructing the state.
nit: could be const auto res{...}
Missing nodiscard, unlike the other converted functions (CheckBlockHeader, CheckMerkleRoot, ContextualCheckBlockHeader)
Same here: missing nodiscard for consistency with the other converted functions
I miss a comment here about the case.
I would like to know the reason to drop the previous
(if (!state.IsValid()) NONFATAL_UNREACHABLE(); return state;), so a hypotheticalConnectBlockthat returns true while setting an invalid state would now be reported as Valid.Intentional as part of the simplification? Is this case not possible anymore?
Applied some (minor) changes following review from @arejula27 -- thanks!
Done
Done
Done
Done
I haven't deemed
nodiscardimportant on all compile-unit-internal methods, but I've added now for consistency.Added (as above)
Indeed. Such checks ensured that the bool and state return values are in-sync, and they became pointless in most places. However, here
ConnectBlockstill return both bool and state, so the check makes sense. I've put it back in theelsebranch.Rebased, following the inclusion of #35621 (first commit dropped, as already in master).
Concept ACK
🐙 This pull request conflicts with the target branch and needs rebase.
Rebased, post #34897 (straightforward resolution).
🐙 This pull request conflicts with the target branch and needs rebase.
Rebased to current master. Only tests affected: some removed tests, some straightforward resolutions.
git range-diff e600c4ce022bf1e856cb81ca941310fe177d7eb6...f65361acfae8d5d0d9f525fe7887334f03cedcc3Ack f65361acfae8d5d0d9f525fe7887334f03cedcc3
This PR only changes signatures as the PR description says, no behavioral changes.
Wrote some small comments, none of them are blockers, just suggestions, but I would highly encourage at least fixing the comment/doc error I mentioned in my last review (
validation.h:1280, "On failure,IsInvalid()is false" should read "true").As I mentioned in the inline comments, I think adding both factories would help readers understand the code and make it cleaner.
Also wrote two small tests (arejula27/bitcoin@67a3be1) that guard how each case is reported (valid/invalid/error). Feel free to cherry-pick, copy, edit or omit.
nit: could you put this brace a line below, to keep a consistent format with the file (see class
ValidationStateright above)?I only found one other manual
Error(...)construction, but might still be cleaner to have a factory here too, e.g.BlockValidationState::ErrorState(reject_reason). Then this becomes:I see the default constructor gets a valid state from
however it would be better for the reader if you also added a factory for the valid state (alongside InvalidState(...)), so the returned state is explicit rather than implicit and independent of the default value of
ModeStatenit: I would prefer
header_state, not a fan of using verbs in variable namesThanks for the reviews, @arejula27!
Changes applied -- all minor:
ProcessNewBlockHeaders.ProcessNewBlockHeaders: add assert to check that the non-valid case is invalid (and not error).AcceptBlockHeader: add asserts to check that non-valid cases are all invalid (and not error).AcceptBlocksrc/consensus/validation.h)ErrorStatefactory method to theBlockValidationStateerror class. Added as a separate commit.git range-diff f65361acfae8d5d0d9f525fe7887334f03cedcc3..58d6d23275067dc284ca13f3d7906ac9aaf7843aDone.
Suggestion taken, factory method for Error added. I've also found a second construction instance (in
AcceptBlock), both use the factory method now. Added you as co-author.I think it's intuitive for the state class to initialize to Valid by default. Adding a factory method for the Valid would be an overkill in my view. It's true that
BlockValidationStateandValidationStatedon't have an explicit constructor, but it's rather clear that the default constructor initializes toM_VALID. I have added a note toValidationStateto clarify, but not changing anything else.Taken.
Good catch. On failure
IsValid()is false, moreoverIsInvalid()is true. I state: "On failure, IsValid() is false and the state contains the specific validation failure reason. Never returns Error state.". From the last bit it follows thatIsInvalid()is true, but I don't mention it here, onlyIsValid(), as that should be used to check for normal vs. exceptional case.agree
re-ack
58d6d23275Thanks, but I think you need the form "reACK" exactly, to be picked up by the review bot. Could you edit it (or re-comment)?
Sorry, first time doing it😅
I am trying to understand this.
Calling
validation_state_pow_and_merkle.Error("")changes the state to Error, making the laterif (validation_state_pow_and_merkle.IsValid())always false so it never runs.Separately, the
IsValid() || IsInvalid() || IsError()assertions appear redundant, even before the refactor: a default-constructed state wasValid, so these assertions would pass even ifCheckBlock()never updated it.Applied fix to a minor fuzz test bug, found in review (thanks @w0xlt).
git range-diff 58d6d23275067dc284ca13f3d7906ac9aaf7843a...981912489d89d40a2f54b58b9e035906e5cb4737Pre-change,
CheckBlockreturned a bool and status in the parameter. The fuzz test saved the bools, and used them for checks at the end. Since there is no bool return any more, those became unavailable, andstatus.IsValid()is used instead.You are right, that the setting of
validation_state_pow_and_merkleto error interferes with this! I'm not sure of the intention of that line, but it seems it didn't do anything meaningful, as that variable was not accessed afterwards. It may contribute to test coverage though. So my resulotion is to move the.Error()call to the end.Applying now, as this is a (minor) bug to the fuzz test. Thanks for the find!
Reviewed
981912489dI get the impression the alternative #35646 returns narrower types, which makes the code more correct by construction rather than adding
assert(state.IsInvalid). Only just discovered that PR though, so will try to review it next, before coming back to this one.nanonit: Could reduce camelCase in touched lines as developer-notes.md enforces snake_case.
nanonit: Even stronger assertion:
nits: So much "state" in
BlockValidationState::InvalidState(...how about:or alternatively make it a free function outside of
BlockValidationStateas we don't need access to private parts:(+ make it
nodiscard).nit: Could use default ctor initialization to avoid any risk of having to seek through the string literals for NUL term.
nit: Could add precondition:
nit: Would prefer this were introduced together with
InvalidState()and then used in the later refactoring commits forFatalError()andAcceptBlock().We want to make sure that we are not overriding an invalid/error state with a valid state with this refactor. Could add this before overwriting the incoming state parameter:
The CI tests and reviewers running the ancestor commits can then help verify that the behavior doesn't change.
Most of them could then hopefully be removed in later commits where we further reduce the scopes of
state-variables.Same in
AcceptBlockHeader()in this commit, and same pattern in later commits.remark in
86104e9d74"Refactor AcceptBlockHeader signature":I understand that these asserts can be added since no paths currently return error. Hope these wires won't be tripped outside of tests in the future. Not sure whether these types of documentation asserts should be used in such critical code when the conditions they catch don't obviously cause problems later on during execution (in contrast to checking a pointer for non-nullness before de-referencing).
It would feel safer if we made the paths which do not return error states instead return a narrower state type which only allowed valid/invalid, instead of having these more imperative checks.
Maybe their additions could be broken out into a commit at the end, or be deferred to a later PR, keeping this more strictly a refactoring PR. Similar changes are done in
4ed1273687"Change ProcessNewBlockHeaders", which in its title admits it's not a pure refactoring commit.Thanks for the review!
#35646 and this PR overlap, but not completely, both have their own merits. PR 35646 was raised later, and I like it, I ack'ed it. I haven't closed this PR, as it has some improvements not present there. In case 35646 is merged first, I will update this PR. Please have a look at #35646 too.
Clarification (Sept 17): I concept-acked #35646, not proper-ack, but I made a mistake, and it showed up as proper-ack (https://github.com/bitcoin/bitcoin/pull/35646#issuecomment-5712874848).
Made some (minor) changes, following latest review (@hodlinator).
git range-diff 981912489d89d40a2f54b58b9e035906e5cb4737...312c4e78faa5dc775bb33351ea4dda8a9e18b50aTaken.
Technically the check only checked for
falsereturn value, that corresponds to!IsValid(). This is a tightening of the checks, but the duplicate inputs case should result in invalid (not error), so it is safe to change. Accepted.Accepted.
Taken.
Accepted.
It is done (in later commit?).
This point becomes irrelevant in a later commit, when
CheckBlockitself doesn't get an inputstate, and the state returned fromCheckBlockHeadercall is placed in a new local variable, so no overwriting can happen.I understand the doubts about using potentially catastrophic
assert's.However, if an invariant can be verified by static code analysis of a small amount of code, assert are useful for not only documenting, but enforcing invariants.
I agree that narrower return values are superior solution in this case, but I did not see an easy way to ensure that.
The concern about code being changed later is always a valid worry, I agree.
I would prefer these methods to have a single return at the end, and assert just before the single return. However, with early-exit returns style that's not practical.
In this PR, the following 4 methods can return Valid or Invalid, but never Error:
CheckBlockHeader: Internal method, and trivial to verify the code: it has 3 lines with 2 returns, and none of them is Error.ContextualCheckBlockHeader: Internal method, more complicated, around 8 returns, one{}and the rest allMakeInvalidAcceptBlockHeader: This is apublicprivate method, and its return are Invalid or Valid, except 2 cases, where it calls into the above two methods. If those return non-valid, that must be invalid, and this is asserted and returned. This way it can be verified by looking only at this method that it cannot return Error.ProcessNewBlockHeaders: Public method. Returns valid, or non-valid fromAcceptBlockHeader, which, by the above, must be Invalid. This is asserted, so that the invariant can be verified by looking only at this method.It is only this last method which is called from outside, from
net_processing.cpp, and there is isAssume'd that it doesn't return Error.Moving these asserts to a separate commit is tempting, but in fact it's only cosmetics.
I've also considered using less dangerous
Assume. Or leaving them out altogether.Based on the above explanation I keep as it is for now. Those asserts are needed to ensure the invariant added to the documentation ("Never returns Error state").
🚧 At least one of the CI tasks failed.
Task
iwyu: https://github.com/bitcoin/bitcoin/actions/runs/35105544002/job/104825688520LLM reason (✨ experimental): CI failed because IWYU reported include fixes were needed and intentionally exited non-zero (“Failure generated from IWYU”).
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.
Fixed IWYU CI failure (missing include for new
Assume).Additionally added comments to
CheckBlockHeaderandContextualCheckBlockHeader(that they cannot return Error), and also fixed an outdated comment insrc/net_processing.cpp(AcceptBlockHeader/ProcessNewBlockHeaders).Reviewed
a92cd68a34The way this PR transforms pre-existing functions one at a time is something I wish #35646 did as well.
Agree that it complements #35646, but think it should go in after that one (see inline comment), so I'll defer my Concept A-C-K until something like that lands. Please don't see my reservations as disinterest, I spend time on it because I agree the general direction is worthwhile.
Branch incorporating my suggestions into existing commits: https://github.com/hodlinator/bitcoin/tree/pr/35570_suggestions
thread https://github.com/bitcoin/bitcoin/pull/35570#discussion_r4014245663:
Please also fix
MakeError(const std::string& reject_reason = "").thread https://github.com/bitcoin/bitcoin/pull/35570#discussion_r4015407700:
What I meant is to add both
MakeInvalid()andMakeError()helpers in the first commit. Then in the "Refactor FatalError signature" and "Refactor AcceptBlock signature" commits you can switch directly toMakeError()instead of the intermediate hop throughstate.Error() ... return statewhich those commits currently do.This can be dropped in the "Refactor CheckBlock signature" commit so we only assign state once.
thread https://github.com/bitcoin/bitcoin/pull/35570#discussion_r4014342260:
I know many checks away in later commits but still think it's good practice to add them in intermediate commits when you are changing behavior of such critical code.
At the very least the "test ancestor commits" CI job can churn through them.
You are changing the local code behavior from maybe changing
statewhen passed as an argument, to definitely stomping it with a return value.I went through and added
Assumes in my suggestions branch and many of them survive until the end, although I admit some are overly paranoid.thread https://github.com/bitcoin/bitcoin/pull/35570#discussion_r4014835740:
Following the call tree on the current PR base is good to do, but not the best we can do. Adding asserts and now comments about current behavior feels like duct tape to me.
As the PRs currently stand, I much prefer #35646 be merged before this PR so invariants are enforced at compile time through types rather than by the duct tape that is runtime failures and comments. That makes it much harder for silent merge conflicts and the like to cause issues.
This
stateshould be removed if we keep this commit where we callCheckBlock()etc which return it's own instances instead of overwritingstate. That means we also refactor the nextif-block:That also necessitates re-introducing
statebefore callingConnectBlock(), unless that method is also refactored to returnBlockValidationState:Realized
BlockValidationState::MakeInvalid({}, ...triggers theAssume(result != BlockValidationResult::BLOCK_RESULT_UNSET), so might be best to skip adding the latter for now.New round of changes following new review comments.
Sorry, the fell through the cracks; done.
Taken. Through reordering, the double touching of
FatalErrorandAcceptBlockcan be avoided.Indeed,
MakeInvalidcan be used, and then there is no need for thestatevariable, only further down. Done.You are right, in the previous form with input-output parameters method had the chance to overwrite the
status, but did so only in error case. I've added the proposedAssume's in every place where we overwrite thestatusalways. Some of theseAssume's disappear in later commits, but not all.One question, how do you decide when to use assume and when assert?
Rebased ot master, hoping to fix the
mining_template_verification.pyfailure in CI (could not reproduce locally).Test failure is due to this
ifinTestBlockValidity:which creates an Invalid state with
result == BlockValidationResult::BLOCK_RESULT_UNSET, which violates a newly addedAssume.@hodlinator: This is a rather bold Assume.
It could be made even bolder, if placed inside
ValidationState::Invalid()! :DThe CI failure caught one violation of this: #31981 introduced a usage where BlockValidationState is used, but the result is discarded, and Unset is used. My fix is to leave out
MakeInvalid()in that case, leave the directValidationState::Invalid()call there. (Note: I'm not sure why this failure occurs in only some CI runs, but that's not too important.)Small change to fix CI failure.
CI caught a violation of the newly introduced
Assume: #31981 introduced a usage of BlockValidationState where the result is discarded, and Unset result is used.git range-diff 6294fb57f8f8db077d22ec294633e7e78762d5b1...0e8dc6b9dd7f07e756dcfe0b8146cc2daa17008eConcept ACK https://github.com/bitcoin/bitcoin/pull/35570/changes/5e2d798b28d55fe3786ea23efc33f5fbf4f4fba0
Thanks for working on this, Initial looks at the
validation.cppmethods use of theBlockValidationStatewas a bit ambiguous to understand, this makes things much clearer since the validation states can be used to replace the boolean values being returned.I have a question, I can see in
validation.cppthat there are some methods that have been skipped such asConnectBlockandConnectTipthese seem to be good prospective targets for this specific refactor?Yeah, see my older comment https://github.com/bitcoin/bitcoin/pull/35570#discussion_r4037905445, I thought this
Assumewas obviously correct but for some reason we have a call-site which didn't want to specify its own enum value.I overlooked that you also found this usage.
This is a rather localized usage. Before #31981, the
inconclusive-not-best-prevblkcheck was outsideTestBlockValidity, and only the string was used. It was moved intoTestBlockValidity, so now it is returned in thereject_reasonof thestate, but since onlyreject_reasonis used, thereasonis left empty. It could use a newBLOCK_INCONCLUSIVEvalue. I may tackle this separately.Yes, the idea can be applied on those equally, I have left them out (or for later?) to limit the scope. Note that #35646 (somewhat related) also tackles those.
@arejula27 , there are no clear-cut rules.
assertstops the program immediately, so it should be used only in cases which should never happen. My guideline: use if its truthfulness can be established by static code analysis of the near-scope code, and excludes further potential error cases. E.g. if previous code makes it impossible that a pointer is null, and the pointer is dereferenced later, it makes sense to assert that it cannot be null.Assertis similar toassert, but it produces logs.Assumeis the least dangerous, it produces logs, but it creates as exception only, not abort.Sounds worth exploring!
(Documenting as self-comment). I've realized that the factory method could be added to the template base class
ValidationStateinstead of the specialized/derived class.BlockValidationStatewould be simpler, the factory would be available forTxValidationStateas well, at the price thatBlockValidationStatewould need a constructor fromValidationState<BlockValidationResult>. However, as the factory would not be useful for TX validation as of now, this wouldn't make much sense.--> break-out PR created: #36318
Earlier concerns neither republished nor resolved: 2 suggestions. See the Run archive linked from the Review report for their assessments.
🟠 Minor ·
ActivateBestChainStepdiscards the specific flush failureA local flush failure during a reorg disconnect now returns
Failed to disconnect block.instead of its specific cause, including in RPC errors, while fatal notifications and shutdown behavior remain unchanged.Location:
src/validation.cpp:3303(head).🔵 Suggestion · Corrupt-block
Errorstates discard the original diagnosisCorrupt stored blocks now reach
BlockCheckedwithBLOCK_RESULT_UNSETrather thanBLOCK_MUTATED; shutdown is unchanged, and practical impact is unconfirmed because no external consumer readingError-mode results was identified.Location:
src/validation.cpp:2399(head).🔵 Suggestion · Stored-block corruption lacks a mode-specific regression test
The refactored branch correctly returns
Error, but existingconnect_blockfuzzing disables its merkle check and only compares success withIsValid(), so it cannot protect the corruption disposition.Location:
src/validation.cpp:2399(head).🔵 Suggestion ·
TestBlockValiditydescribes normal rejection as unexpectedThe remaining comment labels ordinary
CheckBlockrejection as unexpected, although proposal-mode validation accepts external blocks that may fail this check.Location:
src/validation.cpp:4603(head).🔵 Suggestion ·
c9d80b7describes a C-API change its patch does not makeThe message for
c9d80b7claims a C-API return-type change, but its parent already returnsbtck_BlockValidationState*; the patch only simplifies the implementation.Location: src/kernel/bitcoinkernel.cpp:1620 (commit).
Review coverage was incomplete.
Reviewed:
beb7dc927a14· Review report · Previous reportspermalink
This PR needs to be rebased on master. It no longer compiles after #35714, which added a
state.Error()call inFlushStateToDisk, wherestatedoes not exist anymore.chainstate_write_tests.cppalso needs the new signature.On master, the logs for this case show
bad-txnmrklroot, hashMerkleRoot mismatch. Here the state is replaced, so that reason is not logged anywhere and we only see the genericCorrupt block foundmessage. A simple fix is to move the existingLogErrorabove theBLOCK_MUTATEDcheck, so the reason is logged in both cases. If you need the scenario that reproduces the behavioral change, I can share it in a gistIndeed there was a silent merge conflict, thanks for the heads-up @arejula27!
Rebase to current master is without conflict, but it results in code with compile error. #35714 added a
state.Errorline inFlushStateToDisk, and also some new calls insrc/test/chainstate_write_tests.cpp. These have to be updated.I have now rebased to current master, fixed.
(
git range-diff 9e3c5ba481d558cc80190bcd849dbbd0ecb2f60d...774c2c0c667de49f4181953fae5177db34eae5b2)Indeed, good catch!
The old code did overwrite the state, but only partly. It 'upgraded' the error from Invalid to Error, but when doing so, the reject reason was kept. Now a new state is created, that will have the supplied new reason.
This is a slight behavior change (albeit small), I'm still mulling on how to deal with it:
FatalErrorwith a previous state, and potentially preserving the reason string from there.I was looking also for similar cases (
state = ...,MakeError,FatalError). There are a handful of places to check (inConnectTip,ActivateBestChainStep,VerifyDB).Analyzing the old code, the
"Corrupt block..."message was never stored in the state!Details:
BLOCK_MUTATEDis always used with Invalid state, and one of the following reject reasons:"bad-txnmrklroot","bad-txns-duplicate","bad-witness-nonce-size","bad-witness-merkle-match","unexpected-witness".state.m_modeisM_INVALIDnotifications.fatalErroris invoked with"Corrupt block..."state.Erroris calledFixed the point raised by @arejula27.
git range-diff 774c2c0c667de49f4181953fae5177db34eae5b2...7b7392e61f35fdab5e22d7348ae05154a81e2b58I concluded that overwriting the rejection reason here is the right way to go, as a new, higher level error is created from the previous invalid result. Also, it's not recommended to mix Error status with Invalid-style reject reasons.
My fix is adding a specific log and comment about the upgrading of the error.
I've also checked for other potential places where an Invalid state can be upgraded to Error, but found none (checked changed in
validation.cpp, especially around the patternsstate = ...,MakeError,FatalError).In fact, with these changes the conditional change of reject reason in
ValidationState::Erroris not needed, it is only called with a fresh Valid state, theifcould be changed to an assert or removed. I haven't done so (just tried it).tACK
7b7392e61fCorrupted a block on disk and forced a reorg to read it, then compared the logs:
master:
this PR:
The reason is still logged, so this looks good to me. I agree with your view that a new, higher level error is forwarded. Not sure if it should be discussed deeper (long related discussion on #35646) but it is ok for me.
Self-review note: In this line a previous non-valid state may be overwritten. The
DisconnectTip()->FlushStateToDisk()call may return anErrorstate. In the caseFatalError()is called twice.A separate break-out PR was raised with this issue, isolating the (minor) behavior change: #36792
Note: Also covered in #36792
🐙 This pull request conflicts with the target branch and needs rebase.
Straightforward rebase (due to #36782), no other change.