kernel: Use typed errors for fatal and flush error notifications #36326

Open
arejula27 wants to merge 6 commits from kernel-notifications-error-variant into master AGit
arejula27 commented 2026-09-24 12:46:30 +00:00 (Migrated from github.com)

Part of the libbitcoinkernel project (tracking issue #27587 ), specifically the "Remove translation.h usage from the kernel" item. kernel::Notifications::fatalError() and flushError() take a bilingual_str, which pulls util/translation.h and the application-level G_TRANSLATION_FUN into the kernel library, and translation is an application concern rather than a consensus one. The same interface already shows the way out: warningSet() takes a kernel::Warning enum, and the node turns it into a translated string in node/kernel_notifications.cpp.

Along with removing the dependency, another goal here is separating responsibilities, because the goals of error handling and error reporting are different: presenting an error to a user is an application concern, not something libbitcoinkernel itself should own. The error is structured on both sides: in C++ as the full kernel::FatalError variant, and in the C API as its numeric value. With the current changes the C side only carries half of that structure today though, the dynamic fields (a block hash, a path, an exception's what()) do not cross the C API yet, even though ideally they should.

This PR does the same for the two error notifications. A new src/kernel/error.h defines kernel::FlushError as a plain enum and kernel::FatalError as a std::variant with one struct per error, whose fields carry the context the message needs: a block hash, a path, the what() of a caught exception, block heights. It holds types and nothing else, so every message is now built on the node side. The exception is FatalErrorString() in validation.cpp, because a fatal error raised during validation also fails the block through BlockValidationState::Error(), which takes the reason as a plain string right there, and fatalError() returns void, so the node has no way to put its message into that state. A follow-up could store the typed error in the state instead and let the node create the string message.

This does not remove the kernel's dependency on util/translation.h, it is just a step. The other two notifications, progress() and warningSet(), still take a bilingual_str, and bitcoinkernel.cpp, checks.cpp, node/chainstate.cpp, txmempool.cpp and validation.cpp still include the header.

There is one behavior change to mention here. The two C API callbacks lose their message parameter, so they now carry only the error code, the same pattern that btck_BlockValidationResult already uses.

Part of the libbitcoinkernel project (tracking issue #27587 ), specifically the "Remove translation.h usage from the kernel" item. `kernel::Notifications::fatalError()` and `flushError()` take a `bilingual_str`, which pulls `util/translation.h` and the application-level `G_TRANSLATION_FUN` into the kernel library, and translation is an application concern rather than a consensus one. The same interface already shows the way out: `warningSet()` takes a `kernel::Warning` enum, and the node turns it into a translated string in `node/kernel_notifications.cpp`. Along with removing the dependency, another goal here is separating responsibilities, because the goals of error handling and error reporting are different: presenting an error to a user is an application concern, not something `libbitcoinkernel` itself should own. The error is structured on both sides: in C++ as the full `kernel::FatalError` variant, and in the C API as its numeric value. With the current changes the C side only carries half of that structure today though, the dynamic fields (a block hash, a path, an exception's `what()`) do not cross the C API yet, even though ideally they should. This PR does the same for the two error notifications. A new `src/kernel/error.h` defines `kernel::FlushError` as a plain enum and `kernel::FatalError` as a `std::variant` with one struct per error, whose fields carry the context the message needs: a block hash, a path, the `what()` of a caught exception, block heights. It holds types and nothing else, so every message is now built on the node side. The exception is `FatalErrorString()` in `validation.cpp`, because a fatal error raised during validation also fails the block through `BlockValidationState::Error()`, which takes the reason as a plain string right there, and `fatalError()` returns void, so the node has no way to put its message into that state. A follow-up could store the typed error in the state instead and let the node create the string message. This does not remove the kernel's dependency on `util/translation.h`, it is just a step. The other two notifications, `progress()` and `warningSet()`, still take a `bilingual_str`, and `bitcoinkernel.cpp`, `checks.cpp`, `node/chainstate.cpp`, `txmempool.cpp` and `validation.cpp` still include the header. There is one behavior change to mention here. The two C API callbacks lose their `message` parameter, so they now carry only the error code, the same pattern that `btck_BlockValidationResult` already uses.
DrahtBot commented 2026-09-24 12:46:38 +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 sedited, yuvicc, pzafonte

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:

  • #37094 (validation: validate assumeutxo snapshots with a single chainstate by fjahr)
  • #36904 (log: Remove trailing and embedded newlines from log messages by maflcko)
  • #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)
  • #36738 (refactor: move block writes and pruning into BlockManager by pzafonte)
  • #36603 (Improve loadtxoutset performance by ajtowns)
  • #36167 (build: Enable -Wunused by fanquake)
  • #35731 (Indexes: Harden the flush-error notification invariant by arejula27)
  • #34132 (coins,dbwrapper: make database point-read failures fatal by l0rinc)

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.

<!--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/36326 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36326.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36326#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 | [sedited](https://github.com/bitcoin/bitcoin/pull/36326#issuecomment-5814588408), [yuvicc](https://github.com/bitcoin/bitcoin/pull/36326#pullrequestreview-5465955822), [pzafonte](https://github.com/bitcoin/bitcoin/pull/36326#pullrequestreview-5997912616) | 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: * [#37094](https://github.com/bitcoin/bitcoin/pull/37094) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/37094.svg"></sub> (validation: validate assumeutxo snapshots with a single chainstate by fjahr) * [#36904](https://github.com/bitcoin/bitcoin/pull/36904) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36904.svg"></sub> (log: Remove trailing and embedded newlines from log messages by maflcko) * [#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) * [#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) * [#36603](https://github.com/bitcoin/bitcoin/pull/36603) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36603.svg"></sub> (Improve loadtxoutset performance by ajtowns) * [#36167](https://github.com/bitcoin/bitcoin/pull/36167) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36167.svg"></sub> (build: Enable `-Wunused` by fanquake) * [#35731](https://github.com/bitcoin/bitcoin/pull/35731) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35731.svg"></sub> (Indexes: Harden the flush-error notification invariant by arejula27) * [#34132](https://github.com/bitcoin/bitcoin/pull/34132) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/34132.svg"></sub> (coins,dbwrapper: make database point-read failures fatal by l0rinc) 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-->
sedited commented 2026-09-24 12:59:18 +00:00 (Migrated from github.com)

Concept ACK :)

Concept ACK :)
DrahtBot commented 2026-09-24 13:50:00 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/36001208610/job/107638021690
LLM reason (✨ experimental): CI failed because IWYU detected missing/incorrect includes and generated changes (“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/36001208610/job/107638021690</sub> <sub>LLM reason (✨ experimental): CI failed because IWYU detected missing/incorrect includes and generated changes (“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>
ryanofsky commented 2026-09-24 14:50:44 +00:00 (Migrated from github.com)

Remove translation.h usage from the kernel

Interesting. I didn't know this was a goal. Has this been discussed somewhere? Do we want to have no ability for the kernel to show detailed translated messages when something fails in the kernel, like "Bad undo data in block {hash} height {height} file {filename}" (to pick a random example)? Is this because we want (1) all kernel messages to be untranslated? Or (2) all messages that are translated to be represented as structs and enums in the kernel and made into strings by applications? Or some combination of these approaches?

I do think these approaches are reasonable, but they do come with costs. Approach (1) makes harder to write polished applications that are localized and do not require english. Approach (2) is costly to developers and users because it either results in vague messages that do not include important details necessary to understand, or it requires complicated structural representations of exceptional conditions and statuses in code.

IMO, util/translation.h is a low overhead way to provide helpful error and status messages that can be easily translated as needed. I don't see significant benefits to removing it and don't think it should be a goal to remove.

Which is not to say that providing structural error information is not useful at all. Right now we do not provide enough structural error information and should provide more. But it is also possible to take things too far and add too much structure. We should not be creating a situation where calling any kernel API means needing to handle a half-dozen error codes, when a simple error status and a translated string would be easier to handle in code and provide more detailed and helpful information to users.

> Remove translation.h usage from the kernel Interesting. I didn't know this was a goal. Has this been discussed somewhere? Do we want to have no ability for the kernel to show detailed translated messages when something fails in the kernel, like "Bad undo data in block {hash} height {height} file {filename}" (to pick a random example)? Is this because we want (1) all kernel messages to be untranslated? Or (2) all messages that are translated to be represented as structs and enums in the kernel and made into strings by applications? Or some combination of these approaches? I do think these approaches are reasonable, but they do come with costs. Approach (1) makes harder to write polished applications that are localized and do not require english. Approach (2) is costly to developers and users because it either results in vague messages that do not include important details necessary to understand, or it requires complicated structural representations of exceptional conditions and statuses in code. IMO, util/translation.h is a low overhead way to provide helpful error and status messages that can be easily translated as needed. I don't see significant benefits to removing it and don't think it should be a goal to remove. Which is not to say that providing structural error information is not useful at all. Right now we do not provide enough structural error information and should provide more. But it is also possible to take things too far and add too much structure. We should not be creating a situation where calling any kernel API means needing to handle a half-dozen error codes, when a simple error status and a translated string would be easier to handle in code and provide more detailed and helpful information to users.
arejula27 commented 2026-09-25 15:31:51 +00:00 (Migrated from github.com)

@ryanofsky thanks for sharing your opinion!

I don't know if this has been discussed in more depth than the checklist item in #27587 from i took inspiration. @sedited might be able to answer that better. If more discussion is needed, we can keep it here on the PR, or I (or someone else, not sure about the process) can start a thread on the mailing list, whatever works best.

Given the two directions you describe, I was thinking on the 2 when writing the PR.

I think this is less about the dependency itself (despite removing it is a nice win for me), util/translation.h is small, as you say, and more about scope: should the kernel be responsible for producing user-facing output messages at all? The way I see the libbitcoinkernel project (which can be wrong or misunderstood), it is not a module of Core, but a library that uses Core's consensus code and can be used anywhere else, to build any application that needs consensus, not only a node that writes to debug.log. Bark, for example, uses the rust-bitcoinkernel bindings in their test suite (see this tweet), and that kind of consumer is exactly the case where a fixed string is not the right fit. Handing back a string (and I mean any fixed string, not just a bilingual_str) is already an application-level decision (how to log, how to present in a GUI), and the kernel should not be the one making it, it forces the clients to parser the message in case they want to handle it. It also limits the library's own clients: if the kernel ships an already-written message, it pushes the consumer toward the kernel's wording instead of whatever the application wants to say. A structured type does not have that problem, the consumer decides all of it.

On the complexity you are worried about: this set is small and closed. There are 18 cases in total right now, 16 FatalError variants plus 2 FlushError ones, and I do not expect it to grow, these are internal validation/IO failure modes, not an open API surface. It already shrank by one in this branch (FailedToStartIndexes, dropped because it was unreachable from any real kernel consumer).

On your example, "Bad undo data in block {hash} height {height} file {filename}", option (2) does not have to produce a vaguer message. AssumeutxoDataNotFound/SnapshotValidationFailed and similar carry the typed fields needed (a block hash, heights, a path), and the node still builds that exact detailed, translated message (see FatalErrorMessage in kernel_notifications.cpp), nothing is lost. It is true that right now the C API loses that message: it only hands back the numeric code. I was thinking about sending the dynamic part of the error the same way I do for the enum itself, maybe through a union (instead of a variant), but that might push manual maintenance work onto the bindings (that is the reason I did not do it in the first approach, worth a discussion).

On "calling any kernel API means needing to handle a half-dozen error codes": I see that as a positive. Handling the error would be the application's responsibility, and I think that is what lets the kernel stay smaller and closer to consensus, further away from logging or presenting errors. The C API just hands back the numeric code (btck_FatalError); no message is exposed, only the code, the same precedent btck_BlockValidationResult already set. Building anything out of it is entirely up to the consumer. The node (in this repo) is the application that wants the full detailed message, so it is the one place doing an exhaustive std::visit over all the variants (other consumers are free not to be that exhaustive).

All of the above is just my own opinion. As a fairly recent contributor, I am not trying to impose any of this, just making proposals I am happy to change and discuss.

@ryanofsky thanks for sharing your opinion! I don't know if this has been discussed in more depth than the checklist item in #27587 from i took inspiration. @sedited might be able to answer that better. If more discussion is needed, we can keep it here on the PR, or I (or someone else, not sure about the process) can start a thread on the mailing list, whatever works best. Given the two directions you describe, I was thinking on the 2 when writing the PR. I think this is less about the dependency itself (despite removing it is a nice win for me), `util/translation.h` is small, as you say, and more about scope: should the kernel be responsible for producing user-facing output messages at all? The way I see the `libbitcoinkernel` project (which can be wrong or misunderstood), it is not a module of Core, but a library that uses Core's consensus code and can be used anywhere else, to build any application that needs consensus, not only a node that writes to debug.log. Bark, for example, uses the `rust-bitcoinkernel` bindings in their test suite (see this [tweet](https://x.com/matthewvuk2/status/2079991850115756488)), and that kind of consumer is exactly the case where a fixed string is not the right fit. Handing back a string (and I mean any fixed string, not just a `bilingual_str`) is already an application-level decision (how to log, how to present in a GUI), and the kernel should not be the one making it, it forces the clients to parser the message in case they want to handle it. It also limits the library's own clients: if the kernel ships an already-written message, it pushes the consumer toward the kernel's wording instead of whatever the application wants to say. A structured type does not have that problem, the consumer decides all of it. On the complexity you are worried about: this set is small and closed. There are 18 cases in total right now, 16 `FatalError` variants plus 2 `FlushError` ones, and I do not expect it to grow, these are internal validation/IO failure modes, not an open API surface. It already shrank by one in this branch (`FailedToStartIndexes`, dropped because it was unreachable from any real kernel consumer). On your example, "Bad undo data in block {hash} height {height} file {filename}", option (2) does not have to produce a vaguer message. `AssumeutxoDataNotFound`/`SnapshotValidationFailed` and similar carry the typed fields needed (a block hash, heights, a path), and the node still builds that exact detailed, translated message (see `FatalErrorMessage` in `kernel_notifications.cpp`), nothing is lost. It is true that right now the C API loses that message: it only hands back the numeric code. I was thinking about sending the dynamic part of the error the same way I do for the enum itself, maybe through a union (instead of a variant), but that might push manual maintenance work onto the bindings (that is the reason I did not do it in the first approach, worth a discussion). On "calling any kernel API means needing to handle a half-dozen error codes": I see that as a positive. Handling the error would be the application's responsibility, and I think that is what lets the kernel stay smaller and closer to consensus, further away from logging or presenting errors. The C API just hands back the numeric code (`btck_FatalError`); no message is exposed, only the code, the same precedent `btck_BlockValidationResult` already set. Building anything out of it is entirely up to the consumer. The node (in this repo) is the application that wants the full detailed message, so it is the one place doing an exhaustive `std::visit` over all the variants (other consumers are free not to be that exhaustive). All of the above is just my own opinion. As a fairly recent contributor, I am not trying to impose any of this, just making proposals I am happy to change and discuss.
ryanofsky commented 2026-09-25 23:15:00 +00:00 (Migrated from github.com)

Thanks, and I want apologize because my last comment was just based on an initial reaction and not very constructive.

I do agree with the direction of the PR and approach of adding structured error types in a src/kernel/error.h file. Right now kernel functions don't return enough structured error information and they should return more.

I just want to caution against trying to use types intended for error handling for error reporting as well, because the goals of error handling and error reporting are different. For error handling you generally want fewer branching cases to avoid code complexity and bugs, while for error reporting you usually want more detail. I was also just surprised to see the goal of removing the translation header because it is so small and it was unclear what benefits that removal would bring.

Overall direction of the PR seems good, but would maybe just want to clarify the goals a little more. I think there are a number of problems worth addressing in the error handling area, the main ones being that errors are returned by callback instead of return value, which makes them difficult to handle, and that we don't have good error type, and to extend we do there is no type safety so a function that can actually only return 3 errors looks like it returns 15 errors and caller have to deal with unnecessary ambiguity and mess.

But looking at actual changes in this PR they seem reasonable, and like something that could be built on to fix other problems. The one thing I would change is that it seems like btck_NotifyFatalError and btck_NotifyFlushError are losing all details about errors that occur because messages are being replaced by codes. This seems like it could cause real harm to kernel applications because there could be no clean way to extract and present error information to users. But could be fixed by keeping the error messages and adding the codes instead of replacing the messages with codes

Thanks, and I want apologize because my last comment was just based on an initial reaction and not very constructive. I do agree with the direction of the PR and approach of adding structured error types in a [src/kernel/error.h](https://github.com/arejula27/bitcoin/blob/1d66b88dcd0f4608ea151d306547f41a56f29d26/src/kernel/error.h) file. Right now kernel functions don't return enough structured error information and they should return more. I just want to caution against trying to use types intended for error handling for error reporting as well, because the goals of error handling and error reporting are different. For error handling you generally want fewer branching cases to avoid code complexity and bugs, while for error reporting you usually want more detail. I was also just surprised to see the goal of removing the translation header because it is so small and it was unclear what benefits that removal would bring. Overall direction of the PR seems good, but would maybe just want to clarify the goals a little more. I think there are a number of problems worth addressing in the error handling area, the main ones being that errors are returned by callback instead of return value, which makes them difficult to handle, and that we don't have good error type, and to extend we do there is no type safety so a function that can actually only return 3 errors looks like it returns 15 errors and caller have to deal with unnecessary ambiguity and mess. But looking at actual changes in this PR they seem reasonable, and like something that could be built on to fix other problems. The one thing I would change is that it seems like btck_NotifyFatalError and btck_NotifyFlushError are losing all details about errors that occur because messages are being replaced by codes. This seems like it could cause real harm to kernel applications because there could be no clean way to extract and present error information to users. But could be fixed by keeping the error messages and adding the codes instead of replacing the messages with codes
arejula27 commented 2026-09-26 12:18:26 +00:00 (Migrated from github.com)

Appreciate that, @ryanofsky. I have updated the PR description, hope it is what you wanted.

I would also like to recommend reviewers take a look at #35646 (I just left a review there): although DrahtBot does not flag it as a conflict, both PRs define a kernel::FatalError type with the same name but different goal and the main purpose of the PR is other.

Appreciate that, @ryanofsky. I have updated the PR description, hope it is what you wanted. I would also like to recommend reviewers take a look at #35646 (I just left a review there): although DrahtBot does not flag it as a conflict, both PRs define a `kernel::FatalError` type with the same name but different goal and the main purpose of the PR is other.
DrahtBot commented 2026-09-29 19:09:19 +00:00 (Migrated from github.com)

Could turn into draft while CI is red?

Could turn into draft while CI is red?
First-time contributor

Base: aa76bd266df9742a266d52e0e5da8dbf033658f6
Head: 8a5934f7d28204270c56f445519c6f66259c1df8

Findings

[Minor] Preserve snapshot-validation details in the kernel log

The kernel log no longer records why snapshot validation failed or the heights involved, particularly affecting libbitcoinkernel users.

Explanation and suggested change

Previously, the kernel logged the full snapshot-validation message, including the reset from height_from to height_to. It now logs only that it is deleting the snapshot, reverting to the validated chain, and stopping the node; the heights are available only in kernel::SnapshotValidationFailed. bitcoind still records node-rendered text through AbortNode and InitError, but a libbitcoinkernel consumer gets only SNAPSHOT_VALIDATION_FAILED and no details in its log callback. Add an untranslated kernel log line that records the height range. Also update the InvalidateCoinsDBOnDisk() comment saying the user is instructed in MaybeValidateSnapshot(), since the instruction now comes from the node's message.

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

Previous reports

First reported at 8a5934f7d28204270c56f445519c6f66259c1df8. Last checked at 8a5934f7d28204270c56f445519c6f66259c1df8.

[Suggestion] Make fatal-error rendering exhaustive

Current callers are covered, but a future fatal error could compile and silently produce an empty reject reason.

Explanation and suggested change

FatalError() accepts any kernel::FatalError and passes FatalErrorString(error) to state.Error(). The string function checks eight alternatives, then returns an empty string. All current state-setting callers use one of those alternatives, so this does not affect them. But a future caller could pass another variant, such as BlockWriteFailed, and silently set an empty reject reason shown by submitblock or submitheader; the hand-maintained test list would not catch it. Narrow the parameter to a variant containing only state-reported errors and render it with an exhaustive std::visit.

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

Design and approach

[Minor] Preserve dynamic fatal-error details for C API consumers

C API callbacks lose error messages, and several errors' details are not logged elsewhere, leaving consumers without information to diagnose them.

Explanation and suggested change

fatalError() forwards only the error category to the C callback. Although the fields do not cross the C API, several errors are also not logged before notification: the external block-file exception text, the chainstate name and validation reason in ActivateBestChainsFailed, and the block hash in AssumeutxoDataNotFound. A caller of btck_chainstate_manager_import_blocks that encounters an I/O or activation failure therefore sees only a category, with no details in its log callback. Until the C API carries these fields, log the variants' dynamic details in the btck adapter's fatalError() or at the raise sites, using untranslated messages to avoid a translation dependency.

Location: src/kernel/bitcoinkernel.cpp:368 (head).

Previous reports

Previous reports of the same concern:

  • src/kernel/bitcoinkernel.h:412. First reported at 1d66b88dcd0f4608ea151d306547f41a56f29d26. Last checked at 8a5934f7d28204270c56f445519c6f66259c1df8. The author plans to address this separately. Author reply 2026-09-25T15:32:32Z
  • src/kernel/bitcoinkernel.h:485. First reported at 8a5934f7d28204270c56f445519c6f66259c1df8. Last checked at 8a5934f7d28204270c56f445519c6f66259c1df8. The author plans to address this separately. Author reply 2026-09-25T15:32:32Z

Previously reported concerns remain unresolved: 1 minor.

Previous findings
[Minor · still present] Cast error codes to an integer before printing

The demo and test harness print control characters instead of readable fatal and flush error codes.

The error enums have uint8_t underlying types, so streaming their underlying values selects the unsigned char overload and prints characters rather than numbers. For example, DISK_SPACE_TOO_LOW prints BEL instead of 7, while flush errors print NUL or SOH. This makes the diagnostic output uninformative. Cast to unsigned int before streaming in all four handlers, including the matching handlers in src/test/kernel/test_kernel.cpp.

Location: src/bitcoin-chainstate.cpp:143 (head).

Previous reports of the same concern:

  • src/bitcoin-chainstate.cpp:135. First reported at 1d66b88dcd0f4608ea151d306547f41a56f29d26. Last checked at 8a5934f7d28204270c56f445519c6f66259c1df8.
  • src/bitcoin-chainstate.cpp:143. First reported at 8a5934f7d28204270c56f445519c6f66259c1df8. Last checked at 8a5934f7d28204270c56f445519c6f66259c1df8.

Review coverage was incomplete.

Review limitations
  • verifier: I did not trace bitcoin-qt's InitError and message-box path all the way to debug.log. The snapshot-logging finding therefore states its impact with certainty only for libbitcoinkernel consumers.

Review tier: sensitive

Full review report

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:ab973404fb8e3c0d560a5f0df76c1f96a2e0e21182cfc208ac10a039068cb623:00633cd9cb08c8f4661c30fbf00eaba6318f037423dd36deda26cc4a9d01c2c2 --> Base: `aa76bd266df9742a266d52e0e5da8dbf033658f6` Head: `8a5934f7d28204270c56f445519c6f66259c1df8` <!-- ralph-case:2823ddf35eea650d94ff14f3dd1e2f9c17daa066f6e298f3d2db00db50ab216d --> ##### Findings **[Minor] Preserve snapshot-validation details in the kernel log** The kernel log no longer records why snapshot validation failed or the heights involved, particularly affecting libbitcoinkernel users. <details> <summary>Explanation and suggested change</summary> Previously, the kernel logged the full snapshot-validation message, including the reset from `height_from` to `height_to`. It now logs only that it is deleting the snapshot, reverting to the validated chain, and stopping the node; the heights are available only in `kernel::SnapshotValidationFailed`. bitcoind still records node-rendered text through `AbortNode` and `InitError`, but a libbitcoinkernel consumer gets only `SNAPSHOT_VALIDATION_FAILED` and no details in its log callback. Add an untranslated kernel log line that records the height range. Also update the `InvalidateCoinsDBOnDisk()` comment saying the user is instructed in `MaybeValidateSnapshot()`, since the instruction now comes from the node's message. Location: `src/validation.cpp:6025` (head). </details> <details> <summary>Previous reports</summary> First reported at `8a5934f7d28204270c56f445519c6f66259c1df8`. Last checked at `8a5934f7d28204270c56f445519c6f66259c1df8`. </details> **[Suggestion] Make fatal-error rendering exhaustive** Current callers are covered, but a future fatal error could compile and silently produce an empty reject reason. <details> <summary>Explanation and suggested change</summary> `FatalError()` accepts any `kernel::FatalError` and passes `FatalErrorString(error)` to `state.Error()`. The string function checks eight alternatives, then returns an empty string. All current state-setting callers use one of those alternatives, so this does not affect them. But a future caller could pass another variant, such as `BlockWriteFailed`, and silently set an empty reject reason shown by `submitblock` or `submitheader`; the hand-maintained test list would not catch it. Narrow the parameter to a variant containing only state-reported errors and render it with an exhaustive `std::visit`. Location: `src/validation.cpp:2147` (head). </details> ##### Design and approach **[Minor] Preserve dynamic fatal-error details for C API consumers** C API callbacks lose error messages, and several errors' details are not logged elsewhere, leaving consumers without information to diagnose them. <details> <summary>Explanation and suggested change</summary> `fatalError()` forwards only the error category to the C callback. Although the fields do not cross the C API, several errors are also not logged before notification: the external block-file exception text, the chainstate name and validation reason in `ActivateBestChainsFailed`, and the block hash in `AssumeutxoDataNotFound`. A caller of `btck_chainstate_manager_import_blocks` that encounters an I/O or activation failure therefore sees only a category, with no details in its log callback. Until the C API carries these fields, log the variants' dynamic details in the btck adapter's `fatalError()` or at the raise sites, using untranslated messages to avoid a translation dependency. Location: `src/kernel/bitcoinkernel.cpp:368` (head). </details> <details> <summary>Previous reports</summary> Previous reports of the same concern: - src/kernel/bitcoinkernel.h:412. First reported at `1d66b88dcd0f4608ea151d306547f41a56f29d26`. Last checked at `8a5934f7d28204270c56f445519c6f66259c1df8`. The author plans to address this separately. [Author reply](https://github.com/bitcoin/bitcoin/pull/36326#issuecomment-5835018112) 2026-09-25T15:32:32Z - src/kernel/bitcoinkernel.h:485. First reported at `8a5934f7d28204270c56f445519c6f66259c1df8`. Last checked at `8a5934f7d28204270c56f445519c6f66259c1df8`. The author plans to address this separately. [Author reply](https://github.com/bitcoin/bitcoin/pull/36326#issuecomment-5835018112) 2026-09-25T15:32:32Z </details> Previously reported concerns remain unresolved: 1 minor. ##### Previous findings <details> <summary>[Minor · still present] Cast error codes to an integer before printing</summary> The demo and test harness print control characters instead of readable fatal and flush error codes. The error enums have `uint8_t` underlying types, so streaming their underlying values selects the `unsigned char` overload and prints characters rather than numbers. For example, `DISK_SPACE_TOO_LOW` prints BEL instead of `7`, while flush errors print NUL or SOH. This makes the diagnostic output uninformative. Cast to `unsigned int` before streaming in all four handlers, including the matching handlers in `src/test/kernel/test_kernel.cpp`. Location: `src/bitcoin-chainstate.cpp:143` (head). Previous reports of the same concern: - src/bitcoin-chainstate.cpp:135. First reported at `1d66b88dcd0f4608ea151d306547f41a56f29d26`. Last checked at `8a5934f7d28204270c56f445519c6f66259c1df8`. - src/bitcoin-chainstate.cpp:143. First reported at `8a5934f7d28204270c56f445519c6f66259c1df8`. Last checked at `8a5934f7d28204270c56f445519c6f66259c1df8`. </details> Review coverage was incomplete. ##### Review limitations - verifier: I did not trace bitcoin-qt's InitError and message-box path all the way to debug.log. The snapshot-logging finding therefore states its impact with certainty only for libbitcoinkernel consumers. Review tier: sensitive [Full review report](<https://review.fish.foo/traces/36326-8a5934f7d28204270c56f445519c6f66259c1df8-1538-3.html>)
DrahtBot commented 2026-10-08 16:12:53 +00:00 (Migrated from github.com)

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

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
yuvicc (Migrated from github.com) reviewed 2026-10-09 07:50:26 +00:00
yuvicc (Migrated from github.com) left a comment

Concept ACK

I haven’t looked into this in depth yet. I’ll try to review it more closely alongside https://github.com/bitcoin/bitcoin/pull/35646. Meanwhile, I've left some nits.

Concept ACK I haven’t looked into this in depth yet. I’ll try to review it more closely alongside https://github.com/bitcoin/bitcoin/pull/35646. Meanwhile, I've left some nits.
yuvicc (Migrated from github.com) commented 2026-10-09 05:26:23 +00:00

can be marked constexpr & named to_btck to match naming convention?

can be marked `constexpr` & named `to_btck` to match naming convention?
yuvicc (Migrated from github.com) commented 2026-10-09 05:26:47 +00:00

Same here! See comment

Same here! See [comment](https://github.com/bitcoin/bitcoin/pull/36326/changes/cdd475770652dbbc2e9c292281c0670ea42a686f#r4226909227)
yuvicc (Migrated from github.com) commented 2026-10-09 05:30:23 +00:00

I think with this change this method reduces each variant to an error code losing the error details (block hash, paths, snapshot recovery info). For e.g. SystemErrorWhileSavingBlock now reports only SYSTEM_ERROR_WHILE_SAVING_BLOCK consumers cannot reconstruct the underlying cause from the callback.

Maybe exposing through some error object could be a way, not sure though!

I think with this change this method reduces each variant to an error code losing the error details (block hash, paths, snapshot recovery info). For e.g. `SystemErrorWhileSavingBlock` now reports only `SYSTEM_ERROR_WHILE_SAVING_BLOCK` consumers cannot reconstruct the underlying cause from the callback. Maybe exposing through some error object could be a way, not sure though!
yuvicc (Migrated from github.com) commented 2026-10-09 05:11:33 +00:00

af5ed188f1 commit message can be more descriptive.

af5ed188f16f749a431772e7d4253e0f4f20b9b2 commit message can be more descriptive.
yuvicc (Migrated from github.com) commented 2026-10-09 06:12:10 +00:00

should come before key_io_tests.cpp?

should come before `key_io_tests.cpp`?
yuvicc (Migrated from github.com) commented 2026-10-09 06:01:08 +00:00

This can now return an empty string if the variant isn’t one of the listed types, which wasn’t possible before. In practice, though, every caller passes one of the listed types.

This can now return an empty string if the variant isn’t one of the listed types, which wasn’t possible before. In practice, though, every caller passes one of the listed types.
Yudis-bit commented 2026-10-11 09:41:29 +00:00 (Migrated from github.com)

FatalErrorString in src/validation.cpp returns {} for the eight variants that are only routed through Notifications::fatalError(). Having an Assume(false) before the fallthrough return {}; would catch any accidental use of those variants in FatalError(notifications, state, ...) in debug builds, preventing BlockValidationState::Error() from silently absorbing an empty reject reason.

For btck_NotifyFatalError, passing both the code and the formatted message would mirror btck_NotifyWarningSet, which already supplies both btck_Warning warning and (const char* message, size_t message_len). That preserves programmatic dispatch for C consumers without dropping dynamic details like paths or block hashes.

FatalErrorString in src/validation.cpp returns {} for the eight variants that are only routed through Notifications::fatalError(). Having an Assume(false) before the fallthrough return {}; would catch any accidental use of those variants in FatalError(notifications, state, ...) in debug builds, preventing BlockValidationState::Error() from silently absorbing an empty reject reason. For btck_NotifyFatalError, passing both the code and the formatted message would mirror btck_NotifyWarningSet, which already supplies both btck_Warning warning and (const char* message, size_t message_len). That preserves programmatic dispatch for C consumers without dropping dynamic details like paths or block hashes.
pzafonte (Migrated from github.com) reviewed 2026-11-20 20:03:04 +00:00
pzafonte (Migrated from github.com) left a comment

Concept ACK and code reviewed 8a5934f7d2 commit by commit.

Concept ACK and code reviewed 8a5934f7d28204270c56f445519c6f66259c1df8 commit by commit.
pzafonte (Migrated from github.com) commented 2026-11-20 19:26:31 +00:00

Also the heights are also gone from the kernel's log. Because cdd4757 drops the [snapshot] !!! LogError in handle_invalid_snapshot so then after a hash mismatch C API users can't get either height from the callback or the log.

Could the kernel keep a plain log line with them? Something like LogError("[snapshot] validation failed, resetting chain height from %d to %d", ...), similar to the assumeutxo data not found for height (%d) warning just below. Which would be diagnostic rather than user-facing, so it shouldn't need _().

To check, I added ASSERT_DEBUG_LOG("[snapshot] !!!") to chainstatemanager_snapshot_completion_hash_mismatch. The test passes on f739c78 and 54bc6a5 and fails on 8a5934f.

Also the heights are also gone from the kernel's log. Because cdd4757 drops the `[snapshot] !!!` LogError in `handle_invalid_snapshot` so then after a hash mismatch C API users can't get either height from the callback or the log. Could the kernel keep a plain log line with them? Something like `LogError("[snapshot] validation failed, resetting chain height from %d to %d", ...)`, similar to the `assumeutxo data not found for height (%d)` warning just below. Which would be diagnostic rather than user-facing, so it shouldn't need `_()`. To check, I added `ASSERT_DEBUG_LOG("[snapshot] !!!")` to `chainstatemanager_snapshot_completion_hash_mismatch`. The test passes on f739c78 and 54bc6a5 and fails on 8a5934f.
pzafonte (Migrated from github.com) commented 2026-11-20 19:52:39 +00:00

Could 6daa91c and the init.cpp change here go before af5ed18? Then FailedToStartIndexes is never added and codes 9 to 16 keep their values, as the "appended, never inserted" doc comment from cdd4757 says.

8a5934f could likewise be folded into cdd4757, since it restores the translation that cdd4757 drops from the rename message.

nit: If you keep this commit: the message says init calls AbortNode() directly, but it goes through KernelNotifications::abort().

Could 6daa91c and the init.cpp change here go before af5ed18? Then `FailedToStartIndexes` is never added and codes 9 to 16 keep their values, as the "appended, never inserted" doc comment from cdd4757 says. 8a5934f could likewise be folded into cdd4757, since it restores the translation that cdd4757 drops from the rename message. nit: If you keep this commit: the message says init calls `AbortNode()` directly, but it goes through `KernelNotifications::abort()`.
pzafonte (Migrated from github.com) commented 2026-11-20 19:01:04 +00:00

Genuinely curious, would it make sense to add a test_kernel case for it? Destroying the chainman triggers a flush, and replacing blocks/blk00000.dat (or rev00000.dat) with a directory is enough to make that flush fail. I ran it on 8a5934f and the handler got BLOCK_FILE_FLUSH_FAILED (0) and UNDO_FILE_FLUSH_FAILED (1).

test_kernel.cpp diff
+class FlushErrorRecorder : public TestKernelNotifications
+{
+public:
+    std::vector<FlushError> m_errors;
+    void FlushErrorHandler(FlushError error) override { m_errors.push_back(error); }
+};
+
+static std::vector<FlushError> DestroyWithUnopenableFile(const std::string& name, const std::string& file)
+{
+    auto test_directory{TestDirectory{name}};
+    auto notifications{std::make_shared<FlushErrorRecorder>()};
+    auto context{create_context(notifications, ChainType::REGTEST)};
+    auto chainman{create_chainman(
+        test_directory, /*reindex=*/false, /*wipe_chainstate=*/false,
+        /*block_tree_db_in_memory=*/true, /*chainstate_db_in_memory=*/true, context)};
+    for (size_t i{0}; i < 3; i++) {
+        Block block{hex_string_to_byte_vec(REGTEST_BLOCK_DATA[i])};
+        bool new_block{false};
+        chainman->ProcessBlock(block, &new_block);
+        BOOST_REQUIRE(new_block);
+    }
+    const fs::path path{test_directory.m_directory / "blocks" / fs::u8path(file)};
+    BOOST_REQUIRE(fs::exists(path));
+    fs::rename(path, path + ".moved");
+    BOOST_REQUIRE(fs::create_directory(path));
+    BOOST_REQUIRE(notifications->m_errors.empty());
+    chainman.reset();
+    return notifications->m_errors;
+}
+
+static int RawValue(FlushError error) { return int{static_cast<std::underlying_type_t<FlushError>>(error)}; }
+
+BOOST_AUTO_TEST_CASE(btck_flush_error_block_file)
+{
+    const auto errors{DestroyWithUnopenableFile("flush_error_block_file", "blk00000.dat")};
+    BOOST_REQUIRE_EQUAL(errors.size(), 1U);
+    BOOST_CHECK(errors[0] == FlushError::BLOCK_FILE_FLUSH_FAILED);
+    BOOST_CHECK_EQUAL(RawValue(errors[0]), 0);
+}
+
+BOOST_AUTO_TEST_CASE(btck_flush_error_undo_file)
+{
+    const auto errors{DestroyWithUnopenableFile("flush_error_undo_file", "rev00000.dat")};
+    BOOST_REQUIRE_EQUAL(errors.size(), 1U);
+    BOOST_CHECK(errors[0] == FlushError::UNDO_FILE_FLUSH_FAILED);
+    BOOST_CHECK_EQUAL(RawValue(errors[0]), 1);
+}
Genuinely curious, would it make sense to add a test_kernel case for it? Destroying the chainman triggers a flush, and replacing `blocks/blk00000.dat` (or `rev00000.dat`) with a directory is enough to make that flush fail. I ran it on 8a5934f and the handler got `BLOCK_FILE_FLUSH_FAILED` (0) and `UNDO_FILE_FLUSH_FAILED` (1). <details> <summary>test_kernel.cpp diff</summary> ```diff +class FlushErrorRecorder : public TestKernelNotifications +{ +public: + std::vector<FlushError> m_errors; + void FlushErrorHandler(FlushError error) override { m_errors.push_back(error); } +}; + +static std::vector<FlushError> DestroyWithUnopenableFile(const std::string& name, const std::string& file) +{ + auto test_directory{TestDirectory{name}}; + auto notifications{std::make_shared<FlushErrorRecorder>()}; + auto context{create_context(notifications, ChainType::REGTEST)}; + auto chainman{create_chainman( + test_directory, /*reindex=*/false, /*wipe_chainstate=*/false, + /*block_tree_db_in_memory=*/true, /*chainstate_db_in_memory=*/true, context)}; + for (size_t i{0}; i < 3; i++) { + Block block{hex_string_to_byte_vec(REGTEST_BLOCK_DATA[i])}; + bool new_block{false}; + chainman->ProcessBlock(block, &new_block); + BOOST_REQUIRE(new_block); + } + const fs::path path{test_directory.m_directory / "blocks" / fs::u8path(file)}; + BOOST_REQUIRE(fs::exists(path)); + fs::rename(path, path + ".moved"); + BOOST_REQUIRE(fs::create_directory(path)); + BOOST_REQUIRE(notifications->m_errors.empty()); + chainman.reset(); + return notifications->m_errors; +} + +static int RawValue(FlushError error) { return int{static_cast<std::underlying_type_t<FlushError>>(error)}; } + +BOOST_AUTO_TEST_CASE(btck_flush_error_block_file) +{ + const auto errors{DestroyWithUnopenableFile("flush_error_block_file", "blk00000.dat")}; + BOOST_REQUIRE_EQUAL(errors.size(), 1U); + BOOST_CHECK(errors[0] == FlushError::BLOCK_FILE_FLUSH_FAILED); + BOOST_CHECK_EQUAL(RawValue(errors[0]), 0); +} + +BOOST_AUTO_TEST_CASE(btck_flush_error_undo_file) +{ + const auto errors{DestroyWithUnopenableFile("flush_error_undo_file", "rev00000.dat")}; + BOOST_REQUIRE_EQUAL(errors.size(), 1U); + BOOST_CHECK(errors[0] == FlushError::UNDO_FILE_FLUSH_FAILED); + BOOST_CHECK_EQUAL(RawValue(errors[0]), 1); +} ```
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!36326
No description provided.