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

Open
yuvicc wants to merge 16 commits from 2026-06-remove_enum_ie into master AGit
yuvicc commented 2026-07-03 04:51:49 +00:00 (Migrated from github.com)

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.

  • This would also pave a long term fix for #35570, which returns BlockValidationState from validation methods instead of boolean 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.

`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](https://github.com/bitcoin/bitcoin/pull/33856#discussion_r2765218331): > 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](https://github.com/bitcoin/bitcoin/pull/35570#issuecomment-4783419874) to remove `M_ERROR` value. - This would also pave a long term fix for #35570, which returns `BlockValidationState` from validation methods instead of boolean 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 commented 2026-07-03 04:51:58 +00:00 (Migrated from github.com)

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

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/35646 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/35646.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/35646#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | ACK | [optout21](https://github.com/bitcoin/bitcoin/pull/35646#pullrequestreview-5784724499) | | Concept NACK | [purpleKarrot](https://github.com/bitcoin/bitcoin/pull/35646#issuecomment-5801502875) | | Concept ACK | [hodlinator](https://github.com/bitcoin/bitcoin/pull/35646#pullrequestreview-5210572199), [arejula27](https://github.com/bitcoin/bitcoin/pull/35646#issuecomment-5846074774) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#36743](https://github.com/bitcoin/bitcoin/pull/36743) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36743.svg"></sub> ([RFC] build: build with -Wmissing-declarations/prototypes by fanquake) * [#36739](https://github.com/bitcoin/bitcoin/pull/36739) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36739.svg"></sub> (refactor: pass BlockManager to ChainstateManager by pzafonte) * [#36738](https://github.com/bitcoin/bitcoin/pull/36738) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36738.svg"></sub> (refactor: move block writes and pruning into BlockManager by pzafonte) * [#36725](https://github.com/bitcoin/bitcoin/pull/36725) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36725.svg"></sub> (refactor: Use u64 consistently for flatfile sizes by maflcko) * [#36621](https://github.com/bitcoin/bitcoin/pull/36621) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36621.svg"></sub> (node: batch block file pruning in a single pass over block index by mutatrum) * [#36555](https://github.com/bitcoin/bitcoin/pull/36555) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36555.svg"></sub> (rpc: return error when invalidateblock fails by ja7ad) * [#36326](https://github.com/bitcoin/bitcoin/pull/36326) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36326.svg"></sub> (kernel: Use typed errors for fatal and flush error notifications by arejula27) * [#36318](https://github.com/bitcoin/bitcoin/pull/36318) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36318.svg"></sub> (validation: Ensure Invalid ValidationState has result by optout21) * [#36188](https://github.com/bitcoin/bitcoin/pull/36188) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36188.svg"></sub> (crypto: plug hardware optimized SHA256 into libsecp256k1's context by furszy) * [#36074](https://github.com/bitcoin/bitcoin/pull/36074) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36074.svg"></sub> (scripted-diff: [test] Add util/check.h includes for assertions by maflcko) * [#36066](https://github.com/bitcoin/bitcoin/pull/36066) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36066.svg"></sub> (validation: Separate check-only version of ConnectBlock by optout21) * [#36000](https://github.com/bitcoin/bitcoin/pull/36000) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36000.svg"></sub> (validation: prefetch blocks while connecting by l0rinc) * [#35751](https://github.com/bitcoin/bitcoin/pull/35751) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35751.svg"></sub> (validation: use parallel input prevout fetching in TestBlockValidity by andrewtoth) * [#35731](https://github.com/bitcoin/bitcoin/pull/35731) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35731.svg"></sub> (Indexes: Harden the flush-error notification invariant by arejula27) * [#35570](https://github.com/bitcoin/bitcoin/pull/35570) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35570.svg"></sub> (refactor: Change some validation.cpp methods to return BlockValidationState by optout21) * [#34254](https://github.com/bitcoin/bitcoin/pull/34254) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/34254.svg"></sub> (validation: Prevent duplicate logging and looping in invalid block handling by mzumsande) * [#33922](https://github.com/bitcoin/bitcoin/pull/33922) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/33922.svg"></sub> (mining: add getMemoryLoad() and track template non-mempool memory footprint by Sjors) * [#32554](https://github.com/bitcoin/bitcoin/pull/32554) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/32554.svg"></sub> (bench: replace embedded raw block with configurable block generator by l0rinc) * [#31260](https://github.com/bitcoin/bitcoin/pull/31260) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/31260.svg"></sub> (scripted-diff: Type-safe settings retrieval by ryanofsky) * [#29700](https://github.com/bitcoin/bitcoin/pull/29700) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/29700.svg"></sub> (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. <!--5faf32d7da4f0f540f40219e4f7537a3--> ### 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)` <sup>2026-11-03 06:18:20</sup>
DrahtBot commented 2026-07-06 11:13:10 +00:00 (Migrated from github.com)

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

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
yuvicc commented 2026-07-06 16:28:16 +00:00 (Migrated from github.com)

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.

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 commented 2026-07-07 17:13:07 +00:00 (Migrated from github.com)

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?

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 (Migrated from github.com) reviewed 2026-07-08 03:46:53 +00:00
optout21 (Migrated from github.com) left a comment

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).
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).
optout21 (Migrated from github.com) commented 2026-07-08 03:36:17 +00:00

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

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

> [7d0ed51](https://github.com/bitcoin/bitcoin/pull/35646/changes/7d0ed51ec4bf7c09724aa712e93e4a3ac4cc22e8) _validation: route fatal errors through util::Expected_: Could get rid of this local variable if `CheckBlock` signature is also changed (to return state).
optout21 (Migrated from github.com) commented 2026-07-08 03:40:26 +00:00

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

The scope of this local var. could be reduced, or maybe omitted completely, if CheckBlockHeader signature is also changed.

> [7d0ed51](https://github.com/bitcoin/bitcoin/pull/35646/changes/7d0ed51ec4bf7c09724aa712e93e4a3ac4cc22e8) _validation: route fatal errors through util::Expected_: The scope of this local var. could be reduced, or maybe omitted completely, if `CheckBlockHeader` signature is also changed.
optout21 (Migrated from github.com) commented 2026-07-08 03:41:25 +00:00

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

The scope of this local variable could be reduced.

> [7d0ed51](https://github.com/bitcoin/bitcoin/pull/35646/changes/7d0ed51ec4bf7c09724aa712e93e4a3ac4cc22e8) _validation: route fatal errors through util::Expected_: The scope of this local variable could be reduced.
yuvicc commented 2026-07-08 06:00:16 +00:00 (Migrated from github.com)

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?

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
}
> 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 } ``` </details>
yuvicc (Migrated from github.com) reviewed 2026-07-08 06:55:56 +00:00
yuvicc (Migrated from github.com) commented 2026-07-08 06:55:56 +00:00

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

I think this could be done in a follow-up to reduce the review burden here? #35570
yuvicc (Migrated from github.com) reviewed 2026-07-08 06:56:28 +00:00
yuvicc (Migrated from github.com) commented 2026-07-08 06:56:28 +00:00
same as above https://github.com/bitcoin/bitcoin/pull/35646#discussion_r3541844030
yuvicc (Migrated from github.com) reviewed 2026-07-08 06:56:39 +00:00
yuvicc (Migrated from github.com) commented 2026-07-08 06:56:39 +00:00
same as above https://github.com/bitcoin/bitcoin/pull/35646#discussion_r3541844030
maflcko commented 2026-07-08 07:36:33 +00:00 (Migrated from github.com)

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?
> > 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?
DrahtBot commented 2026-07-09 02:40:11 +00:00 (Migrated from github.com)

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

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
yuvicc commented 2026-07-16 05:13:36 +00:00 (Migrated from github.com)

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?

Thanks, I agree. I went with the first option. Fatal/system failures are now represented separately as kernel::FatalError and propagated via util::Expected, while BlockValidationState now only represents valid vs. invalid consensus validation.

Also, the existing RPC behavior is preserved.

> 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? Thanks, I agree. I went with the first option. Fatal/system failures are now represented separately as `kernel::FatalError` and propagated via `util::Expected`, while `BlockValidationState` now only represents valid vs. invalid consensus validation. Also, the existing RPC behavior is preserved.
DrahtBot commented 2026-07-23 00:52:22 +00:00 (Migrated from github.com)

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

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
yuvicc commented 2026-07-27 06:38:51 +00:00 (Migrated from github.com)

Rebased to master.

Rebased to master.
DrahtBot commented 2026-08-14 15:41:39 +00:00 (Migrated from github.com)

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

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
yuvicc commented 2026-08-27 07:15:52 +00:00 (Migrated from github.com)

Rebased on master

Rebased on master
yuvicc commented 2026-09-08 08:13:52 +00:00 (Migrated from github.com)

Ready for review.

Ready for review.
optout21 (Migrated from github.com) reviewed 2026-09-08 15:29:05 +00:00
optout21 (Migrated from github.com) left a comment

ConceptACK 4b183f4e07

Reviewed again, generally looks good.
I've left some comments; most are rather minor, but there are some that should be checked. Therefore not upgrading my Concept A to a proper acknowledgement as of now.
This PR is related to #35570 (of mine), and my assessment is that both PR's stand on their own, but, despite an overlap, they also complement each other.

I uphold my comment from last review:

  • I would be happy to see the second large commit broken up (possible ways: first the void return value changes, then the BlockValidationState changes; first internal validation method changes, then external ones; etc.)
ConceptACK 4b183f4e077eb1e7d48cf5d53036c8591abf9478 Reviewed again, generally looks good. I've left some comments; most are rather minor, but there are some that should be checked. Therefore not upgrading my Concept A to a proper acknowledgement as of now. This PR is related to #35570 (of mine), and my assessment is that both PR's stand on their own, but, despite an overlap, they also complement each other. I uphold my comment from last review: - I would be happy to see the second large commit broken up (possible ways: first the void return value changes, then the BlockValidationState changes; first internal validation method changes, then external ones; etc.)
optout21 (Migrated from github.com) commented 2026-09-08 15:22:52 +00:00

a75d25d kernel: remove INTERNAL_ERROR validation mode:

Isn't this an API change technically? If so, consider a release note for it.

> [a75d25d](https://github.com/bitcoin/bitcoin/pull/35646/changes/a75d25d9bc8e7387d684572ccee74f90f44f0bc5) _kernel: remove INTERNAL_ERROR validation mode_: Isn't this an API change technically? If so, consider a release note for it.
optout21 (Migrated from github.com) commented 2026-09-08 15:20:23 +00:00

9f3ae31 validation: return fatal errors with util::Expected:

Nit: typo: occured -> occurred

> [9f3ae31](https://github.com/bitcoin/bitcoin/pull/35646/changes/9f3ae31ec44e359cea1a3a3ac44c14aa28cb0eed) _validation: return fatal errors with `util::Expected`_: Nit: typo: occured -> occurred
Lines 419-421
optout21 (Migrated from github.com) commented 2026-09-08 14:53:52 +00:00

9f3ae31 validation: return fatal errors with util::Expected:

It's not clear to me that this does not introduce new error reasons. I have the impression that the Error case previously resulted in "inconclusive" (but I'm not sure). If that's the case, this needs to be changed.

> [9f3ae31](https://github.com/bitcoin/bitcoin/pull/35646/changes/9f3ae31ec44e359cea1a3a3ac44c14aa28cb0eed) _validation: return fatal errors with `util::Expected`_: It's not clear to me that this does not introduce new error reasons. I have the impression that the Error case previously resulted in "inconclusive" (but I'm not sure). If that's the case, this needs to be changed.
Lines 1734-1736
optout21 (Migrated from github.com) commented 2026-09-08 14:55:44 +00:00

9f3ae31 validation: return fatal errors with util::Expected:

Note: pre-change error from ActivateBestChain was ignored.

> [9f3ae31](https://github.com/bitcoin/bitcoin/pull/35646/changes/9f3ae31ec44e359cea1a3a3ac44c14aa28cb0eed) _validation: return fatal errors with `util::Expected`_: Note: pre-change error from `ActivateBestChain` was ignored.
Lines 624-625
optout21 (Migrated from github.com) commented 2026-09-08 14:58:33 +00:00

9f3ae31 validation: return fatal errors with util::Expected:

Technically, in this commit BlockValidationState can still be Error, so this error check should be kept, removed in the later commit.

> [9f3ae31](https://github.com/bitcoin/bitcoin/pull/35646/changes/9f3ae31ec44e359cea1a3a3ac44c14aa28cb0eed) _validation: return fatal errors with `util::Expected`_: Technically, in this commit `BlockValidationState` can still be `Error`, so this error check should be kept, removed in the later commit.
optout21 (Migrated from github.com) commented 2026-09-08 15:06:27 +00:00

9f3ae31 validation: return fatal errors with util::Expected:

It's not clear to me that the checks for the returned state can be omitted.

> [9f3ae31](https://github.com/bitcoin/bitcoin/pull/35646/changes/9f3ae31ec44e359cea1a3a3ac44c14aa28cb0eed) _validation: return fatal errors with `util::Expected`_: It's not clear to me that the checks for the returned `state` can be omitted.
Lines 3047-3049
optout21 (Migrated from github.com) commented 2026-09-08 15:14:02 +00:00

9f3ae31 validation: return fatal errors with util::Expected:

I think there is a behavior change here in case of Error: previously BlockChecked was called, and now it isn't.

> [9f3ae31](https://github.com/bitcoin/bitcoin/pull/35646/changes/9f3ae31ec44e359cea1a3a3ac44c14aa28cb0eed) _validation: return fatal errors with `util::Expected`_: I think there is a behavior change here in case of Error: previously `BlockChecked` was called, and now it isn't.
optout21 (Migrated from github.com) commented 2026-09-08 12:16:28 +00:00

9f3ae31 validation: return fatal errors with util::Expected:

It's unclear why the 'empty' CBlock parameter was removed (it's also unclear why it was there in the first place).

> [9f3ae31](https://github.com/bitcoin/bitcoin/pull/35646/changes/9f3ae31ec44e359cea1a3a3ac44c14aa28cb0eed) _validation: return fatal errors with `util::Expected`_: It's unclear why the 'empty' CBlock parameter was removed (it's also unclear why it was there in the first place).
optout21 (Migrated from github.com) commented 2026-09-08 12:19:03 +00:00

9f3ae31 validation: return fatal errors with util::Expected:

Nit: no need to touch this, but can stay.

> [9f3ae31](https://github.com/bitcoin/bitcoin/pull/35646/changes/9f3ae31ec44e359cea1a3a3ac44c14aa28cb0eed) _validation: return fatal errors with `util::Expected`_: Nit: no need to touch this, but can stay.
optout21 (Migrated from github.com) commented 2026-09-08 12:21:30 +00:00

9f3ae31 validation: return fatal errors with util::Expected:

It seems to me, that the (blockPos.IsNull()) branch with the specific error return should be kept.

> [9f3ae31](https://github.com/bitcoin/bitcoin/pull/35646/changes/9f3ae31ec44e359cea1a3a3ac44c14aa28cb0eed) _validation: return fatal errors with `util::Expected`_: It seems to me, that the `(blockPos.IsNull())` branch with the specific error return should be kept.
Lines 4444-4447
optout21 (Migrated from github.com) commented 2026-09-08 15:16:37 +00:00

9f3ae31 validation: return fatal errors with util::Expected:

I think there is a behavior change here: in case of error from AcceptBlock previously BlockChecked was called before return, now it's not.

> [9f3ae31](https://github.com/bitcoin/bitcoin/pull/35646/changes/9f3ae31ec44e359cea1a3a3ac44c14aa28cb0eed) _validation: return fatal errors with `util::Expected`_: I think there is a behavior change here: in case of error from `AcceptBlock` previously `BlockChecked` was called before return, now it's not.
optout21 (Migrated from github.com) commented 2026-09-08 12:24:28 +00:00

9f3ae31 validation: return fatal errors with util::Expected:

Why not keeping the NONFATAL_UNREACHABLE checks?

> [9f3ae31](https://github.com/bitcoin/bitcoin/pull/35646/changes/9f3ae31ec44e359cea1a3a3ac44c14aa28cb0eed) _validation: return fatal errors with `util::Expected`_: Why not keeping the `NONFATAL_UNREACHABLE` checks?
yuvicc (Migrated from github.com) reviewed 2026-09-10 04:25:02 +00:00
yuvicc (Migrated from github.com) commented 2026-09-10 04:25:02 +00:00

bitcoinkernel hasn't released yet.

bitcoinkernel hasn't released yet.
yuvicc (Migrated from github.com) reviewed 2026-09-10 04:47:09 +00:00
yuvicc (Migrated from github.com) commented 2026-09-10 04:47:09 +00:00

Hmm, this means no block data is supplied and read from disk. So a null shared ptr not empty CBlock. Will add a comment mentioning this.

Hmm, this means no block data is supplied and read from disk. So a null shared ptr not empty CBlock. Will add a comment mentioning this.
DrahtBot commented 2026-09-17 06:57:40 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task macOS-cross to arm64: https://github.com/bitcoin/bitcoin/actions/runs/35190448674/job/105101625071
LLM reason (✨ experimental): CI failed due to a C++ build error: Chainstate().InvalidateBlock is declared to take a single CBlockIndex* argument, but wallet_tests.cpp calls it with two arguments.

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.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `macOS-cross to arm64`: https://github.com/bitcoin/bitcoin/actions/runs/35190448674/job/105101625071</sub> <sub>LLM reason (✨ experimental): CI failed due to a C++ build error: `Chainstate().InvalidateBlock` is declared to take a single `CBlockIndex*` argument, but `wallet_tests.cpp` calls it with two arguments.</sub> <details><summary>Hints</summary> 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. </details>
hodlinator (Migrated from github.com) reviewed 2026-09-17 09:37:42 +00:00
hodlinator (Migrated from github.com) left a comment

Concept ACK the earlier push 4b183f4e07

Extracting the error-part of BlockValidationState by using util::Expected is a promising direction.

As the PRs stand today, something like this should be merged before #35570 is considered.

This PR would make review easier if broken up into more commits so that the transforms are applied to one function at a time.

See my suggestions branch: https://github.com/hodlinator/bitcoin/tree/pr/35646_piecemeal

Concept ACK the earlier push 4b183f4e077eb1e7d48cf5d53036c8591abf9478 Extracting the error-part of `BlockValidationState` by using `util::Expected` is a promising direction. As the PRs stand today, something like this should be merged before #35570 is considered. This PR would make review easier if broken up into more commits so that the transforms are applied to one function at a time. See my suggestions branch: https://github.com/hodlinator/bitcoin/tree/pr/35646_piecemeal
hodlinator (Migrated from github.com) commented 2026-09-16 07:44:31 +00:00

nit: Cleaner diff if we retain the optional ending comma:

    INVALID = btck_ValidationMode_INVALID,
nit: Cleaner diff if we retain the optional ending comma: ```suggestion INVALID = btck_ValidationMode_INVALID, ```
hodlinator (Migrated from github.com) commented 2026-09-15 13:30:36 +00:00

Could put the contents of fatal_error.h inside notifications_interface.h since it's fairly tightly coupled with it?

Could put the contents of fatal_error.h inside notifications_interface.h since it's fairly tightly coupled with it?
hodlinator (Migrated from github.com) commented 2026-09-15 13:27:55 +00:00

nit: Could take as sink-argument and move-construct to avoid some copying/heap activity.

    [[nodiscard]] static util::Unexpected<FatalError> Raise(Notifications& notifications, bilingual_str message)
    {
        notifications.fatalError(message);
        return util::Unexpected{FatalError{std::move(message.original)}};
nit: Could take as sink-argument and move-construct to avoid some copying/heap activity. ```suggestion [[nodiscard]] static util::Unexpected<FatalError> Raise(Notifications& notifications, bilingual_str message) { notifications.fatalError(message); return util::Unexpected{FatalError{std::move(message.original)}}; ```
hodlinator (Migrated from github.com) commented 2026-09-17 09:19:07 +00:00

nanonit: More honest/direct name?

    FatalError ReplaceMessage(std::string message) &&
nanonit: More honest/direct name? ```suggestion FatalError ReplaceMessage(std::string message) && ```
hodlinator (Migrated from github.com) commented 2026-09-16 08:43:55 +00:00

Might as well return FlatFilePos instead of keeping it as an out-parameter:

    [[nodiscard]] util::Expected<FlatFilePos, kernel::FatalError> FindUndoPos(int nFile, unsigned int nAddSize) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
Might as well return `FlatFilePos` instead of keeping it as an out-parameter: ```suggestion [[nodiscard]] util::Expected<FlatFilePos, kernel::FatalError> FindUndoPos(int nFile, unsigned int nAddSize) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); ```
Lines 430-431
hodlinator (Migrated from github.com) commented 2026-09-17 08:39:10 +00:00

Why do this roundabout error handling rather than checking the return value of ProcessNewBlock()? Is it a way of preserving the internal error string instead of getting the replaced one?

Why do this roundabout error handling rather than checking the return value of `ProcessNewBlock()`? Is it a way of preserving the internal error string instead of getting the replaced one?
hodlinator (Migrated from github.com) commented 2026-09-16 15:15:34 +00:00

Agree, would keep it as:

    chainman.ProcessNewBlockHeaders({{h}}, /*min_pow_checked=*/true, state);
    if (state.IsValid()) return UniValue::VNULL;
Agree, would keep it as: ```suggestion chainman.ProcessNewBlockHeaders({{h}}, /*min_pow_checked=*/true, state); if (state.IsValid()) return UniValue::VNULL; ```
hodlinator (Migrated from github.com) commented 2026-09-16 08:25:38 +00:00

These renames from dummy to state seem net-negative.

These renames from `dummy` to `state` seem net-negative.
hodlinator (Migrated from github.com) commented 2026-09-16 16:13:22 +00:00

Seems like naming becomes worse here.

Seems like naming becomes worse here.
hodlinator (Migrated from github.com) commented 2026-09-16 07:47:11 +00:00

Would prefer adding the test together with the commit adding the FatalError type since the test is so tightly coupled to the existence of the type.

Would prefer adding the test together with the commit adding the `FatalError` type since the test is so tightly coupled to the existence of the type.
hodlinator (Migrated from github.com) commented 2026-09-16 16:32:56 +00:00

nanonit: While util::Expected does have a E&& error() &&-overload, I think it's less surprising to do:

        return util::Unexpected(std::move(res.error()));
nanonit: While `util::Expected` does have a `E&& error() &&`-overload, I think it's less surprising to do: ```suggestion return util::Unexpected(std::move(res.error())); ```
Lines 3047-3049
hodlinator (Migrated from github.com) commented 2026-09-16 09:33:11 +00:00

thread https://github.com/bitcoin/bitcoin/pull/35646#discussion_r3959411618:

Noticed this too.

In light of this I don't understand how you could A-C-K this? I guess you mean Concept A-C-K of this as an RFC. Seems potentially dangerous but I'm not super-familiar with the signals.

Edit 2026-09-22: My view of this changed somewhat during the review (https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4034759979, https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4028466459). Deferring to the notification system to report fatal errors seems promising.

thread https://github.com/bitcoin/bitcoin/pull/35646#discussion_r3959411618: Noticed this too. In light of this I don't understand how you could A-C-K this? I guess you mean Concept A-C-K of this as an RFC. Seems potentially dangerous but I'm not super-familiar with the signals. Edit 2026-09-22: My view of this changed somewhat during the review (https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4034759979, https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4028466459). Deferring to the notification system to report fatal errors seems promising.
hodlinator (Migrated from github.com) commented 2026-09-16 10:09:32 +00:00

nit: Slightly simpler?

        if (!res.value_or(false)) {
nit: Slightly simpler? ```suggestion if (!res.value_or(false)) { ```
Lines 4440-4447
hodlinator (Migrated from github.com) commented 2026-09-16 16:42:58 +00:00

Good catch! Missed this one. Although we have hit a fatal error, so not signalling BlockChecked might be okay. Then again some subscriber of BlockChecked might be checking state for errors... but that would show up in this PR when we remove error support from state.

Good catch! Missed this one. Although we have hit a fatal error, so not signalling `BlockChecked` might be okay. Then again some subscriber of `BlockChecked` might be checking `state` for errors... but that would show up in this PR when we remove error support from `state`.
hodlinator (Migrated from github.com) commented 2026-09-16 16:50:27 +00:00

nit: Technically this would be more correct:

            LogError("%s: CheckBlock or AcceptBlock FAILED (%s)", __func__, state.ToString());
nit: Technically this would be more correct: ```suggestion LogError("%s: CheckBlock or AcceptBlock FAILED (%s)", __func__, state.ToString()); ```
Lines 4459-4464
hodlinator (Migrated from github.com) commented 2026-09-16 16:51:28 +00:00

Could shorten to:

    if (auto res{ActiveChainstate().ActivateBestChain(block)}; !res.value_or(false)) {
        LogError("%s: ActivateBestChain failed (%s)", __func__, res ? "" : res.error().message());

Same below.

Could shorten to: ```suggestion if (auto res{ActiveChainstate().ActivateBestChain(block)}; !res.value_or(false)) { LogError("%s: ActivateBestChain failed (%s)", __func__, res ? "" : res.error().message()); ``` Same below.
Lines 4759-4762
hodlinator (Migrated from github.com) commented 2026-09-16 16:57:22 +00:00

nit: state is not technically used after this if-block, but would still be more correct to assign to it.

            auto res{chainstate.ConnectBlock(block, pindex, coins)};
            if (!res || !res->IsValid()) {
                LogError("Verification error: found unconnectable block at %d, hash=%s (%s)", pindex->nHeight, pindex->GetBlockHash().ToString(), res ? res->ToString() : res.error().message());
                return VerifyDBResult::CORRUPTED_BLOCK_DB;
            }
            state = *res;
nit: `state` is not technically used after this if-block, but would still be more correct to assign to it. ```suggestion auto res{chainstate.ConnectBlock(block, pindex, coins)}; if (!res || !res->IsValid()) { LogError("Verification error: found unconnectable block at %d, hash=%s (%s)", pindex->nHeight, pindex->GetBlockHash().ToString(), res ? res->ToString() : res.error().message()); return VerifyDBResult::CORRUPTED_BLOCK_DB; } state = *res; ```
hodlinator (Migrated from github.com) commented 2026-09-16 17:05:58 +00:00

nit: I think this code is important enough to keep calling out control flow a bit clearer:

                        if (!res) {
                            break;
                        }
nit: I think this code is important enough to *keep* calling out control flow a bit clearer: ```suggestion if (!res) { break; } ```
hodlinator (Migrated from github.com) commented 2026-09-17 08:36:02 +00:00

If the error is truly fatal, like the disk being unusable, should we still trigger signals like this one?

Maybe it's not worth changing the validation interface further than removing error from BlockValidationState.

Could add a separate FatalError signal if we really deem it worth handling?

Makes me wish BlockValidationState instead of IsValid()+IsInvalid()+IsError() just had one GetMode() which all consumers would put in switch blocks with exhaustive cases so that we could refactor with higher confidence.

If the error is truly *fatal*, like the disk being unusable, should we still trigger signals like this one? Maybe it's not worth changing the validation interface further than removing error from `BlockValidationState`. Could add a separate `FatalError` signal if we really deem it worth handling? Makes me wish `BlockValidationState` instead of `IsValid()`+`IsInvalid()`+`IsError()` just had one `GetMode()` which all consumers would put in `switch` blocks with exhaustive cases so that we could refactor with higher confidence.
optout21 commented 2026-09-17 10:30:03 +00:00 (Migrated from github.com)

not upgrading my Concept A to a proper acknowledgement

@DrahtBot note: As I've noticed during the discussion with @hodlinator , my previous concept A was interpreted as a plain ack. I think this is because there was no space between the "Concept" and "A", and there was a following commit ID. This was against my intention. I edit it to reflect this (insert a space). I should have noticed this, my mistake. Screenshots follow.

image image
> not upgrading my Concept A to a proper acknowledgement @DrahtBot note: As I've noticed during the discussion with @hodlinator , my previous concept A was interpreted as a plain ack. I think this is because there was no space between the "Concept" and "A", and there was a following commit ID. This was against my intention. I edit it to reflect this (insert a space). I should have noticed this, my mistake. Screenshots follow. <img width="1358" height="254" alt="image" src="https://github.com/user-attachments/assets/b2d5ee14-58c8-4b31-8942-28bc4de0ec67" /> <img width="1302" height="240" alt="image" src="https://github.com/user-attachments/assets/2ef85424-994f-46d8-a03c-30489fc5b821" />
maflcko commented 2026-09-17 11:26:03 +00:00 (Migrated from github.com)

Sure, fixed in github.com/maflcko/DrahtBot@7554887cad. You can edit it back, if you want.

Sure, fixed in https://github.com/maflcko/DrahtBot/commit/7554887cadb7c8fb614a278feef14ae399d125ce. You can edit it back, if you want.
optout21 commented 2026-09-17 22:52:07 +00:00 (Migrated from github.com)

Sure, fixed in maflcko/DrahtBot@7554887.

That was fast, thanks! 🙏

> Sure, fixed in [maflcko/DrahtBot@7554887](https://github.com/maflcko/DrahtBot/commit/7554887cadb7c8fb614a278feef14ae399d125ce). That was fast, thanks! 🙏
yuvicc (Migrated from github.com) reviewed 2026-09-18 06:35:58 +00:00
yuvicc (Migrated from github.com) commented 2026-09-18 06:35:58 +00:00

Done.

Done.
yuvicc (Migrated from github.com) reviewed 2026-09-18 06:39:15 +00:00
Lines 430-431
yuvicc (Migrated from github.com) commented 2026-09-18 06:39:15 +00:00

Correct. That was leftover from when ProcessNewBlock() returned only bool. Since it now returns util::Expected, we can use res.error().message() directly and remove sc->m_error.

Correct. That was leftover from when `ProcessNewBlock()` returned only bool. Since it now returns `util::Expected`, we can use `res.error().message()` directly and `remove sc->m_error`.
DrahtBot commented 2026-09-18 15:39:11 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/35315445149/job/105651757101
LLM reason (✨ experimental): CTest failed because the miner_tests test suite failed (ctest returned non-zero exit status 8).

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.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `test ancestor commits`: https://github.com/bitcoin/bitcoin/actions/runs/35315445149/job/105651757101</sub> <sub>LLM reason (✨ experimental): CTest failed because the `miner_tests` test suite failed (`ctest` returned non-zero exit status 8).</sub> <details><summary>Hints</summary> 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. </details>
yuvicc commented 2026-09-19 06:38:34 +00:00 (Migrated from github.com)

Thanks for the review @hodlinator and @optout21, I have split the commits more for easier review and addressed other comments:

  • Added the move-only kernel::FatalError type and co-located it with Notifications.

  • Changed FatalError::Raise() to take ownership of the translated message and move the original string into the error.

  • Renamed WithMessage() to ReplaceMessage().

  • Converted block storage, flushing, block connection, block acceptance, chain activation, invalidation, precious-block handling, and block
    submission to propagate fatal failures through util::Expected.

  • Changed FindUndoPos() to return FlatFilePos directly instead of using an output parameter.

  • Simplified util::Expected checks with value_or(false) where appropriate.

  • Preserved explicit validation-state checks where the returned BlockValidationState remains meaningful, including submitheader.

  • Removed the obsolete validation-state error mode and the kernel INTERNAL_ERROR mode.

  • Kept BlockChecked for ordinary validation results and handled fatal errors through the direct return value and fatalError notification.

  • Addressed the behavior change where fatal AcceptBlock failures no longer emit BlockChecked, peer block-source cleanup now happens directly when ProcessNewBlock() returns a fatal error.

  • Other nits and typos.

Thanks for the review @hodlinator and @optout21, I have split the commits more for easier review and addressed other comments: - Added the move-only `kernel::FatalError` type and co-located it with Notifications. - Changed `FatalError::Raise()` to take ownership of the translated message and move the original string into the error. - Renamed `WithMessage()` to `ReplaceMessage()`. - Converted block storage, flushing, block connection, block acceptance, chain activation, invalidation, precious-block handling, and block submission to propagate fatal failures through `util::Expected`. - Changed `FindUndoPos()` to return `FlatFilePos` directly instead of using an output parameter. - Simplified `util::Expected` checks with value_or(false) where appropriate. - Preserved explicit validation-state checks where the returned `BlockValidationState` remains meaningful, including submitheader. - Removed the obsolete validation-state error mode and the kernel `INTERNAL_ERROR` mode. - Kept `BlockChecked` for ordinary validation results and handled fatal errors through the direct return value and fatalError notification. - Addressed the behavior change where fatal `AcceptBlock` failures no longer emit `BlockChecked`, peer block-source cleanup now happens directly when `ProcessNewBlock()` returns a fatal error. - Other nits and typos.
optout21 (Migrated from github.com) reviewed 2026-09-22 10:05:00 +00:00
optout21 (Migrated from github.com) left a comment

Reviewed 22af5819cd, looks good!
Left some comments.

Reviewed 22af5819cd2d29df7a937909d6dd11f1f8abe2b2, looks good! Left some comments.
optout21 (Migrated from github.com) commented 2026-09-22 08:34:30 +00:00

80a8419 refactor: Make BlockManager use FatalError type:

Nit: res.error() could be also logged.

> [80a8419](https://github.com/bitcoin/bitcoin/pull/35646/changes/80a841992a538177059997bbfa697f71f67abbc7) _refactor: Make BlockManager use FatalError type_: Nit: `res.error()` could be also logged.
Lines 1153-1154
optout21 (Migrated from github.com) commented 2026-09-22 08:35:33 +00:00

80a8419 refactor: Make BlockManager use FatalError type:

Nit: 'res.error()` could be included in the log.

> [80a8419](https://github.com/bitcoin/bitcoin/pull/35646/changes/80a841992a538177059997bbfa697f71f67abbc7) _refactor: Make BlockManager use FatalError type_: Nit: 'res.error()` could be included in the log.
optout21 (Migrated from github.com) commented 2026-09-22 09:38:17 +00:00

0136c27 refactor: Make DisconnectTip() use FatalError type:

Should check that it has value, and it is Valid.

> [0136c27](https://github.com/bitcoin/bitcoin/pull/35646/changes/0136c278069612148ef8396ec3d47fcfb1b1ec0c) _refactor: Make DisconnectTip() use FatalError type_: Should check that it has value, and it is Valid.
optout21 (Migrated from github.com) commented 2026-09-22 09:12:40 +00:00

a43b082 refactor: Make AcceptBlock() use FatalError type:

Why remove this assert here, if it was introduced earlier? I can't see any relevant change in this commit.

> [a43b082](https://github.com/bitcoin/bitcoin/pull/35646/changes/a43b0826098409c26568f132789e729867e129c9) _refactor: Make AcceptBlock() use FatalError type_: Why remove this `assert` here, if it was introduced earlier? I can't see any relevant change in this commit.
optout21 (Migrated from github.com) commented 2026-09-22 08:48:42 +00:00

2b06306 refactor: Make ConnectBlock() use FatalError type:

Nit: This always returns Valid state, could be return {} to better reflect that, and make less use of the local state variable.

> [2b06306](https://github.com/bitcoin/bitcoin/pull/35646/changes/2b0630638c5ac1bd03c781770199da7887906ceb) _refactor: Make ConnectBlock() use FatalError type_: Nit: This always returns Valid state, could be `return {}` to better reflect that, and make less use of the local `state` variable.
optout21 (Migrated from github.com) commented 2026-09-22 09:01:30 +00:00

2b06306 refactor: Make ConnectBlock() use FatalError type:

This looks correct, but it could be a bit simplified and kept more similar to the original, if using !state.IsValid() as condition (it corresponds to state.IsInvalid() || state.IsError()).
Full code snippet:

        if (!state.IsValid()) {
            if (state.IsInvalid()) {
                InvalidBlockFound(pindexNew, state);
            LogInfo("%s: ConnectBlock %s failed, %s\n", __func__, pindexNew->GetBlockHash().ToString(), state.ToString());
            return false;
        }
> [2b06306](https://github.com/bitcoin/bitcoin/pull/35646/changes/2b0630638c5ac1bd03c781770199da7887906ceb) _refactor: Make ConnectBlock() use FatalError type_: This looks correct, but it could be a bit simplified and kept more similar to the original, if using `!state.IsValid()` as condition (it corresponds to `state.IsInvalid() || state.IsError()`). Full code snippet: ``` if (!state.IsValid()) { if (state.IsInvalid()) { InvalidBlockFound(pindexNew, state); LogInfo("%s: ConnectBlock %s failed, %s\n", __func__, pindexNew->GetBlockHash().ToString(), state.ToString()); return false; } ```
Lines 3227-3244
optout21 (Migrated from github.com) commented 2026-09-22 09:22:38 +00:00

0136c27 refactor: Make DisconnectTip() use FatalError type:

I think setting of state to *res in case of Invalid (res && res.IsInvalid()) is missing here, state is being used without being affected by the DisconnectTip call.
(I realize this finding becomes irrelevant in a later commit.)

> [0136c27](https://github.com/bitcoin/bitcoin/pull/35646/changes/0136c278069612148ef8396ec3d47fcfb1b1ec0c) _refactor: Make DisconnectTip() use FatalError type_: I think setting of `state` to `*res` in case of Invalid (`res && res.IsInvalid()`) is missing here, `state` is being used without being affected by the `DisconnectTip` call. (I realize this finding becomes irrelevant in a later commit.)
optout21 (Migrated from github.com) commented 2026-09-22 09:48:49 +00:00

c11ac78 refactor: Make ActivateBestChain() use FatalError type:

This is the only place where ActivateBestChain returns false. Maybe this could be turned into a FatalError (in a new commit), as it is Assume'd already. Then the return value could be changed to void from bool, and that would simplify call sites (there are duplicate branches for false and error).

> [c11ac78](https://github.com/bitcoin/bitcoin/pull/35646/changes/c11ac78862d51e7527dcc28766a7e95f22148827) _refactor: Make ActivateBestChain() use FatalError type_: This is the only place where `ActivateBestChain` returns false. Maybe this could be turned into a FatalError (in a new commit), as it is `Assume`'d already. Then the return value could be changed to `void` from `bool`, and that would simplify call sites (there are duplicate branches for false and error).
optout21 (Migrated from github.com) commented 2026-09-22 09:54:43 +00:00

876a2f9 refactor: Make InvalidateBlock() use FatalError type:

I think this line can stay untouched, with ret.value_or(false).

> [876a2f9](https://github.com/bitcoin/bitcoin/pull/35646/changes/876a2f999cac987ebfc03ae3ef43a2fd0e1f23c6) _refactor: Make InvalidateBlock() use FatalError type_: I think this line can stay untouched, with `ret.value_or(false)`.
Lines 4448-4452
optout21 (Migrated from github.com) commented 2026-09-22 09:14:08 +00:00

a43b082 refactor: Make AcceptBlock() use FatalError type:

Nit: This if occurs in a few places, would it make sense to factor it out somewhere?

> [a43b082](https://github.com/bitcoin/bitcoin/pull/35646/changes/a43b0826098409c26568f132789e729867e129c9) _refactor: Make AcceptBlock() use FatalError type_: Nit: This if occurs in a few places, would it make sense to factor it out somewhere?
hodlinator (Migrated from github.com) reviewed 2026-09-22 11:32:58 +00:00
hodlinator (Migrated from github.com) left a comment

Might take a while until I'm able to do a full review but I see you've incorporated my feedback from https://github.com/bitcoin/bitcoin/pull/35646#pullrequestreview-5210572199, thanks!

Might take a while until I'm able to do a full review but I see you've incorporated my feedback from https://github.com/bitcoin/bitcoin/pull/35646#pullrequestreview-5210572199, thanks!
hodlinator (Migrated from github.com) commented 2026-09-22 11:14:43 +00:00

re https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4069900161:

That is only true as long as the logic above doesn't change. Seems safest to use state as long as it exists.

re https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4069900161: That is only true as long as the logic above doesn't change. Seems safest to use `state` as long as it exists.
hodlinator (Migrated from github.com) commented 2026-09-22 11:16:04 +00:00

re https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4069993828:

Couldn't we just remove the check for IsInvalid() once we remove the Error-mode?

        if (!state.IsValid()) {
            InvalidBlockFound(pindexNew, state);
            LogInfo("%s: ConnectBlock %s failed, %s\n", __func__, pindexNew->GetBlockHash().ToString(), state.ToString());
            return false;
        }
re https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4069993828: Couldn't we just remove the check for `IsInvalid()` once we remove the Error-mode? ```c++ if (!state.IsValid()) { InvalidBlockFound(pindexNew, state); LogInfo("%s: ConnectBlock %s failed, %s\n", __func__, pindexNew->GetBlockHash().ToString(), state.ToString()); return false; } ```
hodlinator (Migrated from github.com) commented 2026-09-22 11:31:41 +00:00

re https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4070346105:

Yes, returning FatalError rather than false here seems like it would decrease incidental complexity.

re https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4070346105: Yes, returning `FatalError` rather than `false` here seems like it would decrease incidental complexity.
Lines 4448-4452
hodlinator (Migrated from github.com) commented 2026-09-22 11:20:07 +00:00

re https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4070085310:

state.Error() is removed in a later commit so I would defer considerations of factoring it out until later.

re https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4070085310: `state.Error()` is removed in a later commit so I would defer considerations of factoring it out until later.
optout21 (Migrated from github.com) reviewed 2026-09-22 13:02:23 +00:00
optout21 (Migrated from github.com) commented 2026-09-22 13:02:23 +00:00

2b06306 refactor: Make ConnectBlock() use FatalError type:

That's true, but it could be improved by making state an if-local in the block where CheckBlock is called, and the declaration of method-local state variable could be moved further down. That way there would be no chance to represent an non-Valid state at this point. (My guiding principle here is to reduce the scope of variables.)

> [2b06306](https://github.com/bitcoin/bitcoin/pull/35646/changes/2b0630638c5ac1bd03c781770199da7887906ceb) _refactor: Make ConnectBlock() use FatalError type_: That's true, but it could be improved by making `state` an if-local in the block where `CheckBlock` is called, and the declaration of method-local `state` variable could be moved further down. That way there would be no chance to represent an non-Valid state at this point. (My guiding principle here is to reduce the scope of variables.)
optout21 (Migrated from github.com) reviewed 2026-09-22 14:26:53 +00:00
Lines 419-421
optout21 (Migrated from github.com) commented 2026-09-22 14:26:53 +00:00

I think this is still a valid concern (in 22af5819cd).
The reason can end up here e.g. with "Failed to write undo data." or "Failed to read block.". I think previously it could only assume "inconclusive".
Could you unresolve this?

I think this is still a valid concern (in 22af5819cd2d29df7a937909d6dd11f1f8abe2b2). The `reason` can end up here e.g. with "Failed to write undo data." or "Failed to read block.". I think previously it could only assume "inconclusive". Could you unresolve this?
optout21 (Migrated from github.com) reviewed 2026-09-22 14:33:07 +00:00
Lines 3038-3042
optout21 (Migrated from github.com) commented 2026-09-22 14:33:07 +00:00

I think this still applies! (in commit 22af5819cd)
Could you unresolve?

I think this still applies! (in commit 22af5819cd2d29df7a937909d6dd11f1f8abe2b2) Could you unresolve?
hodlinator (Migrated from github.com) reviewed 2026-09-22 19:02:18 +00:00
Lines 3038-3042
hodlinator (Migrated from github.com) commented 2026-09-22 19:02:18 +00:00

Agree we need to be careful around this but I think the current approach has promise. Should call out that BlockChecked is only called for Valid/Invalid blocks now in the PR description.

Agree we need to be careful around this but I think the current approach has promise. Should call out that `BlockChecked` is only called for Valid/Invalid blocks now in the PR description.
yuvicc (Migrated from github.com) reviewed 2026-09-23 04:46:41 +00:00
yuvicc (Migrated from github.com) commented 2026-09-23 04:46:41 +00:00

Correct. Thanks.

Correct. Thanks.
yuvicc (Migrated from github.com) reviewed 2026-09-23 05:03:25 +00:00
Lines 1153-1154
yuvicc (Migrated from github.com) commented 2026-09-23 05:03:25 +00:00

Done, Thanks.

Done, Thanks.
yuvicc (Migrated from github.com) reviewed 2026-09-23 05:07:39 +00:00
yuvicc (Migrated from github.com) commented 2026-09-23 05:07:39 +00:00

Hmm. I think this can be also be applied the same to the fJustCheck early return and the final return, since those are also always valid at that point (invalid states are returned earlier) ?

Hmm. I think this can be also be applied the same to the `fJustCheck` early return and the final return, since those are also always valid at that point (invalid states are returned earlier) ?
yuvicc (Migrated from github.com) reviewed 2026-09-23 05:12:44 +00:00
yuvicc (Migrated from github.com) commented 2026-09-23 05:12:44 +00:00

This looks correct, but it could be a bit simplified.....

Good catch, restructured to !state.IsValid() with the nested IsInvalid() check, keeping LogError as in the original.

> > This looks correct, but it could be a bit simplified..... Good catch, restructured to `!state.IsValid()` with the nested `IsInvalid()` check, keeping `LogError` as in the original.
yuvicc (Migrated from github.com) reviewed 2026-09-23 05:13:57 +00:00
yuvicc (Migrated from github.com) commented 2026-09-23 05:13:57 +00:00

Couldn't we just remove the check for IsInvalid() once we remove the Error-mode?

Agreed, dropped the IsInvalid() check in "consensus: remove ValidationState error mode", since !IsValid() is equivalent once Error mode is gone.

> Couldn't we just remove the check for `IsInvalid()` once we remove the Error-mode? Agreed, dropped the `IsInvalid()` check in "consensus: remove `ValidationState` error mode", since `!IsValid()` is equivalent once Error mode is gone.
yuvicc (Migrated from github.com) reviewed 2026-09-23 05:39:36 +00:00
yuvicc (Migrated from github.com) commented 2026-09-23 05:39:36 +00:00

Good catch, that was unintentional.

Good catch, that was unintentional.
yuvicc (Migrated from github.com) reviewed 2026-09-23 05:41:47 +00:00
yuvicc (Migrated from github.com) commented 2026-09-23 05:41:47 +00:00

Thanks, done.

Thanks, done.
yuvicc (Migrated from github.com) reviewed 2026-09-23 05:42:58 +00:00
yuvicc (Migrated from github.com) commented 2026-09-23 05:42:58 +00:00

Agree!

Agree!
optout21 (Migrated from github.com) reviewed 2026-09-23 06:01:46 +00:00
Lines 4448-4452
optout21 (Migrated from github.com) commented 2026-09-23 06:01:46 +00:00

OK, I retract this, feel free to Resolve.

OK, I retract this, feel free to Resolve.
yuvicc (Migrated from github.com) reviewed 2026-09-23 06:05:37 +00:00
yuvicc (Migrated from github.com) commented 2026-09-23 06:05:37 +00:00

Hmm, ProcessNewBlock() gets bg_chain from HistoricalChainstate() under cs_main, then releases the lock before calling bg_chain->ActivateBestChain(). If another ProcessNewBlock() caller (msghand, submitblock RPC, or the loadblk thread) is inside the background chainstate's ActivateBestChain() at that moment, it can reach the snapshot base block. MaybeValidateSnapshot() then sets m_target_utxohash, and the first thread hits this check as soon as it gets m_chainstate_mutex. That window is narrow but real, making it a FatalError would shut down nodes, and also that behavior change doesn't belong in a refactor PR ?

Hmm, `ProcessNewBlock()` gets `bg_chain` from `HistoricalChainstate()` under `cs_main`, then releases the lock before calling `bg_chain->ActivateBestChain()`. If another `ProcessNewBlock()` caller (`msghand`, `submitblock` RPC, or the `loadblk` thread) is inside the background chainstate's `ActivateBestChain()` at that moment, it can reach the snapshot base block. `MaybeValidateSnapshot()` then sets `m_target_utxohash`, and the first thread hits this check as soon as it gets `m_chainstate_mutex`. That window is narrow but real, making it a `FatalError` would shut down nodes, and also that behavior change doesn't belong in a refactor PR ?
optout21 (Migrated from github.com) reviewed 2026-09-23 06:15:22 +00:00
optout21 (Migrated from github.com) commented 2026-09-23 06:15:22 +00:00

I think this can be also be applied the same to the fJustCheck early return and the final return

That seems to be the case: after the genesis block early return there is a large portion of code where validation checks are made, and state may be set to Invalid, without immediate return. But at the end, there is a return on Invalid. So by the time execution gets to the fJustCheck early return, state must be Valid. I would put an Assume(state.IsValid()) there to show and enforce. The early return and the final return can be {} then.
But on a second thought I lean to leaving as-is, seems a bit risky. With this change the scope of the state local variable would not be reduces, so I don't think it's worth it.

> I think this can be also be applied the same to the `fJustCheck` early return and the final return That seems to be the case: after the genesis block early return there is a large portion of code where validation checks are made, and `state` may be set to Invalid, without immediate return. But at the end, there is a return on Invalid. So by the time execution gets to the `fJustCheck` early return, `state` must be Valid. I would put an `Assume(state.IsValid())` there to show and enforce. The early return and the final return can be `{}` then. But on a second thought I lean to leaving as-is, seems a bit risky. With this change the scope of the `state` local variable would not be reduces, so I don't think it's worth it.
yuvicc commented 2026-09-23 14:35:16 +00:00 (Migrated from github.com)

Thanks for review @optout21. Addressed comments:

  • Included the FatalError message in the FindUndoPos and FindNextBlockPos failure logs. Restored the assert(!res->IsNull()) that was unintentionally dropped in the AcceptBlock commit.
  • Return {} instead of state on paths where the state is always valid.
  • the MaybeUpdateMempoolForReorg(...) line is now untouched and keeps ret.value_or(false).
  • dropped the now-redundant IsInvalid() check before InvalidBlockFound() in ConnectTip()
Thanks for review @optout21. Addressed comments: - Included the `FatalError` message in the `FindUndoPos` and `FindNextBlockPos` failure logs. Restored the `assert(!res->IsNull())` that was unintentionally dropped in the AcceptBlock commit. - Return `{}` instead of `state` on paths where the state is always valid. - the `MaybeUpdateMempoolForReorg(...)` line is now untouched and keeps `ret.value_or(false)`. - dropped the now-redundant `IsInvalid()` check before `InvalidBlockFound()` in `ConnectTip()`
purpleKarrot commented 2026-09-23 19:30:35 +00:00 (Migrated from github.com)

I agree with the full motivation but disagree (NACK) conceptually with using util::Expected/std::expected.

std::expected-style error handling trades runtime efficiency for runtime deterministic performance, which is a valid trade-off for systems with hard-realtime-requirements. I explained it on multiple occasions that for Bitcoin, runtime efficiency is more important than runtime deterministic performance, because we need IBD to be as fast as possible and new blocks are added on an extremely irregular cadence (approximately ten minutes on average is about as far away from a hard realtime system as you can possibly imagine). Hence, for Bitcoin, throwing exceptions is the more appropriate mechanism for error handling.

I agree with the full motivation but disagree (NACK) conceptually with using `util::Expected`/`std::expected`. `std::expected`-style error handling trades runtime efficiency for runtime deterministic performance, which is a valid trade-off for systems with hard-realtime-requirements. I explained it on multiple occasions that for Bitcoin, runtime efficiency is more important than runtime deterministic performance, because we need IBD to be as fast as possible and new blocks are added on an extremely irregular cadence (approximately ten minutes on average is about as far away from a hard realtime system as you can possibly imagine). Hence, for Bitcoin, throwing exceptions is the more appropriate mechanism for error handling.
l0rinc commented 2026-09-23 19:51:33 +00:00 (Migrated from github.com)

I explained it on multiple occasions that for Bitcoin, runtime efficiency is more important than runtime deterministic performance

And you received pushback every single time (e.g. https://github.com/bitcoin/bitcoin/pull/36101): exceptions are hard-to-predict invisible control flow, which is why many newer languages are moving away from them and towards explicit, value-based error handling to minimize surprises.
You're presenting your opinion as facts here, ignoring the project's specific needs and history.

because we need IBD to be as fast as possible

I'm glad you're worried about this, so are we, it's why we've been working on this for years, we still have many open PRs optimizing this, you can help by reviewing them. That's also a good way to familiarize yourself with the project.

Hence, for Bitcoin, throwing exceptions is the more appropriate mechanism for error handling.

No, in mission-critical applications exceptions are often forbidden for good reason: they're hard to predict in exceptional (pun intended) circumstances.

> I explained it on multiple occasions that for Bitcoin, runtime efficiency is more important than runtime deterministic performance And you received pushback every single time (e.g. https://github.com/bitcoin/bitcoin/pull/36101): exceptions are hard-to-predict invisible control flow, which is why many newer languages are moving away from them and towards explicit, value-based error handling to minimize surprises. You're presenting your opinion as facts here, ignoring the project's specific needs and history. > because we need IBD to be as fast as possible I'm glad you're worried about this, so are we, it's why we've been working on this for years, we still have many open PRs optimizing this, you can help by reviewing them. That's also a good way to familiarize yourself with the project. > Hence, for Bitcoin, throwing exceptions is the more appropriate mechanism for error handling. No, in mission-critical applications exceptions are often forbidden for good reason: they're hard to predict in exceptional (pun intended) circumstances.
DrahtBot commented 2026-09-24 05:49:19 +00:00 (Migrated from github.com)

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

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
hodlinator commented 2026-09-24 17:51:20 +00:00 (Migrated from github.com)

@purpleKarrot I watched the talk you recommended by Khalil Estell. My impression was that [Ee]xpected performs poorly primarily when the involved types are large/complex. Types being able to be moved like the proposed FatalError probably helps.

I think sacrificing a tiny bit of efficiency in exchange for making error handling explicit at each level is the prudent approach in this part of the code.

@purpleKarrot I watched the talk you recommended by Khalil Estell. My impression was that [Ee]xpected performs poorly primarily when the involved types are large/complex. Types being able to be moved like the proposed `FatalError` probably helps. I think sacrificing a tiny bit of efficiency in exchange for making error handling explicit at each level is the prudent approach in this part of the code.
yuvicc commented 2026-09-25 05:08:55 +00:00 (Migrated from github.com)

std::expected-style error handling trades runtime efficiency for runtime deterministic performance, which is a valid trade-off for systems with hard-realtime-requirements.

Thanks @purpleKarrot. I agree that IBD throughput matters and that exceptions might provide a cheaper success path. However, deterministic execution isn’t the reason for choosing util::Expected here. Its other benefit is making the distinction between a validation result and an operational failure explicit in the function’s interface. That is also part of the motivation for std::expected.

Apart from that there is also existing control flow to preserve. For example, ActivateBestChainStep() updates the mempool after a failed connection or disconnection before propagating the failure. An exception based implementation could preserve this too, but would require deliberately arranging cleanup and catch boundaries, including at the kernel API. Keeping explicit propagation makes that separation a more easier to review change. Also opened a PR in benchcoin to check the IBD performance.

> std::expected-style error handling trades runtime efficiency for runtime deterministic performance, which is a valid trade-off for systems with hard-realtime-requirements. Thanks @purpleKarrot. I agree that IBD throughput matters and that exceptions might provide a cheaper success path. However, deterministic execution isn’t the reason for choosing `util::Expected` here. Its other benefit is making the distinction between a validation result and an operational failure explicit in the function’s interface. That is also part of the [motivation](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p0323r12.html#yay) for std::expected. Apart from that there is also existing control flow to preserve. For example, `ActivateBestChainStep()` updates the mempool after a failed connection or disconnection before propagating the failure. An exception based implementation could preserve this too, but would require deliberately arranging cleanup and catch boundaries, including at the kernel API. Keeping explicit propagation makes that separation a more easier to review change. Also opened a [PR](https://github.com/bitcoin-dev-tools/benchcoin/pull/200) in benchcoin to check the IBD performance.
yuvicc commented 2026-09-25 05:10:41 +00:00 (Migrated from github.com)

Rebased onto master (e8e7e91a11) and resolved conflicts with #35675.

Rebased onto master (e8e7e91a11) and resolved conflicts with #35675.
purpleKarrot commented 2026-09-25 05:46:52 +00:00 (Migrated from github.com)

making the distinction between a validation result and an operational failure explicit

My point is that this distinction is not explicit enough when both are communicated over the same channel.

When block validation returns a success value and throws on exception, client code will look like this:

auto res = validate(block);
if (res) {
  // block is valid
} else {
  // block is invalid
}

Operational failure will take neither of the two branches.

But when validate returns an expected object, operator bool will just tell whether a fatal error occurred. If user code uses conditions like res && res->IsValid(), it is very dangerous to have an else branch, because it may lead to the same situation that caused the 2013 chain split.

And furthermore: If functions returning expected are not marked noexcept, all clients now have to deal with two error handling mechanisms. But if the function is marked noexcept, it will terminate when an actual exception is thrown.

> making the distinction between a validation result and an operational failure explicit My point is that this distinction is not explicit enough when both are communicated over the same channel. When block validation returns a success value and throws on exception, client code will look like this: ```cpp auto res = validate(block); if (res) { // block is valid } else { // block is invalid } ``` Operational failure will take neither of the two branches. But when validate returns an expected object, `operator bool` will just tell whether a fatal error occurred. If user code uses conditions like `res && res->IsValid()`, it is very dangerous to have an `else` branch, because it may lead to the same situation that caused the 2013 chain split. And furthermore: If functions returning expected are not marked `noexcept`, all clients now have to deal with *two* error handling mechanisms. But if the function is marked `noexcept`, it will terminate when an actual exception is thrown.
optout21 commented 2026-09-25 06:45:45 +00:00 (Migrated from github.com)

I agree with the full motivation but disagree (NACK) conceptually with using util::Expected/std::expected.

Contrarian views have the potential to advance things. I've considered your point of view from different sides (including discussions in #36101).
My personal conclusion is that in this particular instance (and probably in many others as well) returns are preferable over exceptions, because the latter is more brittle and error prone in face of future code changes. I say this considering the criticality of the validation code, and also the losly organized nature of the project.
Your objection did raise my awareness of the cost aspects of passing objects as return values (structs, Expected, string fields, movability, etc.), but I dismiss your performance degradation point as minor in comparison with the risks of future mishandled errors.

> I agree with the full motivation but disagree (NACK) conceptually with using `util::Expected`/`std::expected`. Contrarian views have the potential to advance things. I've considered your point of view from different sides (including discussions in #36101). My personal conclusion is that in this particular instance (and probably in many others as well) __returns are preferable over exceptions__, because the latter is more brittle and error prone in face of future code changes. I say this considering the criticality of the validation code, and also the losly organized nature of the project. Your objection did raise my awareness of the cost aspects of passing objects as return values (structs, Expected, string fields, movability, etc.), but I dismiss your performance degradation point as minor in comparison with the risks of future mishandled errors.
optout21 commented 2026-09-25 10:55:19 +00:00 (Migrated from github.com)

Triggered by the return-vs-throw discussion (@purpleKarrot), I've done some microbenchmarking of the different error styles. Styles compared:

  • 0 baseline: always return void, no state
  • 1 return bool, with BlockValidationState as parameter
  • 1.a out-only: set the state on success too (state = {})
  • 1.b in-out: do not touch the state on success (as in the codebase)
  • 2 return BlockValidationState
  • 3 return util::Expected<BlockValidationState, kernel::FatalError>
  • 4 return BlockValidationState (valid or invalid), throw on fatal error
  • 5 return util::Expected<void, std::variant<BlockValidationState, kernel::FatalError>>

For 1&2 it is assumed that state can represent Error as well (not the case in this PR any more, but was before)

The benchmark does 50M iterations of a method call, which itself calls into other methods, with branch-out factor of 2 for 2 levels (1+2+4 = 7 total calls).

Every 1000th call returns invalid, every 1000th (not the same ones) return Error, the rest of the calls (998) return success.

The benchmarks is available at: https://github.com/optout21/bitcoin/blob/error-style-bench/src/bench/validation_state_error_handling.cpp

Sample results below.

Some conclusions:

  • 1.b is the fastest, when the state parameter is not touched at all in the success branch. However, this is not very clean, as state from different methods can get mixed or overwritten, and we aim to make this cleaner (this PR, #35570)
  • util::Expected is generally not slower than out-param style. In fact in some earlier iteration it was even faster than the plain return (analysis found that the differences are due to the specifics of compiler branch optimizations).
  • return+throw is the slowest, due to the overhead of exceptions. With no exceptions, it's the same as the plain return.
  • Generally differences are very small, especially compared to time for the real work of the methods. Differences are on the micro-optimization level. A lot depends on how the state variable is set, in what order it is checked, etc.
  • An interesting idea out of this is that we could to optimize for the frequent success case, and do not use a BlockValidationState object in success case at all. This can be achieved e.g. by instead of:`

util::Expected<BlockValidationState, kernel::FatalError>

using:

util::Expected<void, util::Expected<BlockValidationState, kernel::FatalError>>
or
util::Expected<void, std::variant<BlockValidationState, kernel::FatalError>>

This way the success case is optimized, and this is confirmed by the benchmark. @yuvicc, give it a thought. However, I think it's a micro-optimization not worth doing.

Sample benchmark results
|             ns/call |              call/s |    err% |     total | benchmark
|--------------------:|--------------------:|--------:|----------:|:----------
|                8.23 |      121,479,880.24 |    0.1% |      4.53 | `ErrorHandlingBaselineVoid`
|                8.37 |      119,486,068.62 |    0.0% |      4.60 | `ErrorHandlingBoolInOutState`
|               16.11 |       62,068,002.98 |    0.2% |      8.87 | `ErrorHandlingBoolOutState`
|               14.93 |       66,989,455.90 |    0.1% |      8.27 | `ErrorHandlingReturnExpectedState`
|               14.43 |       69,293,814.61 |    0.0% |      7.94 | `ErrorHandlingReturnState`
|               21.06 |       47,483,573.19 |    0.1% |     11.59 | `ErrorHandlingReturnStateThrow`
|               10.52 |       95,014,644.68 |    0.0% |      5.80 | `ErrorHandlingReturnVoidExpected`
Triggered by the return-vs-throw discussion (@purpleKarrot), I've done some microbenchmarking of the different error styles. Styles compared: - 0 baseline: always return void, no state - 1 return `bool`, with `BlockValidationState` as parameter - 1.a out-only: set the state on success too (`state = {}`) - 1.b in-out: do not touch the state on success (as in the codebase) - 2 return `BlockValidationState` - 3 return `util::Expected<BlockValidationState, kernel::FatalError>` - 4 return `BlockValidationState` (valid or invalid), throw on fatal error - 5 return `util::Expected<void, std::variant<BlockValidationState, kernel::FatalError>>` For 1&2 it is assumed that state can represent Error as well (not the case in this PR any more, but was before) The benchmark does 50M iterations of a method call, which itself calls into other methods, with branch-out factor of 2 for 2 levels (1+2+4 = 7 total calls). Every 1000th call returns invalid, every 1000th (not the same ones) return Error, the rest of the calls (998) return success. The benchmarks is available at: https://github.com/optout21/bitcoin/blob/error-style-bench/src/bench/validation_state_error_handling.cpp Sample results below. Some conclusions: - 1.b is the fastest, when the `state` parameter is not touched at all in the success branch. However, this is not very clean, as state from different methods can get mixed or overwritten, and we aim to make this cleaner (this PR, #35570) - `util::Expected` is generally not slower than out-param style. In fact in some earlier iteration it was even faster than the plain return (analysis found that the differences are due to the specifics of compiler branch optimizations). - return+throw is the slowest, due to the overhead of exceptions. With no exceptions, it's the same as the plain return. - Generally differences are very small, especially compared to time for the real work of the methods. Differences are on the micro-optimization level. A lot depends on how the state variable is set, in what order it is checked, etc. - An interesting idea out of this is that we could to optimize for the frequent success case, and do not use a `BlockValidationState` object in success case at all. This can be achieved e.g. by instead of:` `util::Expected<BlockValidationState, kernel::FatalError>` using: `util::Expected<void, util::Expected<BlockValidationState, kernel::FatalError>>` or `util::Expected<void, std::variant<BlockValidationState, kernel::FatalError>>` This way the success case is optimized, and this is confirmed by the benchmark. @yuvicc, give it a thought. However, I think it's a micro-optimization not worth doing. <details> <summary> Sample benchmark results </summary> ``` | ns/call | call/s | err% | total | benchmark |--------------------:|--------------------:|--------:|----------:|:---------- | 8.23 | 121,479,880.24 | 0.1% | 4.53 | `ErrorHandlingBaselineVoid` | 8.37 | 119,486,068.62 | 0.0% | 4.60 | `ErrorHandlingBoolInOutState` | 16.11 | 62,068,002.98 | 0.2% | 8.87 | `ErrorHandlingBoolOutState` | 14.93 | 66,989,455.90 | 0.1% | 8.27 | `ErrorHandlingReturnExpectedState` | 14.43 | 69,293,814.61 | 0.0% | 7.94 | `ErrorHandlingReturnState` | 21.06 | 47,483,573.19 | 0.1% | 11.59 | `ErrorHandlingReturnStateThrow` | 10.52 | 95,014,644.68 | 0.0% | 5.80 | `ErrorHandlingReturnVoidExpected` ``` </details>
optout21 (Migrated from github.com) reviewed 2026-09-25 11:02:53 +00:00
optout21 (Migrated from github.com) commented 2026-09-25 11:02:53 +00:00

00158ab consensus: remove ValidationState error mode:

Now that the mode is only binary, maybe consider simplifying to a bool?

> [00158ab](https://github.com/bitcoin/bitcoin/pull/35646/changes/00158abcb44b4bb0e9d98e5aad2229834355a489) _consensus: remove ValidationState error mode_: Now that the mode is only binary, maybe consider simplifying to a `bool`?
arejula27 commented 2026-09-26 11:58:42 +00:00 (Migrated from github.com)

Concept ACK

I like the util::Expected direction, as I also asked for it in my review on #35570, so consider this a supporting vote for it. I do not like exceptions, and this error handling is much easier to understand and follow.

Since this PR and my own #36326 ("kernel: Use typed errors for fatal and flush error notifications") overlap, there are a couple of things I would like to mention.

Adding a new type to the kernel here feels from my pov out of scope for this PR, separate from what it sets out to fix (the tri-state in BlockValidationState), since that is already achievable with plain strings. Adding a type is an improvement on top of that, not a requirement for it, and has more implications than what has been already discussed in this conversation: it pulls more core-owned dependencies into the kernel, which I think goes against the general direction of the libbitcoinkernel project, fixes the shape of the errors inside the kernel and also broadens kernel maintenance surface. The kernel is consensus-critical code, so the less responsibility it carries, the easier it is to maintain. Those feel like implications that deserve their own discussion. I have been exploring how to improve the error type and remove dependencies from the kernel for a few months now, until finally proposing #36326. My focus was extracting bilingual_str and improving the kernel API, unrelated to this PR's behavior, but our work ended up colliding.

I think the two ideas are not in conflict, and can actually be combined: the typed kernel::FatalError variant from #36326 could be the payload util::Expected carries here instead of a wrapped-string. Notifying and building the message are already two separate steps in #36326: fatalError() fires right at the origin with the typed data, no string needed at that point, and the translated message gets built afterwards, downstream, on the node side. So swapping the payload would not delay or otherwise change when the fatal notification fires, only what it carries. Worth discussing which PR keeps which part before either one merges, since right now both define kernel::FatalError with the same name, different responsibilities, and incompatible shapes.

Concept ACK I like the `util::Expected` direction, as I also asked for it in [my review on #35570](https://github.com/bitcoin/bitcoin/pull/35570#pullrequestreview-4555262677), so consider this a supporting vote for it. I do not like exceptions, and this error handling is much easier to understand and follow. Since this PR and my own #36326 ("kernel: Use typed errors for fatal and flush error notifications") overlap, there are a couple of things I would like to mention. Adding a new type to the kernel here feels from my pov out of scope for this PR, separate from what it sets out to fix (the tri-state in `BlockValidationState`), since that is already achievable with plain strings. Adding a type is an improvement on top of that, not a requirement for it, and has more implications than what has been already discussed in this conversation: it pulls more core-owned dependencies into the kernel, which I think goes against the general direction of the `libbitcoinkernel` project, fixes the shape of the errors inside the kernel and also broadens kernel maintenance surface. The kernel is consensus-critical code, so the less responsibility it carries, the easier it is to maintain. Those feel like implications that deserve their own discussion. I have been exploring how to improve the error type and remove dependencies from the kernel for a few months now, until finally proposing #36326. My focus was extracting `bilingual_str` and improving the kernel API, unrelated to this PR's behavior, but our work ended up colliding. I think the two ideas are not in conflict, and can actually be combined: the typed `kernel::FatalError` variant from #36326 could be the payload `util::Expected` carries here instead of a wrapped-string. Notifying and building the message are already two separate steps in #36326: `fatalError()` fires right at the origin with the typed data, no string needed at that point, and the translated message gets built afterwards, downstream, on the node side. So swapping the payload would not delay or otherwise change when the fatal notification fires, only what it carries. Worth discussing which PR keeps which part before either one merges, since right now both define `kernel::FatalError` with the same name, different responsibilities, and incompatible shapes.
yuvicc commented 2026-09-29 05:23:32 +00:00 (Migrated from github.com)

Thanks @optout21 for putting this together! I reproduced it locally ( with standalone at -O2, pinned core, GCC 14.2 / Clang 18.1). Results in ns per top-level call (7 nested calls):

benchmark results | Style | GCC | Clang | |-----------------------------|------|-------| | 0 baseline | 10.4 | 10.6 | | 1a out-param | 24.9 | 29.2 | | 1b in-out | 11.9 | 11.5 | | 2 return state | 24.0 | 23.6 | | 3 Expected | 26.4 | 32.4 | | 4 return + throw | 33.8 | 39.7 | | 5 Expected | 16.7 | 20.4 |

The ordering matches yours one. The main cost is building a BlockValidationState (two std::strings) on the success path, not the return mechanism. Agree that style no. 5 isn't worth it now. Moving Invalid into the error channel alongside FatalError would also blur the separation this PR aims for.

Thanks @optout21 for putting this together! I reproduced it locally ( with standalone at -O2, pinned core, GCC 14.2 / Clang 18.1). Results in ns per top-level call (7 nested calls): <details> <summary> benchmark results </summary> | Style | GCC | Clang | |-----------------------------|------|-------| | 0 baseline | 10.4 | 10.6 | | 1a out-param | 24.9 | 29.2 | | 1b in-out | 11.9 | 11.5 | | 2 return state | 24.0 | 23.6 | | 3 Expected<BVS, FatalError> | 26.4 | 32.4 | | 4 return + throw | 33.8 | 39.7 | | 5 Expected<void, variant> | 16.7 | 20.4 | </details> The ordering matches yours one. The main cost is building a `BlockValidationState` (two std::strings) on the success path, not the return mechanism. Agree that style no. 5 isn't worth it now. Moving Invalid into the error channel alongside FatalError would also blur the separation this PR aims for.
optout21 commented 2026-09-29 06:36:58 +00:00 (Migrated from github.com)

Agree that style no. 5 isn't worth it now. Moving Invalid into the error channel alongside FatalError would also blur the separation this PR aims for.

Thanks for looking into it! I think we are in agreement.
The result return is not the hot-path of the chain validation, over-optimization doesn't worth it.

> Agree that style no. 5 isn't worth it now. Moving Invalid into the error channel alongside FatalError would also blur the separation this PR aims for. Thanks for looking into it! I think we are in agreement. The result return is not the hot-path of the chain validation, over-optimization doesn't worth it.
First-time contributor

Earlier concerns remain unresolved; see the full report for their current assessments.

🟠 Minor · Reorg disconnect flush failures no longer raise fatalError

Kernel clients that treat flush_error as non-fatal can miss the unrecoverable-error signal when a required reorg-disconnect flush fails.

Location: src/validation.cpp:3288 (head).

🔵 Suggestion · Fatal-error callback comments omit flushError

ProcessNewBlock can return a FatalError after only flushError fires, contrary to comments that direct callers and kernel embedders solely to fatalError.

Location: src/validation.h:1281 (head).

🔵 Suggestion · Fatal-submission tests miss submitblock's RPC error branch

The fixture only exercises BlockTemplateManager::SubmitBlock, so it does not protect submitblock's new RPC_VERIFY_ERROR result after a fatal failure, including one following a valid BlockChecked notification.

Location: src/test/validation_block_tests.cpp:116 (head).

🔵 Suggestion · TestBlockValidity exposes an unreachable FatalError alternative

Keeping Expected for a currently impossible fatal outcome adds four unreachable caller branches and an unnecessary Mining::checkBlock error contract.

Location: src/node/interfaces.cpp:1006 (head).

Review coverage was incomplete.


Reviewed: ebe01e1c00fb · Full review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:965af1044d9e41839565702e4d9bd0a751eda81f6e8b6402747fa296ef84ebea:7efd3c3ba41667382004cfa7a7db56605da7d8f9b7ab69bc483f27117390ba48 --> <!-- ralph-base:ddea9196493d3b8fd841a36a6c53efd85dac7a05 --> <!-- ralph-head:ebe01e1c00fb9ceee873c8b4e182273392d1f405 --> <!-- ralph-case:eca1e5d1b503ff4302c1182d73c20af49b1b77563cf0570d10c95cf330404a8f --> Earlier concerns remain unresolved; see the full report for their current assessments. **🟠 Minor · Reorg disconnect flush failures no longer raise fatalError** Kernel clients that treat flush_error as non-fatal can miss the unrecoverable-error signal when a required reorg-disconnect flush fails. Location: [`src/validation.cpp:3288`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/ebe01e1c00fb9ceee873c8b4e182273392d1f405/src/validation.cpp#L3288>) (head). **🔵 Suggestion · Fatal-error callback comments omit flushError** ProcessNewBlock can return a FatalError after only flushError fires, contrary to comments that direct callers and kernel embedders solely to fatalError. Location: [`src/validation.h:1281`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/ebe01e1c00fb9ceee873c8b4e182273392d1f405/src/validation.h#L1281>) (head). **🔵 Suggestion · Fatal-submission tests miss submitblock's RPC error branch** The fixture only exercises BlockTemplateManager::SubmitBlock, so it does not protect submitblock's new RPC_VERIFY_ERROR result after a fatal failure, including one following a valid BlockChecked notification. Location: [`src/test/validation_block_tests.cpp:116`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/ebe01e1c00fb9ceee873c8b4e182273392d1f405/src/test/validation_block_tests.cpp#L116>) (head). **🔵 Suggestion · TestBlockValidity exposes an unreachable FatalError alternative** Keeping Expected for a currently impossible fatal outcome adds four unreachable caller branches and an unnecessary Mining::checkBlock error contract. Location: [`src/node/interfaces.cpp:1006`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/ebe01e1c00fb9ceee873c8b4e182273392d1f405/src/node/interfaces.cpp#L1006>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`ebe01e1c00fb`](<https://git.fish.foo/bitcoin/bitcoin/commit/ebe01e1c00fb9ceee873c8b4e182273392d1f405>) · [Full review report](<https://review.fish.foo/traces/35646-ebe01e1c00fb9ceee873c8b4e182273392d1f405-2031-2.html>) · [Previous reports](<https://review.fish.foo/traces/35646/>) [permalink](<https://review.fish.foo/traces/35646-ebe01e1c00fb9ceee873c8b4e182273392d1f405-2031-2.html>)
DrahtBot commented 2026-10-06 00:31:07 +00:00 (Migrated from github.com)

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

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
purpleKarrot commented 2026-10-09 11:17:19 +00:00 (Migrated from github.com)

I like the util::Expected direction, ... I do not like exceptions,

Can we please leave personal preference completely out of the discussion and make a decision based on technical merit? I have documented the risks of result-style error handling ("intermediate functions should not receive errors as values or through shared state that they can inspect, suppress, or turn into validation results. ... Each such handling point creates an opportunity for misuse") in https://github.com/bitcoin/bitcoin/pull/36101#issuecomment-6045777724 and made a direct connection to the 2013 chain split. As written there, I would welcome concrete technical arguments in favor of an alternative design. I hope we can reach consensus before more quality regressions are introduced into the codebase without a proper design goal.

> **I like** the `util::Expected` direction, ... **I do not like** exceptions, Can we please leave personal preference completely out of the discussion and make a decision based on technical merit? I have documented the risks of result-style error handling ("intermediate functions should not receive errors as values or through shared state that they can inspect, suppress, or turn into validation results. ... Each such handling point creates an opportunity for misuse") in https://github.com/bitcoin/bitcoin/pull/36101#issuecomment-6045777724 and made a direct connection to the 2013 chain split. As written there, I would welcome concrete technical arguments in favor of an alternative design. I hope we can reach consensus before more quality regressions are introduced into the codebase without a proper design goal.
purpleKarrot commented 2026-10-09 14:50:36 +00:00 (Migrated from github.com)

@l0rinc, a 👎 is not what I consider a concrete technical argument.

@l0rinc, a 👎 is not what I consider a concrete technical argument.
alexanderwiederin commented 2026-10-09 20:56:18 +00:00 (Migrated from github.com)

What is the most catastrophic outcome we want to avoid?

I would suggest it's a runtime error influencing the consensus verdict. I agree with @purpleKarrot and @maflcko's earlier points that the current design still leaves room for this when results are flattened into a boolean, e.g. bool ok{res && res->IsValid()}, where a fatal error silently becomes "invalid".

What is the most catastrophic outcome we want to avoid? I would suggest it's a runtime error influencing the consensus verdict. I agree with @purpleKarrot and @maflcko's earlier points that the current design still leaves room for this when results are flattened into a boolean, e.g. `bool ok{res && res->IsValid()}`, where a fatal error silently becomes "invalid".
arejula27 commented 2026-10-10 12:44:13 +00:00 (Migrated from github.com)

@purpleKarrot I only meant to support the technical arguments already made in this thread, but I have looked into your objections and here is my reply.

I was not familiar with BIP50, but I took a look at the v0.7.2 code: CDB::Read returned false both for a missing key and for a BDB lock exhaustion, so FetchInputs reported a missing input and the block was marked invalid. The runtime error went through the same channel as the validation result.

I do not think this example shows a problem with result-style error handling. The cause was that a runtime error and a validation result could not be told apart, not the mechanism used to return them. Today the coin lookup path is protected by CCoinsViewErrorCatcher. However, M_ERROR still keeps both outcomes in the same object and relies on every caller checking IsError(). This PR separates invalid blocks from runtime errors even further, by giving each its own type.

As @alexanderwiederin said, some callers still flatten the result into a bool, but none of them affect a consensus verdict. Where it matters, invalid blocks and runtime errors are already told apart: only invalid blocks are marked as such and only their peers are punished. The cases that flatten the result are in RPC, mining, the C API, or the block import loop, where it only updates a counter and a queue (LoadExternalBlockFile, his example).

The microbenchmarks by optout21, reproduced by yuvicc, show no performance cost for util::Expected compared to throwing. On top of that, the error flow stays visible in each function signature, which makes it easier to follow and to maintain, as optout21, hodlinator, l0rinc and I also pointed out earlier in this thread.

I understand your objection is really about the long-term shape of error handling in consensus code (#35904, #36101), but I do not think this PR needs to wait for that. That is a big (and controversial) decision that needs its own discussion, and this PR does not depend on it or commit to any direction. It only fixes a problem whose motivation you agreed with in your first comment, and there is no simple alternative to this PR (as mentioned in #35904, it would require a complex refactor as it not even decide that is the direction fo core). If a different approach is chosen in the future, changing this code then will take no more effort than changing the code as it is today. I think the net impact of this PR is positive in the short term, and neutral in case it is decided to change the approach in the future.

@purpleKarrot I only meant to support the technical arguments already made in this thread, but I have looked into your objections and here is my reply. I was not familiar with BIP50, but I took a look at the v0.7.2 code: [`CDB::Read`](https://github.com/bitcoin/bitcoin/blob/v0.7.2/src/db.h#L115-L146) returned `false` both for a missing key and for a BDB lock exhaustion, so [`FetchInputs`](https://github.com/bitcoin/bitcoin/blob/v0.7.2/src/main.cpp#L1151-L1154) reported a missing input and the block was [marked invalid](https://github.com/bitcoin/bitcoin/blob/v0.7.2/src/main.cpp#L1619-L1624). The runtime error went through the same channel as the validation result. I do not think this example shows a problem with result-style error handling. The cause was that a runtime error and a validation result could not be told apart, not the mechanism used to return them. Today the coin lookup path is protected by `CCoinsViewErrorCatcher`. However, `M_ERROR` still keeps both outcomes in the same object and relies on every caller checking `IsError()`. This PR separates invalid blocks from runtime errors even further, by giving each its own type. As @alexanderwiederin said, some callers still flatten the result into a bool, but none of them affect a consensus verdict. Where it matters, invalid blocks and runtime errors are already told apart: only invalid blocks are marked as such and only their peers are punished. The cases that flatten the result are in RPC, mining, the C API, or the block import loop, where it only updates a counter and a queue (LoadExternalBlockFile, his example). The microbenchmarks by [optout21](https://github.com/bitcoin/bitcoin/pull/35646#issuecomment-5831231696), reproduced by [yuvicc](https://github.com/bitcoin/bitcoin/pull/35646#issuecomment-5884202555), show no performance cost for `util::Expected` compared to throwing. On top of that, the error flow stays visible in each function signature, which makes it easier to follow and to maintain, as [optout21](https://github.com/bitcoin/bitcoin/pull/35646#issuecomment-5828145495), [hodlinator](https://github.com/bitcoin/bitcoin/pull/35646#issuecomment-5819268467), [l0rinc](https://github.com/bitcoin/bitcoin/pull/35646#issuecomment-5801858626) and I also pointed out earlier in this thread. I understand your objection is really about the long-term shape of error handling in consensus code (#35904, #36101), but I do not think this PR needs to wait for that. That is a big (and controversial) decision that needs its own discussion, and this PR does not depend on it or commit to any direction. It only fixes a problem whose motivation you agreed with in [your first comment](https://github.com/bitcoin/bitcoin/pull/35646#issuecomment-5801502875), and there is no simple alternative to this PR (as mentioned in #35904, it would require a complex refactor as it not even decide that is the direction fo core). If a different approach is chosen in the future, changing this code then will take no more effort than changing the code as it is today. I think the net impact of this PR is positive in the short term, and neutral in case it is decided to change the approach in the future.
alexanderwiederin commented 2026-10-10 15:00:25 +00:00 (Migrated from github.com)

Thanks @arejula27, agreed that none of the current flattening sites affect the verdict.

My point is a bit stronger though: that property currently holds because reviewers checked each site, not because the interface enforces it.

Thanks @arejula27, agreed that none of the current flattening sites affect the verdict. My point is a bit stronger though: that property currently holds because reviewers checked each site, not because the interface enforces it.
alexanderwiederin commented 2026-10-12 07:30:37 +00:00 (Migrated from github.com)

I think #35646 and #36101 agree more than it seems: both say an invalid block is a result, not an error, and the 2013 split illustrates the failure both are guarding against. The disagreement for this PR is the mechanism for fatal errors.

I would suggest settling the mechanism discussion in #36101, which gives the project a consistent direction long term.

I think #35646 and #36101 agree more than it seems: both say an invalid block is a result, not an error, and the 2013 split illustrates the failure both are guarding against. The disagreement for this PR is the mechanism for fatal errors. I would suggest settling the mechanism discussion in #36101, which gives the project a consistent direction long term.
optout21 (Migrated from github.com) reviewed 2026-10-21 11:27:19 +00:00
optout21 (Migrated from github.com) left a comment

I've done another round of review (7a6ced08c6), looks good. I was close to a-c-k-ing, but I found 2-3 potential behavior changes, and several nits. Happy to re-review once those are addressed.

I've done another round of review (7a6ced08c60607cbe8c3d15e9d8859e891e763f6), looks good. I was close to a-c-k-ing, but I found 2-3 potential behavior changes, and several nits. Happy to re-review once those are addressed.
optout21 (Migrated from github.com) commented 2026-10-21 09:52:43 +00:00

50b8ed8 kernel: add FatalError type and tests:

Include hygiene: Moving the implementation to the .cpp file could save an include here (util/translation.h).

> [50b8ed8](https://github.com/bitcoin/bitcoin/pull/35646/changes/50b8ed8bbfbe18de210659c48d8f259f6b197466) _kernel: add FatalError type and tests_: Include hygiene: Moving the implementation to the .cpp file could save an include here (`util/translation.h`).
optout21 (Migrated from github.com) commented 2026-10-21 11:16:29 +00:00

f529ce0 refactor: Make ProcessNewBlock() use FatalError type:

Are we silently introducing new validation reason strings?

> [f529ce0](https://github.com/bitcoin/bitcoin/pull/35646/changes/f529ce0d9230d15779ef2043405290b0d3e2d343) _refactor: Make ProcessNewBlock() use FatalError type_: Are we silently introducing new validation reason strings?
optout21 (Migrated from github.com) commented 2026-10-21 09:59:44 +00:00

3e6d69a refactor: Make BlockManager use FatalError type:

Nit: Reverse alphabetical order.

> [3e6d69a](https://github.com/bitcoin/bitcoin/pull/35646/changes/3e6d69ad7ab474238570e7232b172ef628bca653) _refactor: Make BlockManager use FatalError type_: Nit: Reverse alphabetical order.
optout21 (Migrated from github.com) commented 2026-10-21 11:12:35 +00:00

b0654f1 refactor: Make PreciousBlock() use FatalError type:

Unrelated change, omit it.

> [b0654f1](https://github.com/bitcoin/bitcoin/pull/35646/changes/b0654f1fd7e42d9d87eaefd2b576c49b8e9ec8b2) _refactor: Make PreciousBlock() use FatalError type_: Unrelated change, omit it.
optout21 (Migrated from github.com) commented 2026-10-21 10:22:27 +00:00

df90b0e refactor: Make ConnectBlock() use FatalError type:

For robustness (against future changes) return state would be more appropriate here. If it's still Valid, it is the same as {}. If it's not Valid, it should have been checked already. If it's not valid and it has not been checked, that's a bug, and the value should not be swallowed.
Applies for all the return {} lines below.

> [df90b0e](https://github.com/bitcoin/bitcoin/pull/35646/changes/df90b0e70a5f6c13d9462eccb33f680a0cb3edea) _refactor: Make ConnectBlock() use FatalError type_: For robustness (against future changes) `return state` would be more appropriate here. If it's still Valid, it is the same as `{}`. If it's not Valid, it should have been checked already. If it's not valid and it has not been checked, that's a bug, and the value should not be swallowed. Applies for all the `return {}` lines below.
optout21 (Migrated from github.com) commented 2026-10-21 10:06:29 +00:00

5382efd refactor: Make FlushStateToDisk() use FatalError type:

Nit: this-> could be dropped in the changed line.

> [5382efd](https://github.com/bitcoin/bitcoin/pull/35646/changes/5382efd0192734292e1bf4b40c41a71ecf5c44e6) _refactor: Make FlushStateToDisk() use FatalError type_: Nit: `this->` could be dropped in the changed line.
optout21 (Migrated from github.com) commented 2026-10-21 10:06:36 +00:00

5382efd refactor: Make FlushStateToDisk() use FatalError type:

Nit: this-> could be dropped in the changed line.

> [5382efd](https://github.com/bitcoin/bitcoin/pull/35646/changes/5382efd0192734292e1bf4b40c41a71ecf5c44e6) _refactor: Make FlushStateToDisk() use FatalError type_: Nit: `this->` could be dropped in the changed line.
optout21 (Migrated from github.com) commented 2026-10-21 10:56:55 +00:00

598c4f1 refactor: Make ConnectTip() use FatalError type:

Behavior change: previously BlockChecked was signaled upon Error, now it isn't. Should be checked.

> [598c4f1](https://github.com/bitcoin/bitcoin/pull/35646/changes/598c4f19acfcf27654855312afb193b9ef758781) _refactor: Make ConnectTip() use FatalError type_: Behavior change: previously `BlockChecked` was signaled upon `Error`, now it isn't. Should be checked.
optout21 (Migrated from github.com) commented 2026-10-21 11:01:19 +00:00

50449d2 refactor: Make DisconnectTip() use FatalError type:

This error branch should return (return false), to prevent falling through to the Invalid case, which also does a FatalError.

> [50449d2](https://github.com/bitcoin/bitcoin/pull/35646/changes/50449d2d238b1f715a7f7d853480d9ebf9520157) _refactor: Make DisconnectTip() use FatalError type_: This error branch should return (`return false`), to prevent falling through to the Invalid case, which also does a `FatalError`.
optout21 (Migrated from github.com) commented 2026-10-21 10:51:52 +00:00

598c4f1 refactor: Make ConnectTip() use FatalError type:

Important! state has to be set to Error here before returning false.

> [598c4f1](https://github.com/bitcoin/bitcoin/pull/35646/changes/598c4f19acfcf27654855312afb193b9ef758781) _refactor: Make ConnectTip() use FatalError type_: Important! `state` has to be set to `Error` here before returning `false`.
optout21 (Migrated from github.com) commented 2026-10-21 11:03:29 +00:00

50449d2 refactor: Make DisconnectTip() use FatalError type:

Here an Error can cause a false return with a valid state!

> [50449d2](https://github.com/bitcoin/bitcoin/pull/35646/changes/50449d2d238b1f715a7f7d853480d9ebf9520157) _refactor: Make DisconnectTip() use FatalError type_: Here an Error can cause a `false` return with a valid `state`!
optout21 (Migrated from github.com) commented 2026-10-21 10:19:41 +00:00

df90b0e refactor: Make ConnectBlock() use FatalError type:

Nit: return std::move(*res);

> [df90b0e](https://github.com/bitcoin/bitcoin/pull/35646/changes/df90b0e70a5f6c13d9462eccb33f680a0cb3edea) _refactor: Make ConnectBlock() use FatalError type_: Nit: `return std::move(*res);`
optout21 (Migrated from github.com) commented 2026-10-21 10:16:40 +00:00

df90b0e refactor: Make ConnectBlock() use FatalError type:

Note: state is not used from here on, so this could be deleted. In fact, the state local variable could be moved inside the for loop to reduce its scope.

> [df90b0e](https://github.com/bitcoin/bitcoin/pull/35646/changes/df90b0e70a5f6c13d9462eccb33f680a0cb3edea) _refactor: Make ConnectBlock() use FatalError type_: Note: `state` is not used from here on, so this could be deleted. In fact, the `state` local variable could be moved inside the `for` loop to reduce its scope.
Lines 407-409
optout21 (Migrated from github.com) commented 2026-10-21 10:41:25 +00:00

7605fab refactor: Make TestBlockValidity() use FatalError type:

In the current version there is not way to trigger returning a FatalError. ConnectBlock() is called with fJustCheck=true, which skips the merkle/witness checks that report corruption and skips writing undo data. I suggest changing the comment accordingly (but keeping the util::Expected return type).

> [7605fab](https://github.com/bitcoin/bitcoin/pull/35646/changes/7605fabf62be8d059acf8fca1cf2a95bffe7e944) _refactor: Make TestBlockValidity() use FatalError type_: In the current version there is not way to trigger returning a `FatalError`. `ConnectBlock()` is called with `fJustCheck=true`, which skips the merkle/witness checks that report corruption and skips writing undo data. I suggest changing the comment accordingly (but keeping the `util::Expected` return type).
optout21 (Migrated from github.com) commented 2026-10-21 11:15:05 +00:00

f529ce0 refactor: Make ProcessNewBlock() use FatalError type:

Why not [[nodiscard]] here as on other methods? Also, the doc was not updated.

> [f529ce0](https://github.com/bitcoin/bitcoin/pull/35646/changes/f529ce0d9230d15779ef2043405290b0d3e2d343) _refactor: Make ProcessNewBlock() use FatalError type_: Why not `[[nodiscard]]` here as on other methods? Also, the doc was not updated.
yuvicc (Migrated from github.com) reviewed 2026-11-03 05:45:07 +00:00
yuvicc (Migrated from github.com) commented 2026-11-03 05:45:07 +00:00

Correct, nice catch. I think reason should carry existing values (e.g. inconclusive) and debug should be carrying extra details?

Correct, nice catch. I think `reason` should carry existing values (e.g. `inconclusive`) and `debug` should be carrying extra details?
yuvicc commented 2026-11-03 08:24:59 +00:00 (Migrated from github.com)

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

  • Added FatalError::RaiseFlush(). After the rebase, master's 12f691cf28 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](https://github.com/bitcoin/bitcoin/pull/35646#di
  • The DisconnectTip() fatal-error branch now returns instead of falling through to a second FatalError
    ([comment](https://github.com/bitcoin/bitcoin/pull/35646#di
  • 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`
Rebased onto master (ddea919649) and addressed review comments from @optout21. - Added `FatalError::RaiseFlush()`. After the rebase, master's 12f691cf28 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](https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4335391503)). - Fixed some nits [comment](https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4335454700), [comment](https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4335515712) & [comment](https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4335516669). - `ConnectBlock()` now returns `state` instead of `{}` on success paths ([comment](https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4335661713)). - Used `return std::move(*res);` ([comment](https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4335637839)). - Removed the unused `state = *res;` in `VerifyDB()` and moved `state` into the loop ([comment](https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4335610721)). - Updated the `TestBlockValidity()` doc to say a `FatalError` is currently never returned ([comment](https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4335824207)). - `ActivateBestChainStep()` now sets the Error state before returning `false` ([comment](https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4335912176)). - Kept `BlockChecked` firing in the ConnectTip commit and moved its removal to the `ProcessNewBlock()` commit, where it is documented ([comment](https://github.com/bitcoin/bitcoin/pull/35646#di - The `DisconnectTip()` fatal-error branch now returns instead of falling through to a second `FatalError` ([comment](https://github.com/bitcoin/bitcoin/pull/35646#di - `InvalidateBlock()` now sets the Error state instead of rlid state([comment](https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4336010682)). - Dropped the unrelated `rpc/register.h` include move - Added `[[nodiscard]]` to `ProcessNewBlock()` and updated([comment](https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4336111743)). - No new reason strings: fatal errors now report `reason = essage in `debug`
optout21 (Migrated from github.com) reviewed 2026-11-05 12:21:48 +00:00
optout21 (Migrated from github.com) left a comment

crACK ebe01e1c00

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

crACK ebe01e1c00fb9ceee873c8b4e182273392d1f405 Continued the code review. I have not identified any serious issues, left 2 non-blocking comments. Thanks for incorporating my earlier comments!
Lines 191-193
optout21 (Migrated from github.com) commented 2026-11-05 12:12:52 +00:00

cea4ccb refactor: Make ProcessNewBlock() use FatalError type:

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

> [cea4ccb](https://github.com/bitcoin/bitcoin/pull/35646/changes/cea4ccb19c7619a72c1e82239ad2ebb3abec239d) _refactor: Make ProcessNewBlock() use FatalError type_: In case of error, `res.error().message()` could be included in the error message.
optout21 (Migrated from github.com) commented 2026-11-05 12:13:56 +00:00

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.

> [65d1929](https://github.com/bitcoin/bitcoin/pull/35646/changes/65d192966f54cf3ec6da107dfab5c7027ef3063b) _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 commented 2026-11-06 00:28:28 +00:00 (Migrated from github.com)

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

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!35646
No description provided.