Skip to content

RFC: Separate out runtime errors from BlockValidationState using util::Expected - #35646

Open
yuvicc wants to merge 16 commits into
bitcoin:masterfrom
yuvicc:2026-06-remove_enum_ie
Open

yuvicc wants to merge 16 commits into
bitcoin:masterfrom
yuvicc:2026-06-remove_enum_ie

Conversation

@yuvicc

@yuvicc yuvicc commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

BlockValidationState currently carries two unrelated kinds of failure: consensus/policy invalidity which is the actual purpose and runtime errors via a M_ERROR mode in ModeState enum inside ValidationState class. This PR removes M_ERROR and routes runtime errors through util::Expected<T, std::string> instead, making the two failure modes distinct.

Motivation

BlockValidationState exists to describe why a block or transaction is invalid. It holds a consensus/policy reject reason. A disk write or system runtime error is not that, yet it was folded into the same object as a third state i.e. M_ERROR.

This conflation has two costs:

  • Wrong abstraction for non-validating functions. FlushStateToDisk, DisconnectTip, ActivateBestChain, PreciousBlock, and InvalidateBlock do no block validation, but each takes a BlockValidationState out-param to report any runtime error.

  • Three outcomes in one object. Functions that can both validate and hit a runtime error (ConnectBlock, AcceptBlock, ProcessNewBlock) holds valid, invalid, and fatal into a single BlockValidationState, forcing every caller to unwrap.

As noted in the original discussion here:

Functions like FlushStateToDisk, ActivateBestChain aren't exactly about validating a certain block, yet they take a BlockValidationState& out-param just to absorb runtime errors, which feels like the wrong abstraction.

And also discussion here to remove M_ERROR value.

util::Expected is a good option for this reason, it keeps the error handling in the same return value style (system/runtime errors and ValidationState for consensus correctness) and separates-out runtime errors from ValidationState.

Runtime errors could be signaled either by a return value or by throwing. This PR keeps them as return values as it's a minimal change. M_ERROR was already a return-value mechanism included in ValidationState with consensus verdict. This PR doesn't open the exceptions vs returns question, it keeps the existing return-value style and just moves the fatal error into a proper Expected channel.

@DrahtBot

DrahtBot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

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.

Type Reviewers
ACK optout21
Concept NACK purpleKarrot
Concept ACK hodlinator, arejula27

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:

  • #36743 ([RFC] build: build with -Wmissing-declarations/prototypes by fanquake)
  • #36739 (refactor: pass BlockManager to ChainstateManager by pzafonte)
  • #36738 (refactor: move block writes and pruning into BlockManager by pzafonte)
  • #36725 (refactor: Use u64 consistently for flatfile sizes by maflcko)
  • #36621 (node: batch block file pruning in a single pass over block index by mutatrum)
  • #36555 (rpc: return error when invalidateblock fails by ja7ad)
  • #36326 (kernel: Use typed errors for fatal and flush error notifications by arejula27)
  • #36318 (validation: Ensure Invalid ValidationState has result by optout21)
  • #36188 (crypto: plug hardware optimized SHA256 into libsecp256k1's context by furszy)
  • #36074 (scripted-diff: [test] Add util/check.h includes for assertions by maflcko)
  • #36066 (validation: Separate check-only version of ConnectBlock by optout21)
  • #36000 (validation: prefetch blocks while connecting by l0rinc)
  • #35751 (validation: use parallel input prevout fetching in TestBlockValidity by andrewtoth)
  • #35731 (Indexes: Harden the flush-error notification invariant by arejula27)
  • #35570 (refactor: Change some validation.cpp methods to return BlockValidationState by optout21)
  • #34254 (validation: Prevent duplicate logging and looping in invalid block handling by mzumsande)
  • #33922 (mining: add getMemoryLoad() and track template non-mempool memory footprint by Sjors)
  • #32554 (bench: replace embedded raw block with configurable block generator by l0rinc)
  • #31260 (scripted-diff: Type-safe settings retrieval by ryanofsky)
  • #29700 (kernel, refactor: return error status on all fatal errors by ryanofsky)

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++, and func(x, named_arg=0) in Python):

  • src/test/baseindex_tests.cpp: AcceptBlock(new_block, &new_block_index, true, nullptr, nullptr, true)
  • src/test/blockfilter_index_tests.cpp: ProcessNewBlock(block, true, true, nullptr) (three occurrences)
  • src/test/util/mining.cpp: ProcessNewBlock(block, true, true, &new_block)
  • src/test/util/setup_common.cpp: ProcessNewBlock(shared_pblock, true, true, nullptr)
  • src/test/validation_block_tests.cpp: ProcessNewBlock(block, true, true, &ignored) (two occurrences)
  • src/test/validation_chainstate_tests.cpp: ProcessNewBlock(std::make_shared<CBlock>(block), true, true, nullptr)
  • src/test/validation_chainstate_tests.cpp: AcceptBlock(pblockone, &pindex, true, nullptr, &newblock, true)

2026-11-03 06:18:20

@yuvicc

yuvicc commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

Rebased on master to resolve conflicts with #35621.
Adopted its "ignore the flush error" behavior in the new util::Expected API by dropping the flush-error propagation from AcceptBlock.

@maflcko

maflcko commented Jul 7, 2026

Copy link
Copy Markdown
Member

Hmm, it could make sense to be more type-safe here, but looking at the code, there are places that flatten this back down to a boolean, so I wonder what the overall benefit is?

I think it could make sense to think whether any places that flatten this down again to a boolean need a different handling? If yes, fixing that handling should probably be done early in a pull request changing the behavior.

Moreover, I presume all of the runtime-errors are fatal, so I presume they must all call the fatal error function. Maybe this can be enforced at compile-time, so that all those fatal errors ensure that the fatal error function is called exactly once?

@optout21 optout21 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concept ACK

The advantages of this change are:

  • enforcement of returned errors -- some methods can return only runtime errors;
  • reduced risk of accidental mix-up of validation and runtime errors.

At first it looked a bit strange that some errors (runtime errors) are treated as exceptional cases, while validation errors are treated as return values, as previously both were treated the same. However, this makes sense; validation status can be regarded as the non-exceptional output of the checker algotihms, while runtime errors are proper exceptional errors.

Some minor observations:

  • Maybe the big change could be broken up (e.g. in two, first the void return value changes, then the BlockValidationState changes)
  • CheckBlock, CheckBlockHeader could be also be changed to the return-state pattern
  • [[nodiscard]] could be added touched signatures, to reduce risk of ignored errors.
  • In some places where a local state variable is used, its scope could be reduced, or omitted entirely. Preferably error from a call should be handled right away, there is no need for method-wide state/error variable (left comments in a few places).

Comment thread src/validation.cpp Outdated
@@ -2307,6 +2305,7 @@ bool Chainstate::ConnectBlock(const CBlock& block, BlockValidationState& state,
uint256 block_hash{block.GetHash()};
assert(*pindex->phashBlock == block_hash);

BlockValidationState state;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

7d0ed51 validation: route fatal errors through util::Expected:

Could get rid of this local variable if CheckBlock signature is also changed (to return state).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this could be done in a follow-up to reduce the review burden here? #35570

Comment thread src/validation.cpp Resolved
Comment thread src/validation.cpp Resolved
@yuvicc

yuvicc commented Jul 8, 2026

Copy link
Copy Markdown
Contributor Author

Hmm, it could make sense to be more type-safe here, but looking at the code, there are places that flatten this back down to a boolean, so I wonder what the overall benefit is?

You're right that the top-level callers collapses the result back to yes/no, wouldn't that be the right place for it to collapse? e.g. ConnectBlock -> ConnectTip -> ActivateBestChainStep -> ActivateBestChain, where M_ERROR used to be inside ValidationState next to consensus verdict and every caller had to unwrap to distinguish b/w consensus failure v/s fatal error.

I think it could make sense to think whether any places that flatten this down again to a boolean need a different handling?

I've checked, every fatal error already fires at the origin(FatalError()), so by the time it reaches the top-level caller, the node might be shutting down regardless of what the caller does with the string, none of the callers branch on fatal-vs-non-fatal; they just surface the message. If other reviewers also feels the same that the caller needs to programmatically tell the two apart, we could have a distinct type for fatal and non-fatal type.

Moreover, I presume all of the runtime-errors are fatal, so I presume they must all call the fatal error function. Maybe this can be enforced at compile-time, so that all those fatal errors ensure that the fatal error function is called exactly once?

This is mostly true, except for invalidateblock/reconsiderblock rpc whose error returns are non-fatal and fire nothing. I think we can get a compile-time guarantee for the functions where every error is fatal, by constructing FatalError like below?

Details
class FatalError
{
public:
    //! Fire the fatalError notification.
    [[nodiscard]] static util::Unexpected<FatalError> Raise(
        kernel::Notifications& notifications, const bilingual_str& message);

    //! Untranslated message, for logging or surfacing through an RPC error.
    const std::string& message() const LIFETIMEBOUND { return m_message; }

private:
    explicit FatalError(std::string message) : m_message{std::move(message)} {}
    std::string m_message;
};

util::Unexpected<FatalError> FatalError::Raise(Notifications& notifications, const bilingual_str& message)
{
    notifications.fatalError(message);                 // fire (→ AbortNode → shutdown)
    return util::Unexpected{FatalError{message.original}};  // then mint the value
}

@maflcko

maflcko commented Jul 8, 2026

Copy link
Copy Markdown
Member

Hmm, it could make sense to be more type-safe here, but looking at the code, there are places that flatten this back down to a boolean, so I wonder what the overall benefit is?

You're right that the top-level callers collapses the result back to yes/no, wouldn't that be the right place for it to collapse?

Yeah, I am mostly wondering aloud. Because currently, your patch will map both to RPC_INTERNAL_ERROR in GenerateBlock. However, in generateblock, they are mapped to RPC_INTERNAL_ERROR or RPC_VERIFY_ERROR. And in submitblock, they are mapped to a new imaginary/undocumented? "validation-error" string?

That doesn't seem consistent or worthwhile. I'd say:

  • Either we can distinguish the two cases clearly, in which case a separate type and handling makes sense (and they shouldn't be flattened down).
  • Or, we can not distinguish them, in which case splitting them up and then flattening them down again seems pointless?

yuvicc and others added 15 commits November 3, 2026 10:41
Read fatal errors directly from ProcessNewBlock in submission callers. Test
block-write, undo-write, and post-validation flush failures, including the
absence of BlockChecked signals for fatal validation failures.

Fatal AcceptBlock and ConnectBlock failures no longer emit BlockChecked,
since callers now receive the error from ProcessNewBlock. Clean up the
submitted block source in peer processing when ProcessNewBlock returns a
fatal error.

For block submission over the mining interface, a fatal error is reported
with reason "inconclusive" and the error message in debug, so that reason
keeps its existing set of values.

Co-authored-by: Hodlinator <[email protected]>
Co-authored-by: optout <[email protected]>
Runtime failures are now returned separately through `util::Expected`, so `ValidationState`
only needs to represent valid and invalid validation outcomes.
Remove `M_ERROR`, `Error()`, and `IsError()`.
Validation state no longer represents runtime failures, so remove INTERNAL_ERROR from the kernel C API and C++ wrapper.
@yuvicc
yuvicc force-pushed the 2026-06-remove_enum_ie branch from 7a6ced0 to ebe01e1 Compare November 3, 2026 06:17
@yuvicc

yuvicc commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto master (ddea919) and addressed review comments from @optout21.

  • Added FatalError::RaiseFlush(). After the rebase, master's 12f691c makes FlushStateToDisk() fail when FlushChainstateBlockFile() fails. That path has already fired flushError(), not fatalError(). Wrapping it with Raise() would call AbortNode() a second time, and would report a flush failure as a different notification whose shutdown behavior depends on m_shutdown_on_fatal_error.
  • Moved Raise() / RaiseFlush() into kernel/notifications_interface.cpp to drop the util/translation.h include (comment).
  • Fixed some nits comment, comment & comment.
  • ConnectBlock() now returns state instead of {} on success paths (comment).
  • Used return std::move(*res); (comment).
  • Removed the unused state = *res; in VerifyDB() and moved state into the loop (comment).
  • Updated the TestBlockValidity() doc to say a FatalError is currently never returned (comment).
  • ActivateBestChainStep() now sets the Error state before returning false (comment).
  • Kept BlockChecked firing in the ConnectTip commit and moved its removal to the ProcessNewBlock() commit, where it is documented ([comment](RFC: Separate out runtime errors from BlockValidationState using util::Expected #35646 (comment)
  • The DisconnectTip() fatal-error branch now returns instead of falling through to a second FatalError
    ([comment](RFC: Separate out runtime errors from BlockValidationState using util::Expected #35646 (comment)
  • InvalidateBlock() now sets the Error state instead of rlid state(comment).
  • Dropped the unrelated rpc/register.h include move
  • Added [[nodiscard]] to ProcessNewBlock() and updated(comment).
  • No new reason strings: fatal errors now report reason = essage in debug`

@optout21 optout21 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

crACK ebe01e1

Continued the code review. I have not identified any serious issues, left 2 non-blocking comments.
Thanks for incorporating my earlier comments!

Comment thread src/rpc/mining.cpp Outdated
Comment on lines 189 to 191
if (auto res{chainman.ProcessNewBlock(block_out, /*force_processing=*/true, /*min_pow_checked=*/true, nullptr)}; !res || !*res) {
throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cea4ccb refactor: Make ProcessNewBlock() use FatalError type:

In case of error, res.error().message() could be included in the error message.

Comment thread src/validation.cpp
state.Error(strprintf("%s: Failed to find position to write new block to disk: %s", __func__, res.error().message()));
return false;
}
assert(!res->IsNull());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

65d1929 refactor: Make BlockManager use FatalError type:

Even though currently this assert is guaranteed to not be hit, an Assume() instead of assert would be more appropriate.

@DrahtBot

DrahtBot commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

🐙 This pull request conflicts with the target branch and needs rebase.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants