refactor: Change some validation.cpp methods to return BlockValidationState #35570

Open
optout21 wants to merge 12 commits from 2605-validation-state-return into master AGit
optout21 commented 2026-06-20 06:15:23 +00:00 (Migrated from github.com)

Summary. Refactor validation result to be a return value instead of an output parameter in several validation.cpp methods.

Motivation. The benefits of the change are:

  • Exclude the potentially inconsistent case when the bool return value and the returned state are inconsistent
  • Exclude the ambiguity whether the passed in value of state is used or not (not obvious in chained calls)
  • Remove the possibility of unintuitive interaction between subsequent calls with the same state. In case of a validation error, a failure reason is set if the state was valid, but not if it was already invalid.
  • Slightly simpler: It's more evident which is the result; one less parameters.

This has grown out from #33856, mentioned in comment here and here.

Details. Many methods follow the scheme where the validation state is returned in an output parameter (BlockValidationState& state), and and additional bool return value indicating success. In success case the convention is that state.IsValid() and the return value are both true. After the change there is only a BlockValidationState return value, which is either success (state.IsValid() == true), or an invalid/error case.

This change is a highly localized refactor, but touching a sensitive file.

Relevant methods called by ProcessNewBlockHeaders and AcceptBlock (directly and indirectly) are touched.

Changes are separated into commits by touched methods, ordered by bottom-to-top in the call hierarchy.

**Summary**. Refactor validation result to be a return value instead of an output parameter in several `validation.cpp` methods. **Motivation**. The benefits of the change are: - Exclude the potentially inconsistent case when the bool return value and the returned `state` are inconsistent - Exclude the ambiguity whether the passed in value of state is used or not (not obvious in chained calls) - Remove the possibility of unintuitive interaction between subsequent calls with the same state. In case of a validation error, a failure reason is set if the state was valid, but not if it was already invalid. - Slightly simpler: It's more evident which is the result; one less parameters. This has grown out from #33856, mentioned in [comment here](https://github.com/bitcoin/bitcoin/pull/33856#pullrequestreview-4276791829) and [here](https://github.com/bitcoin/bitcoin/pull/33856#issuecomment-4477751949). **Details**. Many methods follow the scheme where the validation state is returned in an output parameter (`BlockValidationState& state`), and and additional `bool` return value indicating success. In success case the convention is that `state.IsValid()` and the return value are both true. After the change there is only a `BlockValidationState` return value, which is either success (`state.IsValid() == true`), or an invalid/error case. This change is a highly localized refactor, but touching a sensitive file. Relevant methods called by `ProcessNewBlockHeaders` and `AcceptBlock` (directly and indirectly) are touched. Changes are separated into commits by touched methods, ordered by bottom-to-top in the call hierarchy.
DrahtBot commented 2026-06-20 06:15:31 +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
Concept ACK w0xlt, purpleKarrot, stringintech, yuvicc, nervana21, enochaz
Stale ACK 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:

  • #36858 (refactor: break the blockstorage/validation circular dependency by pzafonte)
  • #36856 (kernel: add manual pruning by pzafonte)
  • #36792 (validation: avoid partial override of non-valid validation state by optout21)
  • #36782 (doc: fix comments referring to nonexistent functions by fanquake)
  • #36738 (refactor: move block writes and pruning into BlockManager by pzafonte)
  • #36326 (kernel: Use typed errors for fatal and flush error notifications by arejula27)
  • #36318 (validation: Ensure Invalid ValidationState has result by optout21)
  • #36109 (test: fix coinbases built on arbitrary parents by l0rinc)
  • #36066 (validation: Separate check-only version of ConnectBlock by optout21)
  • #35906 (First steps towards a stateless, side-effect free validation library by purpleKarrot)
  • #35793 (Implement BIP 54 (Consensus Cleanup) without mainnet activation by darosior)
  • #35751 (validation: use parallel input prevout fetching in TestBlockValidity by andrewtoth)
  • #35557 (kernel, validation: Add btck_chainstate_manager_set_clock_time by ryanofsky)
  • #35502 (refactor: extract per-message helpers from ProcessMessage (move-only) by w0xlt)

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/bench/duplicate_inputs.cpp: CheckBlock(block, chainparams.GetConsensus(), false, false)
  • src/test/baseindex_tests.cpp: AcceptBlock(new_block, &new_block_index, true, nullptr, nullptr, true)
  • src/validation.cpp: AcceptBlock(pblock, nullptr, true, dbp, nullptr, true)
  • src/validation.cpp: AcceptBlock(pblockrecursive, nullptr, true, &it->second, nullptr, true)

2026-11-24 22:47:15

<!--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/35570 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/35570.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/35570#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 | | ---- | --------- | | Concept ACK | [w0xlt](https://github.com/bitcoin/bitcoin/pull/35570#issuecomment-4760189210), [purpleKarrot](https://github.com/bitcoin/bitcoin/pull/35570#issuecomment-4765343006), [stringintech](https://github.com/bitcoin/bitcoin/pull/35570#issuecomment-4783419874), [yuvicc](https://github.com/bitcoin/bitcoin/pull/35570#issuecomment-4845903603), [nervana21](https://github.com/bitcoin/bitcoin/pull/35570#issuecomment-4927519609), [enochaz](https://github.com/bitcoin/bitcoin/pull/35570#pullrequestreview-5277047699) | | Stale ACK | [arejula27](https://github.com/bitcoin/bitcoin/pull/35570#issuecomment-6672707508) | 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: * [#36858](https://github.com/bitcoin/bitcoin/pull/36858) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36858.svg"></sub> (refactor: break the blockstorage/validation circular dependency by pzafonte) * [#36856](https://github.com/bitcoin/bitcoin/pull/36856) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36856.svg"></sub> (kernel: add manual pruning by pzafonte) * [#36792](https://github.com/bitcoin/bitcoin/pull/36792) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36792.svg"></sub> (validation: avoid partial override of non-valid validation state by optout21) * [#36782](https://github.com/bitcoin/bitcoin/pull/36782) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36782.svg"></sub> (doc: fix comments referring to nonexistent functions by fanquake) * [#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) * [#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) * [#36109](https://github.com/bitcoin/bitcoin/pull/36109) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36109.svg"></sub> (test: fix coinbases built on arbitrary parents by l0rinc) * [#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) * [#35906](https://github.com/bitcoin/bitcoin/pull/35906) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35906.svg"></sub> (First steps towards a stateless, side-effect free validation library by purpleKarrot) * [#35793](https://github.com/bitcoin/bitcoin/pull/35793) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35793.svg"></sub> (Implement BIP 54 (Consensus Cleanup) without mainnet activation by darosior) * [#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) * [#35557](https://github.com/bitcoin/bitcoin/pull/35557) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35557.svg"></sub> (kernel, validation: Add btck_chainstate_manager_set_clock_time by ryanofsky) * [#35502](https://github.com/bitcoin/bitcoin/pull/35502) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35502.svg"></sub> (refactor: extract per-message helpers from ProcessMessage (move-only) by w0xlt) 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/bench/duplicate_inputs.cpp`: `CheckBlock(block, chainparams.GetConsensus(), false, false)` - `src/test/baseindex_tests.cpp`: `AcceptBlock(new_block, &new_block_index, true, nullptr, nullptr, true)` - `src/validation.cpp`: `AcceptBlock(pblock, nullptr, true, dbp, nullptr, true)` - `src/validation.cpp`: `AcceptBlock(pblockrecursive, nullptr, true, &it->second, nullptr, true)` <sup>2026-11-24 22:47:15</sup>
DrahtBot commented 2026-06-20 07:12:31 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task tidy: https://github.com/bitcoin/bitcoin/actions/runs/27862735029/job/82461396003
LLM reason (✨ experimental): CI failed because clang-tidy reported readability-const-return-type errors in src/validation.cpp (e.g., static const BlockValidationState ... return types), causing the clang-tidy step to exit with failure.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `tidy`: https://github.com/bitcoin/bitcoin/actions/runs/27862735029/job/82461396003</sub> <sub>LLM reason (✨ experimental): CI failed because clang-tidy reported `readability-const-return-type` errors in `src/validation.cpp` (e.g., `static const BlockValidationState ...` return types), causing the clang-tidy step to exit with failure.</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>
optout21 commented 2026-06-20 13:30:31 +00:00 (Migrated from github.com)

While working on this PR, one instance was identified where the invariant return_value == state.IsValid() was not guaranteed:
At the end of ChainstateManager::AcceptBlock(), FlushStateToDisk() was called, and its return value discarded, but it could have a side effect in state. In turn, this could make a difference in ChainstateManager::LoadExternalBlockFile().

Options to resolve this:

A. Since the return value is ignored, ignore the state returned as well.
B. Handle the error from FlushStateToDisk(), and pass the error.

The ignoring of flush result (A.) is also proposed in #29700 (cc: @ryanofsky ).

The minor behavior-change could be also omitted from this PR, limiting strictly to a no-behavior-change refactor:

  • Do not change AcceptBlock, keep the dual value & state return values
  • Restrict the scope of the PR and drop all commits 5-13
  • Defer this PR until this issue is solved separately first
While working on this PR, one instance was identified where the invariant `return_value == state.IsValid()` was not guaranteed: At the end of `ChainstateManager::AcceptBlock()`, `FlushStateToDisk()` was called, and its return value discarded, but it could have a side effect in `state`. In turn, this could make a difference in `ChainstateManager::LoadExternalBlockFile()`. Options to resolve this: A. Since the return value is ignored, ignore the `state` returned as well. B. Handle the error from `FlushStateToDisk()`, and pass the error. The ignoring of flush result (A.) is also proposed in #29700 (cc: @ryanofsky ). The minor behavior-change could be also omitted from this PR, limiting strictly to a no-behavior-change refactor: - Do not change `AcceptBlock`, keep the dual value & state return values - Restrict the scope of the PR and drop all commits 5-13 - Defer this PR until this issue is solved separately first
w0xlt commented 2026-06-20 22:36:15 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
purpleKarrot commented 2026-06-22 05:59:23 +00:00 (Migrated from github.com)

Concept ACK. Preferring the return value over output parameters is a useful and I would say necessary improment.

But could we avoid using BlockValidationState as a state machine, or mutable local variable? That means, instead of code like:

{
  BlockValidationState state;
  if (...) {
    state.Invalid(...);
  }
  return state;
}

I would prefer something like:

{
  if (...) {
    return BlockValidationState::Invalid(...);
  }
  return BlockValidationState::Valid();
}
Concept ACK. Preferring the return value over output parameters is a useful and I would say *necessary* improment. But could we avoid using `BlockValidationState` as a state machine, or mutable local variable? That means, instead of code like: ```cpp { BlockValidationState state; if (...) { state.Invalid(...); } return state; } ``` I would prefer something like: ```cpp { if (...) { return BlockValidationState::Invalid(...); } return BlockValidationState::Valid(); } ```
optout21 commented 2026-06-22 06:16:06 +00:00 (Migrated from github.com)

could we avoid using BlockValidationState as a state machine, or mutable local variable

I fully agree, shorter-scoped variables mean less chance of potential interplay between calls, less complexity. I did change this in several places, but not everywhere. In some places there was a real chance for interaction between subsequent calls (e.g. error reason is set conditional of already set value), and I kept it to be safe (w.r.t. behavior changes). But I should review and change it more aggressively.

> could we avoid using `BlockValidationState` as a state machine, or mutable local variable I fully agree, shorter-scoped variables mean less chance of potential interplay between calls, less complexity. I did change this in several places, but not everywhere. In some places there was a real chance for interaction between subsequent calls (e.g. error reason is set conditional of already set value), and I kept it to be safe (w.r.t. behavior changes). But I should review and change it more aggressively.
optout21 commented 2026-06-22 16:40:28 +00:00 (Migrated from github.com)

Applied some improvements:

  • Got rid of method-wide BlockValidationState state variables, use only restricted scope state variables, optimally in "if (const auto state = Xxx; !state.IsValid())" construct. Thanks @purpleKarrot for the emphasis!
  • Added InvalidState static helper to create invalid BlockValidationState instance. In error branches, instead of 3 statements (declaration, setting, and return) now one is enough (return&construction). Added as new first commit.
Applied some improvements: - Got rid of method-wide `BlockValidationState state` variables, use only restricted scope state variables, optimally in `"if (const auto state = Xxx; !state.IsValid())"` construct. Thanks @purpleKarrot for the emphasis! - Added `InvalidState` static helper to create invalid `BlockValidationState` instance. In error branches, instead of 3 statements (declaration, setting, and return) now one is enough (return&construction). Added as new first commit.
arejula27 (Migrated from github.com) reviewed 2026-06-23 18:11:07 +00:00
arejula27 (Migrated from github.com) left a comment

concept ACK 8207ac1bb79f76c9005e8e2d695b725539b3c5c0

Looks good overall. I'd push this one step further and use util::Expected here, it's a natural fit and follows the PR's own motivation. The PR already cleans up the bool + state out-param inconsistency by making state the return value; util::Expected<T, BlockValidationState> does the same thing but at the type level instead of by convention. Success and failure become distinct alternatives of the type.

Concretely, a bare BlockValidationState still carries all three modes (M_VALID/M_INVALID/M_ERROR) in the return value even though M_VALID is now redundant with "the call succeeded". With util::Expected that mode collapses into has_value() and is no longer stored, the failure modes move to the error channel, and out-params like ppindex fold into the success channel. util/result.h also explicitly steers low-level functions toward util::Expected.

// pindex folded into the success channel
[[nodiscard]] util::Expected<CBlockIndex*, BlockValidationState> AcceptBlockHeader(
    const CBlockHeader& block, bool min_pow_checked);

auto res = AcceptBlockHeader(header, /*min_pow_checked=*/true);
if (!res) {
    if (res.error().IsInvalid()) MaybePunishNodeForBlock(...); // peer's fault
    return util::Unexpected{std::move(res).error()};
}
CBlockIndex* pindex = res.value(); // only reachable on success

One open question (happy to leave it as discussion): where does M_INVALID fit best? Above I put it in the error channel next to M_ERROR, but it's arguably a successful, expected outcome of validation, the function did run and produced a verdict ("this block is invalid"), whereas M_ERROR is a genuine runtime failure that prevented producing a result. So an alternative split would keep Valid/Invalid in the value channel and reserve the error channel for runtime errors only. I don't have a strong preference.

concept ACK 8207ac1bb79f76c9005e8e2d695b725539b3c5c0 Looks good overall. I'd push this one step further and use `util::Expected` here, it's a natural fit and follows the PR's own motivation. The PR already cleans up the `bool` + `state` out-param inconsistency by making state the return value; `util::Expected<T, BlockValidationState>` does the same thing but at the type level instead of by convention. Success and failure become distinct alternatives of the type. Concretely, a bare `BlockValidationState` still carries all three modes (`M_VALID`/`M_INVALID`/`M_ERROR`) in the return value even though `M_VALID` is now redundant with "the call succeeded". With `util::Expected` that mode collapses into `has_value()` and is no longer stored, the failure modes move to the error channel, and out-params like `ppindex` fold into the success channel. `util/result.h` also explicitly steers low-level functions toward `util::Expected`. ```cpp // pindex folded into the success channel [[nodiscard]] util::Expected<CBlockIndex*, BlockValidationState> AcceptBlockHeader( const CBlockHeader& block, bool min_pow_checked); auto res = AcceptBlockHeader(header, /*min_pow_checked=*/true); if (!res) { if (res.error().IsInvalid()) MaybePunishNodeForBlock(...); // peer's fault return util::Unexpected{std::move(res).error()}; } CBlockIndex* pindex = res.value(); // only reachable on success ``` One open question (happy to leave it as discussion): where does `M_INVALID` fit best? Above I put it in the error channel next to `M_ERROR`, but it's arguably a *successful, expected* outcome of validation, the function did run and produced a verdict ("this block is invalid"), whereas `M_ERROR` is a genuine runtime failure that prevented producing a result. So an alternative split would keep Valid/Invalid in the value channel and reserve the error channel for runtime errors only. I don't have a strong preference.
arejula27 (Migrated from github.com) commented 2026-06-23 16:36:01 +00:00

On failure, IsInvalid() is false
Would not be "true"?

> On failure, IsInvalid() is false Would not be "true"?
stringintech commented 2026-06-23 20:59:42 +00:00 (Migrated from github.com)

Concept ACK

One open question (happy to leave it as discussion): where does M_INVALID fit best? Above I put it in the error channel next to M_ERROR, but it's arguably a successful, expected outcome of validation, the function did run and produced a verdict ("this block is invalid"), whereas M_ERROR is a genuine runtime failure that prevented producing a result. So an alternative split would keep Valid/Invalid in the value channel and reserve the error channel for runtime errors only. I don't have a strong preference.

There is a thread in #33856 where this was also brought up. I included a POC in the last comment of that thread which keeps the value channel for M_VALID/M_INVALID and the error channel for M_ERROR, which I think makes more sense as you're suggesting: M_INVALID is not an operation failure.

In general, I think stripping the runtime failure from BlockValidationState could also leave the door open for preferring exceptions over error values in the future. That said, this should be orthogonal to this PR and could be addressed in a follow-up if desired.

Concept ACK > One open question (happy to leave it as discussion): where does M_INVALID fit best? Above I put it in the error channel next to M_ERROR, but it's arguably a successful, expected outcome of validation, the function did run and produced a verdict ("this block is invalid"), whereas M_ERROR is a genuine runtime failure that prevented producing a result. So an alternative split would keep Valid/Invalid in the value channel and reserve the error channel for runtime errors only. I don't have a strong preference. There is a thread in #33856 where this was also brought up. I included a POC in the [last comment](https://github.com/bitcoin/bitcoin/pull/33856#discussion_r3068580118) of that thread which keeps the value channel for `M_VALID`/`M_INVALID` and the error channel for `M_ERROR`, which I think makes more sense as you're suggesting: `M_INVALID` is not an operation failure. In general, I think stripping the runtime failure from `BlockValidationState` could also leave the door open for preferring exceptions over error values in the future. That said, this should be orthogonal to this PR and could be addressed in a follow-up if desired.
arejula27 commented 2026-06-24 10:36:30 +00:00 (Migrated from github.com)

which I think makes more sense as you're suggesting: M_INVALID is not an operation failure.

I think both approaches are ok, though I slightly prefer util::Expected<CBlockIndex*, BlockValidationError>, an invalid block is an error in the same way a hardware failure causes validation to fail. That said, I understand the distinction behind util::Expected<BlockValidationState, std::string>, where the value represents logical state (valid or not) and the error is something unrelated to the function's logic. I'd accept either.

That said, this should be orthogonal to this PR and could be addressed in a follow-up if desired.

I completely disagree that this is orthogonal to the PR. This is a fundamentally different refactor, it differs not just internals but the API and its callers in a critical section of the code. I don't think it's correct to keep returning state through an value of the BlockValidationState when we already have util::Expected in the codebase for exactly this purpose.

On top of that, I don't think it's a good idea to keep touching this section of the code without a clear long-term direction changes that are purely stylistic or for maintainability, only to refactor everything again later when util::Expected gets introduced. This PR is already proposing a structural change to error handling here, it should go all the way rather than leave a half-finished migration that will need to be revisited.

> which I think makes more sense as you're suggesting: M_INVALID is not an operation failure. I think both approaches are ok, though I slightly prefer `util::Expected<CBlockIndex*, BlockValidationError>`, an invalid block is an error in the same way a hardware failure causes validation to fail. That said, I understand the distinction behind `util::Expected<BlockValidationState, std::string>`, where the value represents logical state (valid or not) and the error is something unrelated to the function's logic. **I'd accept either.** > That said, this should be orthogonal to this PR and could be addressed in a follow-up if desired. I completely disagree that this is orthogonal to the PR. This is a fundamentally different refactor, it differs not just internals but the API and its callers in a critical section of the code. I don't think it's correct to keep returning state through an value of the `BlockValidationState `when we already have `util::Expected` in the codebase for exactly this purpose. On top of that, I don't think it's a good idea to keep touching this section of the code without a clear long-term direction changes that are purely stylistic or for maintainability, only to refactor everything again later when `util::Expected` gets introduced. This PR is already proposing a structural change to error handling here, it should go all the way rather than leave a half-finished migration that will need to be revisited.
stringintech commented 2026-06-24 11:03:10 +00:00 (Migrated from github.com)

I completely disagree that this is orthogonal to the PR. This is a fundamentally different refactor, it differs not just internals but the API and its callers in a critical section of the code. I don't think it's correct to keep returning state through an value of the BlockValidationState when we already have util::Expected in the codebase for exactly this purpose.

The way I see it, the main thing we achieve with the current refactor is the ability to reason about things more locally, by not having to pass state around and absorb it across a chain of operations. This seems like a separate objective from making BlockValidationState no longer absorb runtime errors or changing it to BlockValidationError. Even if reviewers would prefer seeing both goals addressed in a single batch/PR, I think it would be valuable to have a kind of separation between them through distinct commits.

> I completely disagree that this is orthogonal to the PR. This is a fundamentally different refactor, it differs not just internals but the API and its callers in a critical section of the code. I don't think it's correct to keep returning state through an value of the BlockValidationState when we already have util::Expected in the codebase for exactly this purpose. The way I see it, the main thing we achieve with the current refactor is the ability to reason about things more locally, by not having to pass state around and absorb it across a chain of operations. This seems like a separate objective from making `BlockValidationState` no longer absorb runtime errors or changing it to `BlockValidationError`. Even if reviewers would prefer seeing both goals addressed in a single batch/PR, I think it would be valuable to have a kind of separation between them through distinct commits.
arejula27 commented 2026-06-24 14:15:56 +00:00 (Migrated from github.com)

The way I see it, the main thing we achieve with the current refactor is the ability to reason about things more locally, by not having to pass state around and absorb it across a chain of operations

Agree, this is a relevant topic alone to be merged, and my concerns should not be a blocker, however i feel that would be the correct way to implement this and fits inside the PR. I will continue the discussion when more changes or reviews are submitted to not flood the thread

> The way I see it, the main thing we achieve with the current refactor is the ability to reason about things more locally, by not having to pass state around and absorb it across a chain of operations Agree, this is a relevant topic alone to be merged, and **my concerns should not be a blocker**, however i feel that would be the correct way to implement this and fits inside the PR. I will continue the discussion when more changes or reviews are submitted to not flood the thread
optout21 commented 2026-06-25 14:38:43 +00:00 (Migrated from github.com)

@arejula27: very valuable suggestion using util::Expected, I will explore this idea. The current PR doesn't change the content of the BlockValidationState returned, only how it is returned, there is no behavior change (except the special case 9965489e243143fdbba6e8f379e598c92368d45c), the changes in the commits are relatively localized scope. Nonetheless, I will explore the util::Expected suggestion, and apply it, or not (in that case I will mention it as an alternative considered).

Another idea related to this: some methods return only Valid or Invalid, but not Error -- I've documented this in the header comments in a few places for more visibility. This is by convention, and not enforced. Maybe this could be enforced (maybe by the return value used).

@arejula27: very valuable suggestion using `util::Expected`, I will explore this idea. The current PR doesn't change the content of the `BlockValidationState` returned, only how it is returned, there is no behavior change (except the special case 9965489e243143fdbba6e8f379e598c92368d45c), the changes in the commits are relatively localized scope. Nonetheless, I will explore the `util::Expected` suggestion, and apply it, or not (in that case I will mention it as an alternative considered). Another idea related to this: some methods return only Valid or Invalid, but not Error -- I've documented this in the header comments in a few places for more visibility. This is by convention, and not enforced. Maybe this could be enforced (maybe by the return value used).
ryanofsky commented 2026-06-28 21:24:06 +00:00 (Migrated from github.com)

re: https://github.com/bitcoin/bitcoin/pull/35570#issuecomment-4758227624

While working on this PR, one instance was identified where the invariant return_value == state.IsValid() was not guaranteed

Really nice catch. I think it would make sense to open a separate PR to fix this, so this PR can just be a refactoring and not change behavior. One approach could be: 78100ea27d076e9c76f444364dfd8fbaf719fefc

re: https://github.com/bitcoin/bitcoin/pull/35570#issuecomment-4758227624 > While working on this PR, one instance was identified where the invariant `return_value == state.IsValid()` was not guaranteed Really nice catch. I think it would make sense to open a separate PR to fix this, so this PR can just be a refactoring and not change behavior. One approach could be: 78100ea27d076e9c76f444364dfd8fbaf719fefc
optout21 commented 2026-06-29 13:11:19 +00:00 (Migrated from github.com)

Really nice catch. I think it would make sense to open a separate PR to fix this

Thanks, I'll do this. Thanks for the prepared commit as well.

> Really nice catch. I think it would make sense to open a separate PR to fix this Thanks, I'll do this. Thanks for the prepared commit as well.
optout21 commented 2026-06-29 21:48:20 +00:00 (Migrated from github.com)

Update:

  • The single minor behavior-relevant change has been split off into #35621.
  • The commit from there is included in this PR as first commit (rebased on top of #35621); this PR should come only after #35621.
Update: - The single minor behavior-relevant change has been split off into #35621. - The commit from there is included in this PR as first commit (rebased on top of #35621); this PR should come only after #35621.
yuvicc commented 2026-06-30 16:49:01 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
yuvicc commented 2026-07-03 05:13:41 +00:00 (Migrated from github.com)

Following up on the discussion above about util::Expected being the long term refactor, I've opened an RFC #35646 which might be the direction where this could end.

Following up on the discussion above about `util::Expected` being the long term refactor, I've opened an RFC #35646 which might be the direction where this could end.
arejula27 (Migrated from github.com) reviewed 2026-07-04 23:42:50 +00:00
arejula27 (Migrated from github.com) left a comment

re-concept-ACK 014f2774b9
Second pass focused on correctness and the new signatures, nothing significant to flag

re-concept-ACK 014f2774b9 Second pass focused on correctness and the new signatures, nothing significant to flag
arejula27 (Migrated from github.com) commented 2026-07-04 23:36:39 +00:00

nit: could be const (only IsValid() is called), like the fuzz/block.cpp temporaries this PR already made const.

nit: could be const (only IsValid() is called), like the fuzz/block.cpp temporaries this PR already made const.
arejula27 (Migrated from github.com) commented 2026-07-04 23:36:55 +00:00

nit: could be const (only const methods are called on it).

nit: could be const (only const methods are called on it).
arejula27 (Migrated from github.com) commented 2026-07-04 23:35:14 +00:00

nit: state is dead after this line, so create(std::move(state)) avoids copy-constructing the state.

nit: state is dead after this line, so create(std::move(state)) avoids copy-constructing the state.
arejula27 (Migrated from github.com) commented 2026-07-04 23:37:28 +00:00

nit: could be const auto res{...}

nit: could be const auto res{...}
arejula27 (Migrated from github.com) commented 2026-07-04 23:33:40 +00:00

Missing nodiscard, unlike the other converted functions (CheckBlockHeader, CheckMerkleRoot, ContextualCheckBlockHeader)

Missing [[nodiscard]], unlike the other converted functions (CheckBlockHeader, CheckMerkleRoot, ContextualCheckBlockHeader)
arejula27 (Migrated from github.com) commented 2026-07-04 23:34:39 +00:00

Same here: missing nodiscard for consistency with the other converted functions

Same here: missing [[nodiscard]] for consistency with the other converted functions
arejula27 (Migrated from github.com) commented 2026-07-04 23:39:43 +00:00

I miss a comment here about the case.

I would like to know the reason to drop the previous (if (!state.IsValid()) NONFATAL_UNREACHABLE(); return state;), so a hypothetical ConnectBlock that returns true while setting an invalid state would now be reported as Valid.

Intentional as part of the simplification? Is this case not possible anymore?

I miss a comment here about the case. I would like to know the reason to drop the previous `(if (!state.IsValid()) NONFATAL_UNREACHABLE(); return state;)`, so a hypothetical `ConnectBlock ` that returns true while setting an invalid state would now be reported as Valid. Intentional as part of the simplification? Is this case not possible anymore?
optout21 (Migrated from github.com) reviewed 2026-07-06 05:07:17 +00:00
optout21 (Migrated from github.com) left a comment

Applied some (minor) changes following review from @arejula27 -- thanks!

Applied some (minor) changes following review from @arejula27 -- thanks!
optout21 (Migrated from github.com) commented 2026-07-06 05:04:44 +00:00

Done

Done
optout21 (Migrated from github.com) commented 2026-07-06 05:04:52 +00:00

Done

Done
optout21 (Migrated from github.com) commented 2026-07-06 05:04:37 +00:00

Done

Done
optout21 (Migrated from github.com) commented 2026-07-06 05:05:02 +00:00

Done

Done
optout21 (Migrated from github.com) commented 2026-07-06 04:54:35 +00:00

I haven't deemed nodiscard important on all compile-unit-internal methods, but I've added now for consistency.

I haven't deemed `nodiscard` important on all compile-unit-internal methods, but I've added now for consistency.
optout21 (Migrated from github.com) commented 2026-07-06 04:55:17 +00:00

Added (as above)

Added (as above)
optout21 (Migrated from github.com) commented 2026-07-06 04:44:40 +00:00

Indeed. Such checks ensured that the bool and state return values are in-sync, and they became pointless in most places. However, here ConnectBlock still return both bool and state, so the check makes sense. I've put it back in the else branch.

Indeed. Such checks ensured that the bool and state return values are in-sync, and they became pointless in most places. However, here `ConnectBlock` still return both bool and state, so the check makes sense. I've put it back in the `else` branch.
optout21 commented 2026-07-08 04:31:51 +00:00 (Migrated from github.com)

Rebased, following the inclusion of #35621 (first commit dropped, as already in master).

Rebased, following the inclusion of #35621 (first commit dropped, as already in master).
nervana21 commented 2026-07-09 16:49:48 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
DrahtBot commented 2026-07-10 00:53:05 +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).
optout21 commented 2026-07-12 07:07:18 +00:00 (Migrated from github.com)

Rebased, post #34897 (straightforward resolution).

Rebased, post #34897 (straightforward resolution).
DrahtBot commented 2026-08-14 15:41:59 +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).
optout21 commented 2026-08-18 11:03:12 +00:00 (Migrated from github.com)

Rebased to current master. Only tests affected: some removed tests, some straightforward resolutions.
git range-diff e600c4ce022bf1e856cb81ca941310fe177d7eb6...f65361acfae8d5d0d9f525fe7887334f03cedcc3

Rebased to current master. Only tests affected: some removed tests, some straightforward resolutions. `git range-diff e600c4ce022bf1e856cb81ca941310fe177d7eb6...f65361acfae8d5d0d9f525fe7887334f03cedcc3`
arejula27 (Migrated from github.com) reviewed 2026-09-05 15:14:40 +00:00
arejula27 (Migrated from github.com) left a comment

Ack f65361acfae8d5d0d9f525fe7887334f03cedcc3

This PR only changes signatures as the PR description says, no behavioral changes.

Wrote some small comments, none of them are blockers, just suggestions, but I would highly encourage at least fixing the comment/doc error I mentioned in my last review (validation.h:1280, "On failure, IsInvalid() is false" should read "true").

As I mentioned in the inline comments, I think adding both factories would help readers understand the code and make it cleaner.

Also wrote two small tests (arejula27/bitcoin@67a3be1) that guard how each case is reported (valid/invalid/error). Feel free to cherry-pick, copy, edit or omit.

Ack f65361acfae8d5d0d9f525fe7887334f03cedcc3 This PR only changes signatures as the PR description says, no behavioral changes. Wrote some small comments, none of them are blockers, just suggestions, but I would highly encourage at least fixing the comment/doc error I mentioned in my last review (`validation.h:1280`, "On failure,` IsInvalid()` is false" should read "true"). As I mentioned in the inline comments, I think adding both factories would help readers understand the code and make it cleaner. Also wrote two small tests (arejula27/bitcoin@67a3be1) that guard how each case is reported (valid/invalid/error). Feel free to cherry-pick, copy, edit or omit.
arejula27 (Migrated from github.com) commented 2026-09-05 14:51:50 +00:00

nit: could you put this brace a line below, to keep a consistent format with the file (see class ValidationState right above)?

nit: could you put this brace a line below, to keep a consistent format with the file (see class `ValidationState `right above)?
Lines 2151-2154
arejula27 (Migrated from github.com) commented 2026-09-05 14:23:39 +00:00

I only found one other manualError(...)construction, but might still be cleaner to have a factory here too, e.g. BlockValidationState::ErrorState(reject_reason). Then this becomes:

    notifications.fatalError(message);
    return BlockValidationState::ErrorState(message.original);

I only found one other manual` Error(...) `construction, but might still be cleaner to have a factory here too, e.g. `BlockValidationState::ErrorState(reject_reason)`. Then this becomes: ```suggestion notifications.fatalError(message); return BlockValidationState::ErrorState(message.original); ```
arejula27 (Migrated from github.com) commented 2026-09-05 13:40:32 +00:00

I see the default constructor gets a valid state from

enum class ModeState {
    M_VALID,   //!< everything ok
    M_INVALID, //!< network rule violation (DoS value may be set)
    M_ERROR,   //!< run-time error
} m_mode{ModeState::M_VALID};   // <-- in-class initializer

however it would be better for the reader if you also added a factory for the valid state (alongside InvalidState(...)), so the returned state is explicit rather than implicit and independent of the default value of ModeState

I see the default constructor gets a valid state from ``` enum class ModeState { M_VALID, //!< everything ok M_INVALID, //!< network rule violation (DoS value may be set) M_ERROR, //!< run-time error } m_mode{ModeState::M_VALID}; // <-- in-class initializer ``` however it would be better for the reader if you also added a factory for the valid state (alongside InvalidState(...)), so the returned state is explicit rather than implicit and independent of the default value of `ModeState`
arejula27 (Migrated from github.com) commented 2026-09-05 14:44:15 +00:00

nit: I would prefer header_state, not a fan of using verbs in variable names

        BlockValidationState header_state{AcceptBlockHeader(block, &pindex, min_pow_checked)};
nit: I would prefer `header_state`, not a fan of using verbs in variable names ```suggestion BlockValidationState header_state{AcceptBlockHeader(block, &pindex, min_pow_checked)}; ```
optout21 (Migrated from github.com) reviewed 2026-09-08 09:52:40 +00:00
optout21 (Migrated from github.com) left a comment

Thanks for the reviews, @arejula27!
Changes applied -- all minor:

  • Fix error in documentation of ProcessNewBlockHeaders.
  • ProcessNewBlockHeaders: add assert to check that the non-valid case is invalid (and not error).
  • AcceptBlockHeader: add asserts to check that non-valid cases are all invalid (and not error).
  • Minor local variable rename in AcceptBlock
  • Minor formatting change (src/consensus/validation.h)
  • Add ErrorState factory method to the BlockValidationState error class. Added as a separate commit.

git range-diff f65361acfae8d5d0d9f525fe7887334f03cedcc3..58d6d23275067dc284ca13f3d7906ac9aaf7843a

Thanks for the reviews, @arejula27! Changes applied -- all minor: - Fix error in documentation of `ProcessNewBlockHeaders`. - `ProcessNewBlockHeaders`: add assert to check that the non-valid case is invalid (and not error). - `AcceptBlockHeader`: add asserts to check that non-valid cases are all invalid (and not error). - Minor local variable rename in `AcceptBlock` - Minor formatting change (`src/consensus/validation.h`) - Add `ErrorState` factory method to the `BlockValidationState` error class. Added as a separate commit. `git range-diff f65361acfae8d5d0d9f525fe7887334f03cedcc3..58d6d23275067dc284ca13f3d7906ac9aaf7843a`
optout21 (Migrated from github.com) commented 2026-09-08 09:49:49 +00:00

Done.

Done.
Lines 2151-2154
optout21 (Migrated from github.com) commented 2026-09-08 09:49:22 +00:00

Suggestion taken, factory method for Error added. I've also found a second construction instance (in AcceptBlock), both use the factory method now. Added you as co-author.

Suggestion taken, factory method for Error added. I've also found a second construction instance (in `AcceptBlock`), both use the factory method now. Added you as co-author.
optout21 (Migrated from github.com) commented 2026-09-08 09:47:37 +00:00

I think it's intuitive for the state class to initialize to Valid by default. Adding a factory method for the Valid would be an overkill in my view. It's true that BlockValidationState and ValidationState don't have an explicit constructor, but it's rather clear that the default constructor initializes to M_VALID. I have added a note to ValidationState to clarify, but not changing anything else.

I think it's intuitive for the state class to initialize to Valid by default. Adding a factory method for the Valid would be an overkill in my view. It's true that `BlockValidationState` and `ValidationState` don't have an explicit constructor, but it's rather clear that the default constructor initializes to `M_VALID`. I have added a note to `ValidationState` to clarify, but not changing anything else.
optout21 (Migrated from github.com) commented 2026-09-08 09:49:37 +00:00

Taken.

Taken.
optout21 (Migrated from github.com) commented 2026-09-08 07:11:08 +00:00

Good catch. On failure IsValid() is false, moreover IsInvalid() is true. I state: "On failure, IsValid() is false and the state contains the specific validation failure reason. Never returns Error state.". From the last bit it follows that IsInvalid() is true, but I don't mention it here, only IsValid(), as that should be used to check for normal vs. exceptional case.

Good catch. On failure `IsValid()` is false, moreover `IsInvalid()` is true. I state: "On failure, IsValid() is false and the state contains the specific validation failure reason. Never returns Error state.". From the last bit it follows that `IsInvalid()` is true, but I don't mention it here, only `IsValid()`, as that should be used to check for normal vs. exceptional case.
arejula27 (Migrated from github.com) reviewed 2026-09-10 16:03:11 +00:00
arejula27 (Migrated from github.com) commented 2026-09-10 16:03:11 +00:00

agree

agree
arejula27 (Migrated from github.com) reviewed 2026-09-10 16:03:59 +00:00
arejula27 (Migrated from github.com) left a comment

re-ack 58d6d23275

re-ack 58d6d23275067dc284ca13f3d7906ac9aaf7843a
optout21 commented 2026-09-10 22:12:54 +00:00 (Migrated from github.com)

re-ack 58d6d23275

Thanks, but I think you need the form "reACK" exactly, to be picked up by the review bot. Could you edit it (or re-comment)?

> re-ack 58d6d23275067dc284ca13f3d7906ac9aaf7843a Thanks, but I think you need the form "reACK" exactly, to be picked up by the review bot. Could you edit it (or re-comment)?
arejula27 commented 2026-09-10 22:19:30 +00:00 (Migrated from github.com)

Sorry, first time doing it😅

Sorry, first time doing it😅
w0xlt (Migrated from github.com) reviewed 2026-09-11 01:07:13 +00:00
w0xlt (Migrated from github.com) commented 2026-09-11 01:07:13 +00:00

I am trying to understand this.
Calling validation_state_pow_and_merkle.Error("") changes the state to Error, making the later if (validation_state_pow_and_merkle.IsValid()) always false so it never runs.

Separately, the IsValid() || IsInvalid() || IsError() assertions appear redundant, even before the refactor: a default-constructed state was Valid, so these assertions would pass even if CheckBlock() never updated it.

I am trying to understand this. Calling `validation_state_pow_and_merkle.Error("")` changes the state to Error, making the later `if (validation_state_pow_and_merkle.IsValid())` always false so it never runs. Separately, the `IsValid() || IsInvalid() || IsError()` assertions appear redundant, even before the refactor: a default-constructed state was `Valid`, so these assertions would pass even if `CheckBlock()` never updated it.
optout21 (Migrated from github.com) reviewed 2026-09-11 07:22:01 +00:00
optout21 (Migrated from github.com) left a comment

Applied fix to a minor fuzz test bug, found in review (thanks @w0xlt).

git range-diff 58d6d23275067dc284ca13f3d7906ac9aaf7843a...981912489d89d40a2f54b58b9e035906e5cb4737

Applied fix to a minor fuzz test bug, found in review (thanks @w0xlt). `git range-diff 58d6d23275067dc284ca13f3d7906ac9aaf7843a...981912489d89d40a2f54b58b9e035906e5cb4737`
optout21 (Migrated from github.com) commented 2026-09-11 07:20:25 +00:00

Pre-change, CheckBlock returned a bool and status in the parameter. The fuzz test saved the bools, and used them for checks at the end. Since there is no bool return any more, those became unavailable, and status.IsValid() is used instead.

You are right, that the setting of validation_state_pow_and_merkle to error interferes with this! I'm not sure of the intention of that line, but it seems it didn't do anything meaningful, as that variable was not accessed afterwards. It may contribute to test coverage though. So my resulotion is to move the .Error() call to the end.

Applying now, as this is a (minor) bug to the fuzz test. Thanks for the find!

Pre-change, `CheckBlock` returned a bool and status in the parameter. The fuzz test saved the bools, and used them for checks at the end. Since there is no bool return any more, those became unavailable, and `status.IsValid()` is used instead. You are right, that the setting of `validation_state_pow_and_merkle` to error interferes with this! I'm not sure of the intention of that line, but it seems it didn't do anything meaningful, as that variable was not accessed afterwards. It may contribute to test coverage though. So my resulotion is to move the `.Error()` call to the end. Applying now, as this is a (minor) bug to the fuzz test. Thanks for the find!
hodlinator (Migrated from github.com) reviewed 2026-09-15 13:18:32 +00:00
hodlinator (Migrated from github.com) left a comment

Reviewed 981912489d

I get the impression the alternative #35646 returns narrower types, which makes the code more correct by construction rather than adding assert(state.IsInvalid). Only just discovered that PR though, so will try to review it next, before coming back to this one.

Reviewed 981912489d89d40a2f54b58b9e035906e5cb4737 I get the impression the alternative #35646 returns narrower types, which makes the code more correct by construction rather than adding `assert(state.IsInvalid)`. Only just discovered that PR though, so will try to review it next, before coming back to this one.
hodlinator (Migrated from github.com) commented 2026-09-15 12:27:55 +00:00

nanonit: Could reduce camelCase in touched lines as developer-notes.md enforces snake_case.

            const BlockValidationState state{CheckBlock(block, chain_params->GetConsensus())};
            assert(state.IsValid());
nanonit: Could reduce camelCase in touched lines as developer-notes.md enforces snake_case. ```suggestion const BlockValidationState state{CheckBlock(block, chain_params->GetConsensus())}; assert(state.IsValid()); ```
hodlinator (Migrated from github.com) commented 2026-09-15 12:30:06 +00:00

nanonit: Even stronger assertion:

        assert(cvstate.IsInvalid());
nanonit: Even stronger assertion: ```suggestion assert(cvstate.IsInvalid()); ```
hodlinator (Migrated from github.com) commented 2026-09-15 09:54:19 +00:00

nits: So much "state" in BlockValidationState::InvalidState(... how about:

    static BlockValidationState MakeInvalid(BlockValidationResult result,

or alternatively make it a free function outside of BlockValidationState as we don't need access to private parts:

[[nodiscard]] inline BlockValidationState InvalidBlockValidationState(BlockValidationResult result,
    const std::string& reject_reason = {}, const std::string& debug_message = {})
{

(+ make it nodiscard).

nits: So much "state" in `BlockValidationState::InvalidState(...` how about: ```suggestion static BlockValidationState MakeInvalid(BlockValidationResult result, ``` or alternatively make it a free function outside of `BlockValidationState` as we don't need access to private parts: ```c++ [[nodiscard]] inline BlockValidationState InvalidBlockValidationState(BlockValidationResult result, const std::string& reject_reason = {}, const std::string& debug_message = {}) { ``` (+ make it `nodiscard`).
hodlinator (Migrated from github.com) commented 2026-09-15 09:48:15 +00:00

nit: Could use default ctor initialization to avoid any risk of having to seek through the string literals for NUL term.

        const std::string& reject_reason = {}, const std::string& debug_message = {})
nit: Could use default ctor initialization to avoid any risk of having to seek through the string literals for NUL term. ```suggestion const std::string& reject_reason = {}, const std::string& debug_message = {}) ```
hodlinator (Migrated from github.com) commented 2026-09-15 09:53:00 +00:00

nit: Could add precondition:

        Assume(result != BlockValidationResult::BLOCK_RESULT_UNSET);
nit: Could add precondition: ```c++ Assume(result != BlockValidationResult::BLOCK_RESULT_UNSET); ```
hodlinator (Migrated from github.com) commented 2026-09-15 12:10:28 +00:00

nit: Would prefer this were introduced together with InvalidState() and then used in the later refactoring commits for FatalError() and AcceptBlock().

nit: Would prefer this were introduced together with `InvalidState()` and then used in the later refactoring commits for `FatalError()` and `AcceptBlock()`.
hodlinator (Migrated from github.com) commented 2026-09-15 10:00:26 +00:00

0f6e59c Refactor CheckBlockHeader signature:

We want to make sure that we are not overriding an invalid/error state with a valid state with this refactor. Could add this before overwriting the incoming state parameter:

    Assume(state.IsValid());

The CI tests and reviewers running the ancestor commits can then help verify that the behavior doesn't change.

Most of them could then hopefully be removed in later commits where we further reduce the scopes of state-variables.

Same in AcceptBlockHeader() in this commit, and same pattern in later commits.

> [0f6e59c](https://github.com/bitcoin/bitcoin/pull/35570/changes/0f6e59cd81755e801cd4f2bb60ff7211bb8762ba) _Refactor CheckBlockHeader signature_: We want to make sure that we are not overriding an invalid/error state with a valid state with this refactor. Could add this before overwriting the incoming state parameter: ```c++ Assume(state.IsValid()); ``` The CI tests and reviewers running the ancestor commits can then help verify that the behavior doesn't change. Most of them could then hopefully be removed in later commits where we further reduce the scopes of `state`-variables. Same in `AcceptBlockHeader()` in this commit, and same pattern in later commits.
hodlinator (Migrated from github.com) commented 2026-09-15 11:01:41 +00:00

remark in 86104e9d74 "Refactor AcceptBlockHeader signature":

I understand that these asserts can be added since no paths currently return error. Hope these wires won't be tripped outside of tests in the future. Not sure whether these types of documentation asserts should be used in such critical code when the conditions they catch don't obviously cause problems later on during execution (in contrast to checking a pointer for non-nullness before de-referencing).

It would feel safer if we made the paths which do not return error states instead return a narrower state type which only allowed valid/invalid, instead of having these more imperative checks.

Maybe their additions could be broken out into a commit at the end, or be deferred to a later PR, keeping this more strictly a refactoring PR. Similar changes are done in 4ed1273687 "Change ProcessNewBlockHeaders", which in its title admits it's not a pure refactoring commit.

remark in 86104e9d74d92cd0c4b72aa0983177c9fcf665e0 "Refactor AcceptBlockHeader signature": I understand that these asserts *can* be added since no paths currently return error. Hope these wires won't be tripped outside of tests in the future. Not sure whether these types of documentation asserts should be used in such critical code when the conditions they catch don't obviously cause problems later on during execution (in contrast to checking a pointer for non-nullness before de-referencing). It would feel safer if we made the paths which do not return error states instead return a narrower state type which only allowed valid/invalid, instead of having these more imperative checks. Maybe their additions could be broken out into a commit at the end, or be deferred to a later PR, *keeping this more strictly a refactoring PR*. Similar changes are done in 4ed127368759983972278265320c278ef3014230 "Change ProcessNewBlockHeaders", which in its title admits it's not a pure refactoring commit.
optout21 commented 2026-09-16 12:22:50 +00:00 (Migrated from github.com)

I get the impression the alternative #35646 returns narrower types, which makes the code more correct by construction rather than adding assert(state.IsInvalid). Only just discovered that PR though, so will try to review it next, before coming back to this one.

Thanks for the review!
#35646 and this PR overlap, but not completely, both have their own merits. PR 35646 was raised later, and I like it, I ack'ed it. I haven't closed this PR, as it has some improvements not present there. In case 35646 is merged first, I will update this PR. Please have a look at #35646 too.

Clarification (Sept 17): I concept-acked #35646, not proper-ack, but I made a mistake, and it showed up as proper-ack (https://github.com/bitcoin/bitcoin/pull/35646#issuecomment-5712874848).

> I get the impression the alternative #35646 returns narrower types, which makes the code more correct by construction rather than adding `assert(state.IsInvalid)`. Only just discovered that PR though, so will try to review it next, before coming back to this one. Thanks for the review! #35646 and this PR overlap, but not completely, both have their own merits. PR 35646 was raised later, and I like it, I ack'ed it. I haven't closed this PR, as it has some improvements not present there. In case 35646 is merged first, I will update this PR. Please have a look at #35646 too. Clarification (Sept 17): I concept-acked #35646, not proper-ack, but I made a mistake, and it showed up as proper-ack (https://github.com/bitcoin/bitcoin/pull/35646#issuecomment-5712874848).
optout21 (Migrated from github.com) reviewed 2026-09-16 13:59:48 +00:00
optout21 (Migrated from github.com) left a comment

Made some (minor) changes, following latest review (@hodlinator).

git range-diff 981912489d89d40a2f54b58b9e035906e5cb4737...312c4e78faa5dc775bb33351ea4dda8a9e18b50a

Made some (minor) changes, following latest review (@hodlinator). ```git range-diff 981912489d89d40a2f54b58b9e035906e5cb4737...312c4e78faa5dc775bb33351ea4dda8a9e18b50a```
optout21 (Migrated from github.com) commented 2026-09-16 12:28:07 +00:00

Taken.

Taken.
optout21 (Migrated from github.com) commented 2026-09-16 12:25:41 +00:00

Technically the check only checked for false return value, that corresponds to !IsValid(). This is a tightening of the checks, but the duplicate inputs case should result in invalid (not error), so it is safe to change. Accepted.

Technically the check only checked for `false` return value, that corresponds to `!IsValid()`. This is a tightening of the checks, but the duplicate inputs case should result in invalid (not error), so it is safe to change. Accepted.
optout21 (Migrated from github.com) commented 2026-09-16 12:43:06 +00:00

Accepted.

sed -i "s/InvalidState/MakeInvalid/g" src/validation.cpp src/validation.h
sed -i "s/ErrorState/MakeError/g" src/validation.cpp src/validation.h
Accepted. ``` sed -i "s/InvalidState/MakeInvalid/g" src/validation.cpp src/validation.h sed -i "s/ErrorState/MakeError/g" src/validation.cpp src/validation.h ```
optout21 (Migrated from github.com) commented 2026-09-16 12:44:37 +00:00

Taken.

Taken.
optout21 (Migrated from github.com) commented 2026-09-16 12:44:17 +00:00

Accepted.

Accepted.
optout21 (Migrated from github.com) commented 2026-09-16 12:29:45 +00:00

It is done (in later commit?).

It is done (in later commit?).
optout21 (Migrated from github.com) commented 2026-09-16 12:40:46 +00:00

This point becomes irrelevant in a later commit, when CheckBlock itself doesn't get an input state, and the state returned from CheckBlockHeader call is placed in a new local variable, so no overwriting can happen.

    // Check that the header is valid (particularly PoW).  This is mostly
    // redundant with the call in AcceptBlockHeader.
    if (const auto state = CheckBlockHeader(block, consensusParams, fCheckPOW); !state.IsValid())
        return state;
This point becomes irrelevant in a later commit, when `CheckBlock` itself doesn't get an input `state`, and the state returned from `CheckBlockHeader` call is placed in a new local variable, so no overwriting can happen. ``` // Check that the header is valid (particularly PoW). This is mostly // redundant with the call in AcceptBlockHeader. if (const auto state = CheckBlockHeader(block, consensusParams, fCheckPOW); !state.IsValid()) return state; ```
optout21 (Migrated from github.com) commented 2026-09-16 13:47:00 +00:00

I understand the doubts about using potentially catastrophic assert's.
However, if an invariant can be verified by static code analysis of a small amount of code, assert are useful for not only documenting, but enforcing invariants.
I agree that narrower return values are superior solution in this case, but I did not see an easy way to ensure that.
The concern about code being changed later is always a valid worry, I agree.
I would prefer these methods to have a single return at the end, and assert just before the single return. However, with early-exit returns style that's not practical.

In this PR, the following 4 methods can return Valid or Invalid, but never Error:

  • CheckBlockHeader: Internal method, and trivial to verify the code: it has 3 lines with 2 returns, and none of them is Error.
  • ContextualCheckBlockHeader: Internal method, more complicated, around 8 returns, one {} and the rest all MakeInvalid
  • AcceptBlockHeader: This is a public private method, and its return are Invalid or Valid, except 2 cases, where it calls into the above two methods. If those return non-valid, that must be invalid, and this is asserted and returned. This way it can be verified by looking only at this method that it cannot return Error.
  • ProcessNewBlockHeaders: Public method. Returns valid, or non-valid from AcceptBlockHeader, which, by the above, must be Invalid. This is asserted, so that the invariant can be verified by looking only at this method.
    It is only this last method which is called from outside, from net_processing.cpp, and there is is Assume'd that it doesn't return Error.

Moving these asserts to a separate commit is tempting, but in fact it's only cosmetics.
I've also considered using less dangerous Assume. Or leaving them out altogether.

Based on the above explanation I keep as it is for now. Those asserts are needed to ensure the invariant added to the documentation ("Never returns Error state").

I understand the doubts about using potentially catastrophic `assert`'s. However, if an invariant can be verified by static code analysis of a small amount of code, assert are useful for not only documenting, but enforcing invariants. I agree that narrower return values are superior solution in this case, but I did not see an easy way to ensure that. The concern about code being changed later is always a valid worry, I agree. I would prefer these methods to have a single return at the end, and assert just before the single return. However, with early-exit returns style that's not practical. In this PR, the following 4 methods can return Valid or Invalid, but never Error: - `CheckBlockHeader`: Internal method, and trivial to verify the code: it has 3 lines with 2 returns, and none of them is Error. - `ContextualCheckBlockHeader`: Internal method, more complicated, around 8 returns, one `{}` and the rest all `MakeInvalid` - `AcceptBlockHeader`: This is a ~~public~~ private method, and its return are Invalid or Valid, except 2 cases, where it calls into the above two methods. If those return non-valid, that must be invalid, and this is asserted and returned. This way it can be verified by looking only at this method that it cannot return Error. - `ProcessNewBlockHeaders`: Public method. Returns valid, or non-valid from `AcceptBlockHeader`, which, by the above, must be Invalid. This is asserted, so that the invariant can be verified by looking only at this method. It is only this last method which is called from outside, from `net_processing.cpp`, and there is is `Assume`'d that it doesn't return Error. Moving these asserts to a separate commit is tempting, but in fact it's only cosmetics. I've also considered using less dangerous `Assume`. Or leaving them out altogether. Based on the above explanation I keep as it is for now. Those asserts are needed to ensure the invariant added to the documentation ("Never returns Error state").
DrahtBot commented 2026-09-16 15:24:43 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/35105544002/job/104825688520
LLM reason (✨ experimental): CI failed because IWYU reported include fixes were needed and intentionally exited non-zero (“Failure generated from IWYU”).

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `iwyu`: https://github.com/bitcoin/bitcoin/actions/runs/35105544002/job/104825688520</sub> <sub>LLM reason (✨ experimental): CI failed because IWYU reported include fixes were needed and intentionally exited non-zero (“Failure generated from IWYU”).</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>
optout21 commented 2026-09-16 16:50:27 +00:00 (Migrated from github.com)

Fixed IWYU CI failure (missing include for new Assume).
Additionally added comments to CheckBlockHeader and ContextualCheckBlockHeader (that they cannot return Error), and also fixed an outdated comment in src/net_processing.cpp (AcceptBlockHeader/ProcessNewBlockHeaders).

Fixed IWYU CI failure (missing include for new `Assume`). Additionally added comments to `CheckBlockHeader` and `ContextualCheckBlockHeader` (that they cannot return Error), and also fixed an outdated comment in `src/net_processing.cpp` (AcceptBlockHeader/ProcessNewBlockHeaders).
hodlinator (Migrated from github.com) reviewed 2026-09-17 07:55:47 +00:00
hodlinator (Migrated from github.com) left a comment

Reviewed a92cd68a34

The way this PR transforms pre-existing functions one at a time is something I wish #35646 did as well.

Agree that it complements #35646, but think it should go in after that one (see inline comment), so I'll defer my Concept A-C-K until something like that lands. Please don't see my reservations as disinterest, I spend time on it because I agree the general direction is worthwhile.

Branch incorporating my suggestions into existing commits: https://github.com/hodlinator/bitcoin/tree/pr/35570_suggestions

Reviewed a92cd68a3433b2cdae9c944345d8d20417c5a46f The way this PR transforms pre-existing functions one at a time is something I wish #35646 did as well. Agree that it complements #35646, but think it should go in after that one (see inline comment), so I'll defer my Concept A-C-K until something like that lands. Please don't see my reservations as disinterest, I spend time on it because I agree the general direction is worthwhile. Branch incorporating my suggestions into existing commits: https://github.com/hodlinator/bitcoin/tree/pr/35570_suggestions
hodlinator (Migrated from github.com) commented 2026-09-16 18:25:14 +00:00
thread https://github.com/bitcoin/bitcoin/pull/35570#discussion_r4014245663: Please also fix `MakeError(const std::string& reject_reason = "")`.
hodlinator (Migrated from github.com) commented 2026-09-16 19:31:08 +00:00

thread https://github.com/bitcoin/bitcoin/pull/35570#discussion_r4015407700:

What I meant is to add both MakeInvalid() and MakeError() helpers in the first commit. Then in the "Refactor FatalError signature" and "Refactor AcceptBlock signature" commits you can switch directly to MakeError() instead of the intermediate hop through state.Error() ... return state which those commits currently do.

thread https://github.com/bitcoin/bitcoin/pull/35570#discussion_r4015407700: What I meant is to add both `MakeInvalid()` and `MakeError()` helpers in the first commit. Then in the "Refactor FatalError signature" and "Refactor AcceptBlock signature" commits you can switch directly to `MakeError()` instead of the intermediate hop through `state.Error() ... return state` which those commits currently do.
hodlinator (Migrated from github.com) commented 2026-09-16 19:15:21 +00:00

This can be dropped in the "Refactor CheckBlock signature" commit so we only assign state once.

This can be dropped in the "Refactor CheckBlock signature" commit so we only assign state once. ```suggestion ```
hodlinator (Migrated from github.com) commented 2026-09-16 19:37:09 +00:00

thread https://github.com/bitcoin/bitcoin/pull/35570#discussion_r4014342260:

I know many checks away in later commits but still think it's good practice to add them in intermediate commits when you are changing behavior of such critical code.

At the very least the "test ancestor commits" CI job can churn through them.

You are changing the local code behavior from maybe changing state when passed as an argument, to definitely stomping it with a return value.

I went through and added Assumes in my suggestions branch and many of them survive until the end, although I admit some are overly paranoid.

thread https://github.com/bitcoin/bitcoin/pull/35570#discussion_r4014342260: I know many checks away in later commits but still think it's good practice to add them in intermediate commits when you are changing behavior of such critical code. At the very least the "test ancestor commits" CI job can churn through them. You are changing the local code behavior from *maybe* changing `state` when passed as an argument, to definitely stomping it with a return value. I went through and added `Assume`s in my suggestions branch and many of them survive until the end, although I admit some are overly paranoid.
hodlinator (Migrated from github.com) commented 2026-09-16 20:04:25 +00:00

thread https://github.com/bitcoin/bitcoin/pull/35570#discussion_r4014835740:

Following the call tree on the current PR base is good to do, but not the best we can do. Adding asserts and now comments about current behavior feels like duct tape to me.

As the PRs currently stand, I much prefer #35646 be merged before this PR so invariants are enforced at compile time through types rather than by the duct tape that is runtime failures and comments. That makes it much harder for silent merge conflicts and the like to cause issues.

thread https://github.com/bitcoin/bitcoin/pull/35570#discussion_r4014835740: Following the call tree *on the current PR base* is good to do, but not the best we can do. Adding asserts and now comments about current behavior feels like duct tape to me. As the PRs currently stand, I much prefer #35646 be merged before this PR so invariants are enforced at compile time through types rather than by the duct tape that is runtime failures and comments. That makes it much harder for silent merge conflicts and the like to cause issues.
hodlinator (Migrated from github.com) commented 2026-09-17 07:35:11 +00:00

470b305 Internal simplification in TestBlockValidity:

This state should be removed if we keep this commit where we call CheckBlock() etc which return it's own instances instead of overwriting state. That means we also refactor the next if-block:

    if (block.hashPrevBlock != *Assert(tip->phashBlock)) {
        return BlockValidationState::MakeInvalid({}, "inconclusive-not-best-prevblk");
    }

That also necessitates re-introducing state before calling ConnectBlock(), unless that method is also refactored to return BlockValidationState:

    {
        BlockValidationState state;
        // Set fJustCheck to true in order to update, and not clear, validation caches.
        if (!chainstate.ConnectBlock(block, state, &index_dummy, view_dummy, /*fJustCheck=*/true)) {
            if (state.IsValid()) NONFATAL_UNREACHABLE();
            return state;
        } else {
            if (!state.IsValid()) NONFATAL_UNREACHABLE();
        }
    }
> [470b305](https://github.com/bitcoin/bitcoin/pull/35570/changes/470b305665cad8e2d60a9f3ad1d44e9c8f129f19) _Internal simplification in TestBlockValidity_: This `state` should be removed if we keep this commit where we call `CheckBlock()` etc which return it's own instances instead of overwriting `state`. That means we also refactor the next `if`-block: ```c++ if (block.hashPrevBlock != *Assert(tip->phashBlock)) { return BlockValidationState::MakeInvalid({}, "inconclusive-not-best-prevblk"); } ``` That also necessitates re-introducing `state` before calling `ConnectBlock()`, unless that method is also refactored to return `BlockValidationState`: ```c++ { BlockValidationState state; // Set fJustCheck to true in order to update, and not clear, validation caches. if (!chainstate.ConnectBlock(block, state, &index_dummy, view_dummy, /*fJustCheck=*/true)) { if (state.IsValid()) NONFATAL_UNREACHABLE(); return state; } else { if (!state.IsValid()) NONFATAL_UNREACHABLE(); } } ```
hodlinator (Migrated from github.com) reviewed 2026-09-17 14:19:52 +00:00
hodlinator (Migrated from github.com) commented 2026-09-17 14:19:52 +00:00

Realized BlockValidationState::MakeInvalid({}, ... triggers the Assume(result != BlockValidationResult::BLOCK_RESULT_UNSET), so might be best to skip adding the latter for now.

Realized `BlockValidationState::MakeInvalid({}, ...` triggers the `Assume(result != BlockValidationResult::BLOCK_RESULT_UNSET)`, so might be best to skip adding the latter for now.
optout21 (Migrated from github.com) reviewed 2026-09-18 14:05:19 +00:00
optout21 (Migrated from github.com) left a comment

New round of changes following new review comments.

New round of changes following new review comments.
optout21 (Migrated from github.com) commented 2026-09-18 12:57:51 +00:00

Sorry, the fell through the cracks; done.

Sorry, the fell through the cracks; done.
optout21 (Migrated from github.com) commented 2026-09-18 13:04:57 +00:00

Taken. Through reordering, the double touching of FatalError and AcceptBlock can be avoided.

Taken. Through reordering, the double touching of `FatalError` and `AcceptBlock` can be avoided.
optout21 (Migrated from github.com) commented 2026-09-18 12:59:38 +00:00

Indeed, MakeInvalid can be used, and then there is no need for the state variable, only further down. Done.

Indeed, `MakeInvalid` can be used, and then there is no need for the `state` variable, only further down. Done.
optout21 (Migrated from github.com) commented 2026-09-18 14:01:51 +00:00

You are right, in the previous form with input-output parameters method had the chance to overwrite the status, but did so only in error case. I've added the proposed Assume's in every place where we overwrite the status always. Some of these Assume's disappear in later commits, but not all.

You are right, in the previous form with input-output parameters method _had the chance_ to overwrite the `status`, but did so only in error case. I've added the proposed `Assume`'s in every place where we overwrite the `status` _always_. Some of these `Assume`'s disappear in later commits, but not all.
arejula27 (Migrated from github.com) reviewed 2026-09-18 14:21:32 +00:00
arejula27 (Migrated from github.com) commented 2026-09-18 14:21:32 +00:00

One question, how do you decide when to use assume and when assert?

One question, how do you decide when to use assume and when assert?
optout21 commented 2026-09-18 14:59:29 +00:00 (Migrated from github.com)

Rebased ot master, hoping to fix the mining_template_verification.py failure in CI (could not reproduce locally).

Rebased ot master, hoping to fix the `mining_template_verification.py` failure in CI (could not reproduce locally).
optout21 commented 2026-09-18 15:48:26 +00:00 (Migrated from github.com)

Test failure is due to this if in TestBlockValidity:

    if (block.hashPrevBlock != *Assert(tip->phashBlock)) {
        return BlockValidationState::MakeInvalid({}, "inconclusive-not-best-prevblk");
    }

which creates an Invalid state with result == BlockValidationResult::BLOCK_RESULT_UNSET, which violates a newly added Assume.

Test failure is due to this `if` in `TestBlockValidity`: ``` if (block.hashPrevBlock != *Assert(tip->phashBlock)) { return BlockValidationState::MakeInvalid({}, "inconclusive-not-best-prevblk"); } ``` which creates an Invalid state with `result == BlockValidationResult::BLOCK_RESULT_UNSET`, which violates a newly added `Assume`.
optout21 (Migrated from github.com) reviewed 2026-09-19 04:51:33 +00:00
optout21 (Migrated from github.com) commented 2026-09-19 04:51:33 +00:00

@hodlinator: This is a rather bold Assume.
It could be made even bolder, if placed inside ValidationState::Invalid()! :D
The CI failure caught one violation of this: #31981 introduced a usage where BlockValidationState is used, but the result is discarded, and Unset is used. My fix is to leave out MakeInvalid() in that case, leave the direct ValidationState::Invalid() call there. (Note: I'm not sure why this failure occurs in only some CI runs, but that's not too important.)

@hodlinator: This is a rather bold Assume. It could be made even bolder, if placed inside `ValidationState::Invalid()`! :D The CI failure caught one violation of this: #31981 introduced a usage where BlockValidationState is used, but the result is discarded, and Unset is used. My fix is to leave out `MakeInvalid()` in that case, leave the direct `ValidationState::Invalid()` call there. (Note: I'm not sure why this failure occurs in only some CI runs, but that's not too important.)
optout21 commented 2026-09-19 04:54:35 +00:00 (Migrated from github.com)

Small change to fix CI failure.
CI caught a violation of the newly introduced Assume: #31981 introduced a usage of BlockValidationState where the result is discarded, and Unset result is used.

git range-diff 6294fb57f8f8db077d22ec294633e7e78762d5b1...0e8dc6b9dd7f07e756dcfe0b8146cc2daa17008e

Small change to fix CI failure. CI caught a violation of the newly introduced `Assume`: #31981 introduced a usage of BlockValidationState where the result is discarded, and Unset result is used. `git range-diff 6294fb57f8f8db077d22ec294633e7e78762d5b1...0e8dc6b9dd7f07e756dcfe0b8146cc2daa17008e`
enirox001 (Migrated from github.com) reviewed 2026-09-22 10:54:18 +00:00
enirox001 (Migrated from github.com) left a comment

Concept ACK https://github.com/bitcoin/bitcoin/pull/35570/changes/5e2d798b28d55fe3786ea23efc33f5fbf4f4fba0

Thanks for working on this, Initial looks at the validation.cpp methods use of the BlockValidationState was a bit ambiguous to understand, this makes things much clearer since the validation states can be used to replace the boolean values being returned.

I have a question, I can see in validation.cpp that there are some methods that have been skipped such as ConnectBlock and ConnectTip these seem to be good prospective targets for this specific refactor?

Concept ACK https://github.com/bitcoin/bitcoin/pull/35570/changes/5e2d798b28d55fe3786ea23efc33f5fbf4f4fba0 Thanks for working on this, Initial looks at the `validation.cpp` methods use of the `BlockValidationState` was a bit ambiguous to understand, this makes things much clearer since the validation states can be used to replace the boolean values being returned. I have a question, I can see in `validation.cpp` that there are some methods that have been skipped such as `ConnectBlock` and `ConnectTip` these seem to be good prospective targets for this specific refactor?
hodlinator (Migrated from github.com) reviewed 2026-09-22 11:40:11 +00:00
hodlinator (Migrated from github.com) commented 2026-09-22 11:40:11 +00:00

Yeah, see my older comment https://github.com/bitcoin/bitcoin/pull/35570#discussion_r4037905445, I thought this Assume was obviously correct but for some reason we have a call-site which didn't want to specify its own enum value.

Yeah, see my older comment https://github.com/bitcoin/bitcoin/pull/35570#discussion_r4037905445, I thought this `Assume` was obviously correct but for some reason we have a call-site which didn't want to specify its own enum value.
optout21 (Migrated from github.com) reviewed 2026-09-22 14:49:17 +00:00
optout21 (Migrated from github.com) commented 2026-09-22 14:49:17 +00:00

I overlooked that you also found this usage.
This is a rather localized usage. Before #31981, the inconclusive-not-best-prevblk check was outside TestBlockValidity, and only the string was used. It was moved into TestBlockValidity, so now it is returned in the reject_reason of the state, but since only reject_reason is used, the reason is left empty. It could use a new BLOCK_INCONCLUSIVE value. I may tackle this separately.

I overlooked that you also found this usage. This is a rather localized usage. Before #31981, the `inconclusive-not-best-prevblk` check was outside `TestBlockValidity`, and only the string was used. It was moved into `TestBlockValidity`, so now it is returned in the `reject_reason` of the `state`, but since only `reject_reason` is used, the `reason` is left empty. It could use a new `BLOCK_INCONCLUSIVE` value. I may tackle this separately.
optout21 commented 2026-09-22 14:54:46 +00:00 (Migrated from github.com)

I have a question, I can see in validation.cpp that there are some methods that have been skipped such as ConnectBlock and ConnectTip these seem to be good prospective targets for this specific refactor?

Yes, the idea can be applied on those equally, I have left them out (or for later?) to limit the scope. Note that #35646 (somewhat related) also tackles those.

> I have a question, I can see in `validation.cpp` that there are some methods that have been skipped such as `ConnectBlock` and `ConnectTip` these seem to be good prospective targets for this specific refactor? Yes, the idea can be applied on those equally, I have left them out (or for later?) to limit the scope. Note that #35646 (somewhat related) also tackles those.
optout21 (Migrated from github.com) reviewed 2026-09-22 15:04:23 +00:00
optout21 (Migrated from github.com) commented 2026-09-22 15:04:23 +00:00

One question, how do you decide when to use assume and when assert?

@arejula27 , there are no clear-cut rules.
assert stops the program immediately, so it should be used only in cases which should never happen. My guideline: use if its truthfulness can be established by static code analysis of the near-scope code, and excludes further potential error cases. E.g. if previous code makes it impossible that a pointer is null, and the pointer is dereferenced later, it makes sense to assert that it cannot be null.
Assert is similar to assert, but it produces logs.
Assume is the least dangerous, it produces logs, but it creates as exception only, not abort.

> One question, how do you decide when to use assume and when assert? @arejula27 , there are no clear-cut rules. `assert` stops the program immediately, so it should be used only in cases which should never happen. My guideline: use if its truthfulness can be established by static code analysis of the near-scope code, and excludes further potential error cases. E.g. if previous code makes it impossible that a pointer is null, and the pointer is dereferenced later, it makes sense to assert that it cannot be null. `Assert` is similar to `assert`, but it produces logs. `Assume` is the least dangerous, it produces logs, but it creates as exception only, not abort.
hodlinator (Migrated from github.com) reviewed 2026-09-22 19:05:08 +00:00
hodlinator (Migrated from github.com) commented 2026-09-22 19:05:08 +00:00

It could use a new BLOCK_INCONCLUSIVE value. I may tackle this separately.

Sounds worth exploring!

> It could use a new `BLOCK_INCONCLUSIVE` value. I may tackle this separately. Sounds worth exploring!
optout21 (Migrated from github.com) reviewed 2026-09-23 11:07:00 +00:00
optout21 (Migrated from github.com) commented 2026-09-23 11:07:00 +00:00

0ef8aa8 Add factory method to BlockValidationState for easier construction:

(Documenting as self-comment). I've realized that the factory method could be added to the template base class ValidationState instead of the specialized/derived class. BlockValidationState would be simpler, the factory would be available for TxValidationState as well, at the price that BlockValidationState would need a constructor from ValidationState<BlockValidationResult>. However, as the factory would not be useful for TX validation as of now, this wouldn't make much sense.

> [0ef8aa8](https://github.com/bitcoin/bitcoin/pull/35570/changes/0ef8aa896860fa691e0c1b2b8817190d9f64d5a2) _Add factory method to BlockValidationState for easier construction_: (Documenting as self-comment). I've realized that the factory method could be added to the template base class `ValidationState` instead of the specialized/derived class. `BlockValidationState` would be simpler, the factory would be available for `TxValidationState` as well, at the price that `BlockValidationState` would need a constructor from `ValidationState<BlockValidationResult>`. However, as the factory would not be useful for TX validation as of now, this wouldn't make much sense.
optout21 (Migrated from github.com) reviewed 2026-09-23 11:55:03 +00:00
optout21 (Migrated from github.com) commented 2026-09-23 11:55:03 +00:00

--> break-out PR created: #36318

--> break-out PR created: #36318
First-time contributor

Earlier concerns neither republished nor resolved: 2 suggestions. See the Run archive linked from the Review report for their assessments.

🟠 Minor · ActivateBestChainStep discards the specific flush failure

A local flush failure during a reorg disconnect now returns Failed to disconnect block. instead of its specific cause, including in RPC errors, while fatal notifications and shutdown behavior remain unchanged.

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

🔵 Suggestion · Corrupt-block Error states discard the original diagnosis

Corrupt stored blocks now reach BlockChecked with BLOCK_RESULT_UNSET rather than BLOCK_MUTATED; shutdown is unchanged, and practical impact is unconfirmed because no external consumer reading Error-mode results was identified.

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

🔵 Suggestion · Stored-block corruption lacks a mode-specific regression test

The refactored branch correctly returns Error, but existing connect_block fuzzing disables its merkle check and only compares success with IsValid(), so it cannot protect the corruption disposition.

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

🔵 Suggestion · TestBlockValidity describes normal rejection as unexpected

The remaining comment labels ordinary CheckBlock rejection as unexpected, although proposal-mode validation accepts external blocks that may fail this check.

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

🔵 Suggestion · c9d80b7 describes a C-API change its patch does not make

The message for c9d80b7 claims a C-API return-type change, but its parent already returns btck_BlockValidationState*; the patch only simplifies the implementation.

Location: src/kernel/bitcoinkernel.cpp:1620 (commit).

Review coverage was incomplete.


Reviewed: beb7dc927a14 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:806938d40e279b6d701b2e78128bb1a09b55193a0b697245a1dce6241d3081c1:3607c760b63c01fb7f1f349adfc3fd0614b148a7df02e42f2f0edc2d448925a1 --> <!-- ralph-base:3e4c803da8b5b63eda5791be869cff4bc18f1c2c --> <!-- ralph-head:beb7dc927a14cfdc95e4b09f0829769c64d4e646 --> <!-- ralph-case:9748ccf617fac851232078fc4dfcb7072d72c652c3c64c64045b4a76714abf1f --> Earlier concerns neither republished nor resolved: 2 suggestions. See the Run archive linked from the Review report for their assessments. **🟠 Minor · `ActivateBestChainStep` discards the specific flush failure** A local flush failure during a reorg disconnect now returns `Failed to disconnect block.` instead of its specific cause, including in RPC errors, while fatal notifications and shutdown behavior remain unchanged. Location: [`src/validation.cpp:3303`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/beb7dc927a14cfdc95e4b09f0829769c64d4e646/src/validation.cpp#L3303>) (head). **🔵 Suggestion · Corrupt-block `Error` states discard the original diagnosis** Corrupt stored blocks now reach `BlockChecked` with `BLOCK_RESULT_UNSET` rather than `BLOCK_MUTATED`; shutdown is unchanged, and practical impact is unconfirmed because no external consumer reading `Error`-mode results was identified. Location: [`src/validation.cpp:2399`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/beb7dc927a14cfdc95e4b09f0829769c64d4e646/src/validation.cpp#L2399>) (head). **🔵 Suggestion · Stored-block corruption lacks a mode-specific regression test** The refactored branch correctly returns `Error`, but existing `connect_block` fuzzing disables its merkle check and only compares success with `IsValid()`, so it cannot protect the corruption disposition. Location: [`src/validation.cpp:2399`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/beb7dc927a14cfdc95e4b09f0829769c64d4e646/src/validation.cpp#L2399>) (head). **🔵 Suggestion · `TestBlockValidity` describes normal rejection as unexpected** The remaining comment labels ordinary `CheckBlock` rejection as unexpected, although proposal-mode validation accepts external blocks that may fail this check. Location: [`src/validation.cpp:4603`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/beb7dc927a14cfdc95e4b09f0829769c64d4e646/src/validation.cpp#L4603>) (head). **🔵 Suggestion · `c9d80b7` describes a C-API change its patch does not make** The message for `c9d80b7` claims a C-API return-type change, but its parent already returns `btck_BlockValidationState*`; the patch only simplifies the implementation. Location: src/kernel/bitcoinkernel.cpp:1620 (commit). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`beb7dc927a14`](<https://git.fish.foo/bitcoin/bitcoin/commit/beb7dc927a14cfdc95e4b09f0829769c64d4e646>) · [Review report](<https://review.fish.foo/report/35570-beb7dc927a14cfdc95e4b09f0829769c64d4e646-3094-6.html>) · [Previous reports](<https://review.fish.foo/traces/35570/>) [permalink](<https://review.fish.foo/report/35570-beb7dc927a14cfdc95e4b09f0829769c64d4e646-3094-6.html>)
arejula27 (Migrated from github.com) reviewed 2026-11-04 16:20:25 +00:00
arejula27 (Migrated from github.com) left a comment

This PR needs to be rebased on master. It no longer compiles after #35714, which added a state.Error() call in FlushStateToDisk, where state does not exist anymore. chainstate_write_tests.cpp also needs the new signature.

This PR needs to be rebased on master. It no longer compiles after #35714, which added a `state.Error()` call in `FlushStateToDisk`, where `state` does not exist anymore. `chainstate_write_tests.cpp` also needs the new signature.
arejula27 (Migrated from github.com) commented 2026-11-04 16:20:03 +00:00

On master, the logs for this case show bad-txnmrklroot, hashMerkleRoot mismatch. Here the state is replaced, so that reason is not logged anywhere and we only see the generic Corrupt block found message. A simple fix is to move the existing LogError above the BLOCK_MUTATED check, so the reason is logged in both cases. If you need the scenario that reproduces the behavioral change, I can share it in a gist

On master, the logs for this case show `bad-txnmrklroot, hashMerkleRoot mismatch`. Here the state is replaced, so that reason is not logged anywhere and we only see the generic `Corrupt block found` message. A simple fix is to move the existing `LogError` above the `BLOCK_MUTATED` check, so the reason is logged in both cases. If you need the scenario that reproduces the behavioral change, I can share it in a gist
optout21 commented 2026-11-05 07:41:50 +00:00 (Migrated from github.com)

Indeed there was a silent merge conflict, thanks for the heads-up @arejula27!
Rebase to current master is without conflict, but it results in code with compile error. #35714 added a state.Error line in FlushStateToDisk, and also some new calls in src/test/chainstate_write_tests.cpp. These have to be updated.

I have now rebased to current master, fixed.

(git range-diff 9e3c5ba481d558cc80190bcd849dbbd0ecb2f60d...774c2c0c667de49f4181953fae5177db34eae5b2)

Indeed there was a silent merge conflict, thanks for the heads-up @arejula27! Rebase to current master is without conflict, but it results in code with compile error. #35714 added a `state.Error` line in `FlushStateToDisk`, and also some new calls in `src/test/chainstate_write_tests.cpp`. These have to be updated. I have now rebased to current master, fixed. (`git range-diff 9e3c5ba481d558cc80190bcd849dbbd0ecb2f60d...774c2c0c667de49f4181953fae5177db34eae5b2`)
optout21 (Migrated from github.com) reviewed 2026-11-05 08:41:50 +00:00
optout21 (Migrated from github.com) commented 2026-11-05 08:41:50 +00:00

Indeed, good catch!
The old code did overwrite the state, but only partly. It 'upgraded' the error from Invalid to Error, but when doing so, the reject reason was kept. Now a new state is created, that will have the supplied new reason.

This is a slight behavior change (albeit small), I'm still mulling on how to deal with it:

  • Workaround, add another logging (or just switch the order), so both reject reasons are logged. Keep the overwrite.
  • Overwrite the Invalid state with a new Error one, but include the previous state (as string) in the new reject reason (and log).
  • Change the behavior in a separate commit, so it's explicit. The reason is logged and overwritten.
  • Mimic the old behavior, by always supplying FatalError with a previous state, and potentially preserving the reason string from there.
  • Sort out the issue in a separate PR (for better visibility)

I was looking also for similar cases (state = ..., MakeError, FatalError). There are a handful of places to check (in ConnectTip, ActivateBestChainStep, VerifyDB).

Analyzing the old code, the "Corrupt block..." message was never stored in the state!

Details:
  • BLOCK_MUTATED is always used with Invalid state, and one of the following reject reasons: "bad-txnmrklroot", "bad-txns-duplicate", "bad-witness-nonce-size", "bad-witness-merkle-match", "unexpected-witness".
  • when execution gets into the if branch, state.m_mode is M_INVALID
  • notifications.fatalError is invoked with "Corrupt block..."
  • state.Error is called
  • mode is set to Error, but reject reason is not Changed
  • Later logging uses the original reject reason
if (state.GetResult() == BlockValidationResult::BLOCK_MUTATED) {
    // We don't write down blocks to disk if they may have been
    // corrupted, so this should be impossible unless we're having hardware
    // problems.
    return FatalError(m_chainman.GetNotifications(), state, _("Corrupt block found indicating potential hardware failure."));
}
LogError("%s: Consensus::CheckBlock: %s\n", __func__, state.ToString());
bool FatalError(Notifications& notifications, BlockValidationState& state, const bilingual_str& message)
{
    notifications.fatalError(message);
    return state.Error(message.original);
}
bool Error(const std::string& reject_reason)
{
    if (m_mode == ModeState::M_VALID)
        m_reject_reason = reject_reason;
    m_mode = ModeState::M_ERROR;
    return false;
}
Indeed, good catch! The old code did overwrite the state, but only partly. It 'upgraded' the error from Invalid to Error, but when doing so, the reject reason was kept. Now a new state is created, that will have the supplied new reason. This is a slight behavior change (albeit small), I'm still mulling on how to deal with it: - Workaround, add another logging (or just switch the order), so both reject reasons are logged. Keep the overwrite. - Overwrite the Invalid state with a new Error one, but include the previous state (as string) in the new reject reason (and log). - Change the behavior in a separate commit, so it's explicit. The reason is logged and overwritten. - Mimic the old behavior, by always supplying `FatalError` with a previous state, and potentially preserving the reason string from there. - Sort out the issue in a separate PR (for better visibility) I was looking also for similar cases (`state = ...`, `MakeError`, `FatalError`). There are a handful of places to check (in `ConnectTip`, `ActivateBestChainStep`, `VerifyDB`). Analyzing the old code, the `"Corrupt block..."` message was never stored in the state! <details> <summary> Details: </summary> - `BLOCK_MUTATED` is always used with Invalid state, and one of the following reject reasons: `"bad-txnmrklroot"`, `"bad-txns-duplicate"`, `"bad-witness-nonce-size"`, `"bad-witness-merkle-match"`, `"unexpected-witness"`. - when execution gets into the if branch, `state.m_mode` is `M_INVALID` - `notifications.fatalError` is invoked with `"Corrupt block..."` - `state.Error` is called - mode is set to Error, but reject reason is not Changed - Later logging uses the original reject reason ```C++ if (state.GetResult() == BlockValidationResult::BLOCK_MUTATED) { // We don't write down blocks to disk if they may have been // corrupted, so this should be impossible unless we're having hardware // problems. return FatalError(m_chainman.GetNotifications(), state, _("Corrupt block found indicating potential hardware failure.")); } LogError("%s: Consensus::CheckBlock: %s\n", __func__, state.ToString()); ``` ```C++ bool FatalError(Notifications& notifications, BlockValidationState& state, const bilingual_str& message) { notifications.fatalError(message); return state.Error(message.original); } ``` ```C++ bool Error(const std::string& reject_reason) { if (m_mode == ModeState::M_VALID) m_reject_reason = reject_reason; m_mode = ModeState::M_ERROR; return false; } ``` </details>
optout21 (Migrated from github.com) reviewed 2026-11-05 10:24:53 +00:00
optout21 (Migrated from github.com) left a comment

Fixed the point raised by @arejula27.

git range-diff 774c2c0c667de49f4181953fae5177db34eae5b2...7b7392e61f35fdab5e22d7348ae05154a81e2b58

Fixed the point raised by @arejula27. `git range-diff 774c2c0c667de49f4181953fae5177db34eae5b2...7b7392e61f35fdab5e22d7348ae05154a81e2b58`
optout21 (Migrated from github.com) commented 2026-11-05 10:18:02 +00:00

I concluded that overwriting the rejection reason here is the right way to go, as a new, higher level error is created from the previous invalid result. Also, it's not recommended to mix Error status with Invalid-style reject reasons.
My fix is adding a specific log and comment about the upgrading of the error.

I've also checked for other potential places where an Invalid state can be upgraded to Error, but found none (checked changed in validation.cpp, especially around the patterns state = ..., MakeError, FatalError).

In fact, with these changes the conditional change of reject reason in ValidationState::Error is not needed, it is only called with a fresh Valid state, the if could be changed to an assert or removed. I haven't done so (just tried it).

I concluded that overwriting the rejection reason here is the right way to go, as a new, higher level error is created from the previous invalid result. Also, it's not recommended to mix Error status with Invalid-style reject reasons. My fix is adding a specific log and comment about the upgrading of the error. I've also checked for other potential places where an Invalid state can be upgraded to Error, but found none (checked changed in `validation.cpp`, especially around the patterns `state = ...`, `MakeError`, `FatalError`). In fact, with these changes the conditional change of reject reason in `ValidationState::Error` is not needed, it is only called with a fresh Valid state, the `if` could be changed to an assert or removed. I haven't done so (just tried it).
arejula27 commented 2026-11-05 23:55:52 +00:00 (Migrated from github.com)

tACK 7b7392e61f

Corrupted a block on disk and forced a reorg to read it, then compared the logs:

master:

ConnectTip: ConnectBlock <hash> failed, bad-txnmrklroot, hashMerkleRoot mismatch

this PR:

ConnectBlock: Consensus::CheckBlock: Corrupt block found: bad-txnmrklroot, hashMerkleRoot mismatch
ConnectTip: ConnectBlock <hash> failed, Corrupt block found indicating potential hardware failure.

The reason is still logged, so this looks good to me. I agree with your view that a new, higher level error is forwarded. Not sure if it should be discussed deeper (long related discussion on #35646) but it is ok for me.

tACK 7b7392e61f35fdab5e22d7348ae05154a81e2b58 Corrupted a block on disk and forced a reorg to read it, then compared the logs: master: ``` ConnectTip: ConnectBlock <hash> failed, bad-txnmrklroot, hashMerkleRoot mismatch ``` this PR: ``` ConnectBlock: Consensus::CheckBlock: Corrupt block found: bad-txnmrklroot, hashMerkleRoot mismatch ConnectTip: ConnectBlock <hash> failed, Corrupt block found indicating potential hardware failure. ``` The reason is still logged, so this looks good to me. I agree with your view that a new, higher level error is forwarded. Not sure if it should be discussed deeper (long related discussion on #35646) but it is ok for me.
optout21 (Migrated from github.com) reviewed 2026-11-06 13:17:43 +00:00
optout21 (Migrated from github.com) commented 2026-11-06 13:17:43 +00:00

Self-review note: In this line a previous non-valid state may be overwritten. The DisconnectTip() -> FlushStateToDisk() call may return an Error state. In the case FatalError() is called twice.

Self-review note: In this line a previous non-valid state may be overwritten. The `DisconnectTip()` -> `FlushStateToDisk()` call may return an `Error` state. In the case `FatalError()` is called twice.
optout21 (Migrated from github.com) reviewed 2026-11-06 18:15:27 +00:00
optout21 (Migrated from github.com) commented 2026-11-06 18:15:27 +00:00

A separate break-out PR was raised with this issue, isolating the (minor) behavior change: #36792

A separate break-out PR was raised with this issue, isolating the (minor) behavior change: #36792
optout21 (Migrated from github.com) reviewed 2026-11-06 18:34:04 +00:00
optout21 (Migrated from github.com) commented 2026-11-06 18:34:04 +00:00

Note: Also covered in #36792

Note: Also covered in #36792
DrahtBot commented 2026-11-24 17:12:49 +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).
optout21 commented 2026-11-24 22:46:57 +00:00 (Migrated from github.com)

Straightforward rebase (due to #36782), no other change.

Straightforward rebase (due to #36782), no other change.
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!35570
No description provided.