Skip to content

kernel: Introduce C header API - #30595

Merged
fanquake merged 23 commits into
bitcoin:masterfrom
sedited:kernelApi
Nov 4, 2025
Merged

kernel: Introduce C header API#30595
fanquake merged 23 commits into
bitcoin:masterfrom
sedited:kernelApi

Conversation

@sedited

@sedited sedited commented Aug 6, 2024

Copy link
Copy Markdown
Contributor

This is a first attempt at introducing a C header for the libbitcoinkernel library that may be used by external applications for interfacing with Bitcoin Core's validation logic. It currently is limited to operations on blocks. This is a conscious choice, since it already offers a lot of powerful functionality, but sits just on the cusp of still being reviewable scope-wise while giving some pointers on how the rest of the API could look like.

The current design was informed by the development of some tools using the C header:

The library has also been used by other developers already:

Next to the C++ header also made available in this pull request, bindings for other languages are available here:

The rust bindings include unit and fuzz tests for the API.

The header currently exposes logic for enabling the following functionality:

  • Feature-parity with the now deprecated libbitcoin-consensus
  • Optimized sha256 implementations that were not available to previous users of libbitcoin-consensus thanks to a static kernel context
  • Full support for logging as well as control over categories and severity
  • Feature parity with the existing experimental bitcoin-chainstate
  • Traversing the block index as well as using block index entries for reading block and undo data.
  • Running the chainstate in memory
  • Reindexing (both full and chainstate-only)
  • Interrupting long-running functions

The pull request introduces a new kernel-only test binary that purely relies on the kernel C header and the C++ standard library. This is intentionally done to show its capabilities without relying on other code inside the project. This may be relaxed to include some of the existing utilities, or even be merged into the existing test suite.

The complete docs for the API as well as some usage examples are hosted on thecharlatan.ch/kernel-docs. The docs are generated from the following repository (which also holds the examples): github.com/TheCharlatan/kernel-docs.

How can I review this PR?

Scrutinize the commit messages, run the tests, write your own little applications using the library, let your favorite code sanitizer loose on it, hook it up to your fuzzing infrastructure, profile the difference between the existing bitcoin-chainstate and the bitcoin-chainstate introduced here, be nitty on the documentation, police the C interface, opine on your own API design philosophy.

To get a feeling for the API, read through the tests, or one of the examples.

To configure this PR for making the shared library and the bitcoin-chainstate and test_kernel utilities available:

cmake -B build -DBUILD_KERNEL_LIB=ON -DBUILD_UTIL_CHAINSTATE=ON

Once compiled the library is part of the build artifacts that can be installed with:

cmake --install build

Why a C header (and not a C++ header)

  • Shipping a shared library with a C++ header is hard, because of name mangling and an unstable ABI.
  • Mature and well-supported tooling for integrating C exists for nearly every popular language.
  • C offers a reasonably stable ABI

Also see #30595 (comment).

What about versioning?

The header and library are still experimental and I would expect this to remain so for some time, so best not to worry about versioning yet.

Potential future additions

In future, the C header could be expanded to support (some of these have been roughly implemented):

  • Handling transactions, block headers, coins cache, utxo set, meta data, and the mempool
  • Adapters for an abstract coins store
  • Adapters for an abstract block store
  • Adapters for an abstract block tree store
  • Allocators and buffers for more efficient memory usage
  • An "io-less" interface
  • Hooks for an external mempool, or external policy rules

Current drawbacks

  • For external applications to read the block index of an existing Bitcoin Core node, Bitcoin Core needs to shut down first, since leveldb does not support reading across multiple processes. Other than migrating away from leveldb, there does not seem to be a solution for this problem. Such a migration is implemented in kernel: Replace leveldb-based BlockTreeDB with WAL and .dat file based store #32427.
  • The fatal error handling through the notifications is awkward. This is partly improved through kernel: Handle fatal errors through return values #29642.
  • Handling shared pointers in the interfaces is unfortunate. They make ownership and freeing of the resources fuzzy and poison the interfaces with additional types and complexity. However, they seem to be an artifact of the current code that interfaces with the validation engine. The validation engine itself does not seem to make extensive use of these shared pointers.
  • If multiple instances of the same type of objects are used, there is no mechanism for distinguishing the log messages produced by each of them. A potential solution is kernel, logging: Pass Logger instances to kernel objects #30342.
  • The background leveldb compaction thread may not finish in time leading to a non-clean exit. There seems to be nothing we can do about this, outside of patching leveldb.

@DrahtBot

DrahtBot commented Aug 6, 2024

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

Code Coverage & Benchmarks

For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/30595.

Reviews

See the guideline for information on the review process.

Type Reviewers
ACK alexanderwiederin, stringintech, laanwj, ismaelsadeeq, fanquake
Concept ACK stickies-v
Approach ACK w0xlt, yuvicc
Approach NACK purpleKarrot
User requested bot ignore josibake

If your review is incorrectly listed, please react with 👎 to this comment and the bot will ignore it on the next update.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #33728 (test: Add bitcoin-chainstate test for assumeutxo functionality by stringintech)
  • #33680 (validation: do not wipe utxo cache for stats/scans/snapshots by l0rinc)
  • #33455 (CPack by purpleKarrot)
  • #33247 (build: Remove CMAKE_SKIP_BUILD_RPATH and SKIP_BUILD_RPATH settings by 151henry151)
  • #33191 (net: Provide block templates to peers on request by ajtowns)
  • #32953 ([POC] ci: Skip compilation when running static code analysis by hebasto)
  • #32427 ((RFC) kernel: Replace leveldb-based BlockTreeDB with flat-file based store by TheCharlatan)
  • #31507 (build: Use clang-cl to build on Windows natively by hebasto)
  • #31382 (kernel: Flush in ChainstateManager destructor by TheCharlatan)
  • #30437 (ipc: add bitcoin-mine test program by ryanofsky)
  • #30214 (refactor: Improve assumeutxo state representation by ryanofsky)
  • #29415 (Broadcast own transactions only via short-lived Tor or I2P connections by vasild)
  • #28792 (Embed default ASMap as binary dump header file by fjahr)
  • #26022 (Add util::ResultPtr class by ryanofsky)
  • #25722 (refactor: Use util::Result class for wallet loading by ryanofsky)
  • #25665 (refactor: Add util::Result failure values, multiple error and warning messages by ryanofsky)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

LLM Linter (✨ experimental)

Possible typos and grammar issues:

  • A un-recoverable system error encountered by the library. -> An unrecoverable system error encountered by the library. [“A” before a vowel sound should be “An”; “un-recoverable” is more commonly written “unrecoverable” — the revised phrase is grammatical and clearer.]

drahtbot_id_5_m

@DrahtBot

DrahtBot commented Aug 6, 2024

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Debug: https://github.com/bitcoin/bitcoin/runs/28396412371

Hints

Make sure to run all tests locally, according to the documentation.

The failure may 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.

@theuni

theuni commented Aug 7, 2024

Copy link
Copy Markdown
Member

Very cool. Can't wait to dig in when I have some free time.

@ryanofsky

Copy link
Copy Markdown
Contributor

This seems to offer a lot of nice features, but can you explain the tradeoffs of wrapping the C++ interface in C instead of using C++ from rust directly? It seems like having a C middle layer introduces a lot of boilerplate, and I'm wondering if it is really necessary. For example it seems like there is a rust cxx crate (https://docs.rs/cxx/latest/cxx/, https://chatgpt.com/share/dd4dde59-66d6-4486-88a6-2f42144be056) that lets you call C++ directly from Rust and avoid the need for C boilerplate. It looks like https://cppyy.readthedocs.io/en/latest/index.html is an even more full-featured way of calling c++ from python.

Another drawback of going through a C API seems like not just increased boilerplate, but reduced safety. For example, the implementation is using reinterpret_cast everywhere and it seems like the exposed C functions use a kernel_ErrorCode enum type with the union of every possible error type, so callers don't have a way to know which functions can return which errors.

@sedited

sedited commented Aug 13, 2024

Copy link
Copy Markdown
Contributor Author

Thank you for the questions and kicking this discussion off @ryanofsky! I'll update the PR description with a better motiviation re. C vs C++ header, but will also try to answer your questions here.

This seems to offer a lot of nice features, but can you explain the tradeoffs of wrapping the C++ interface in C instead of using C++ from rust directly? It seems like having a C middle layer introduces a lot of boilerplate, and I'm wondering if it is really necessary. For example it seems like there is a rust cxx crate (https://docs.rs/cxx/latest/cxx/, https://chatgpt.com/share/dd4dde59-66d6-4486-88a6-2f42144be056) that lets you call C++ directly from Rust and avoid the need for C boilerplate. It looks like https://cppyy.readthedocs.io/en/latest/index.html is an even more full-featured way of calling c++ from python.

It is true that the interoperability between C++ and Rust has become very good. In fact there is someone working on wrapping the entirety of Bitcoin Core in Rust: https://github.com/klebs6/bitcoin-rs.

During the last Core Dev meeting in Berlin I also asked if a C API were desirable in the first place (notes here) during the libbitcoinkernel session. I moved forward with this implementation, because the consensus at the time with many contributors in the room was that it was desirable. The reasons for this as discussed during the session at the meeting can be briefly summarised:

  • Shipping a shared library with a C++ header is hard
  • Mature and well-supported tooling for integrating C exists for nearly every popular language.
  • C offers a reasonably stable ABI

So if we want the broadest possible support, across as many languages as possible with both dynamic and statically compiled libraries, a C header is the go-to option. I'm speculating here, but a C++ header might also make future standard version bumps and adoption of new standard library features harder. If having some trade-offs with compatibility, library portability, and language support is acceptable, a C++ header might be acceptaple though. It would be nice to hear more reviewers give their opinions here.

I'd also like to add that two libraries that we use and depend on in this project, minisketch and zeromq, use the same pattern. They are C++ codebases, that only expose a C API that in both instances can be used with a C++ RAII wrapper. So there is precedent in the free software ecosystem for doing things this way.

The quality of C++ language interop seems to vary a lot between languages. Python and Rust seem to have decent support, ziglang on the other hand has no support for C++ bindings. JVM family languages are a bit hit and miss, and many of the common academic and industrial data analysis languages, like Julia, R, and Matlab have no support for direct C++ bindings. The latter category should not be disregarded as potential future users, since this library might be useful to access Bitcoin Core data for data analysis projects.

Another drawback of going through a C API seems like not just increased boilerplate, but reduced safety. For example, the implementation is using reinterpret_cast everywhere

I feel like the reduced type safety due to casting is bit of a red herring. The type casting can be harder to abuse if you always use a dedicated helper function for interpreting passed in data types (as I believe is implemented here). Casting is also a pattern used in many other projects; both minisketch and libzmq use similar type casts extensively. It should definitely be possible to scrutinize the API in this PR to a point where it offers decent safety to its users as well as contributors to and maintainers of this code base.

The concerns around boilerplate are more serious in my view, but at least with the current internal code and headers I feel like exposing a safe C++ API is not trivial either. The current headers do not lend themselves to it well, for example through tricky locking mechanics, exposing boost types, or confusing lifetimes. There also comes a point where we should probably stop extensively refactoring internal code for the kernel. I've heard some voices during the last two Core Dev meetings with concerns that the kernel project might turn the validation code into an extensive forever building site. Having some boilerplate and glue to abstract some the ugliness and make it safe seems like an acceptable solution for this dilemma. If this means boilerplate is required anyway, I would personally prefer a C API.

Some of the boilerplate-y duplicate definitions in the header could be dropped again eventually if some of the enums are moved to C-style enums instead of class enum. As long as they are properly namespaced, I don't see a big drawback for this. Similarly, some of the structs could be defined in a way where they can be used on both sides using pimpl or similar idioms. All in all, most of these translations seem very straightforward.

It might be interesting to see how some of the RPC methods could be re-implemented using the kernel header. There have been some RPC implementation bugs over the years that were due to unsafe usage of our internal code within the method implementations. Using the kernel header instead might make this safer and reduce boilerplate. To be clear, I am not suggesting replacing the implementations, but separately re-implementing some of them to show where the kernel header might shine.

it seems like the exposed C functions use a kernel_ErrorCode enum type with the union of every possible error type, so callers don't have a way to know which functions can return which errors.

We have disagreed on the design of this before. If I understood you correctly, consolidating all error codes into a single enumeration was one of the reasons you opened your version for handling fatal errors in the kernel: #29700 as an alternative to my original: #29642. I am still a bit torn by the two approaches. I get that it may be useful to exactly see which errors may be encountered by invoking a certain routine, but at the same time I get the feeling this often ends up splintering the error handling to the point where you end up with a catch all approach after all. I also think that it is nice to have a single, central list for looking up all error codes and defining some routines for handling them in close proximity to their definition. It would be nice to finally hear some more voices besides the two of us discussing this. real-or-random has recently provided some good points on error handling in the libsecp silent payments pr (that I mostly did not adopt in this PR) and argues that most error codes are not useful to the user. As mentioned in the description, error handling is a weak spot of this pull request and I would like to improve it.

@ryanofsky

ryanofsky commented Aug 13, 2024

Copy link
Copy Markdown
Contributor

I guess another thing I'd like to know is if this is the initial C API, and the implementation is around 3000 lines, and it doesn't handle "transactions, block headers, coins cache, utxo set, meta data, and the mempool", how much bigger do you think it will get if it does cover most of the things you would like it to cover? Like is this 20%, 30%, or 50% of the expected size?

I like the idea of reviewing and merging this PR, and establishing a way to interoperate with rust libraries and external projects. I just think going forward we should not lock ourselves into an approach that requires everything to go through a C interface. As we build on this and add features, we should experiment with other approaches that use C++ directly, especially when it can reduce boilerplate and avoid bugs.

Thanks for pointing to me to the other error handling discussion. I very much agree with the post that says having a single error handling path is highly desirable. I especially agree with this in cases where detailed error messages are still provided (keeping in mind that error handling != error reporting, you can return simple error states with detailed messages or logging). Of course there are places where callers do need to handle separate error cases, especially when there are temporary failures, timeouts, and interruptions, and in these cases functions should return 2 or 3 error states instead of 1. But I don't think there is a reason in modern application code for functions to be able to return 5, 10, 20, or 50 error states generally. In low-level or very general OS, networking or DBMS code it might make sense, but for application code it seems like a cargo cult programming practice that made IBM service manuals very impressive in the 1980s but does not have a present day rationale. There are special cases, but I don't think it should be a normal thing for functions to be returning 15 error codes if we are trying to provide a safe and easy to use API.

Again though, if this approach is the easiest way to get cross-language interoperability working right now, I think we should try it. I just think we should be looking for ways to make things simpler and safer going forward.

@sedited

sedited commented Aug 13, 2024

Copy link
Copy Markdown
Contributor Author

I guess another thing I'd like to know is if this is the initial C API, and the implementation is around 3000 lines, and it doesn't handle "transactions, block headers, coins cache, utxo set, meta data, and the mempool", how much bigger do you think it will get if it does cover most of the things you would like it to cover? Like is this 20%, 30%, or 50% of the expected size?

I think a fair comparison would be comparing the amount of code "glue" required, e.g. the size of the bitcoinkernel.cpp file in this pull request. The size of the header is very dependent on the detail of documentation and I think judging it by the amount of test code is also hard. On my branch including iterators for the UTXO set, handling headers, and simple mempool processing, basically all the stuff required to drop-in replace the calls to validation code in net_processing with the C API, is about similar in size: https://github.com/bitcoin/bitcoin/pull/30595/files#diff-cc28221ef8d0c7294dda4e3df9f70bb6c062006b387468380c2c2cc02b6762c3 . The code on that branch is more hacky than the code here, so I would expect a bit less than a doubling in size to get all the features required to run a full node with transaction relay.

In low-level or very general OS, networking or DBMS code it might make sense, but for application code it seems like a cargo cult programming practice that made IBM service manuals very impressive in the 1980s but does not have a present day rationale.

Heh, well put. I think for most functions here it could be feasible to have more concise error codes without too much effort, but I feel like I have to detach from this a bit before being able to come up with an alternative.

@ryanofsky

Copy link
Copy Markdown
Contributor

I think for most functions here it could be feasible to have more concise error codes without too much effort, but I feel like I have to detach from this a bit before being able to come up with an alternative.

Thanks, I think I'd need to look at this more to give concrete suggestions, but I'd hope most functions would just return a simple success or failure status, with a descriptive error message in the case of failure. When functions need to return more complicated information or can fail in different ways that callers will want to distinguish, it should be easy to return the relevant information in custom struct or enum types. I think it's usually better for functions to return simpler custom types than more complicated shared types, because it lets callers know what values functions can return just by looking at their declarations.

@sedited

sedited commented Sep 1, 2024

Copy link
Copy Markdown
Contributor Author

I think for most functions here it could be feasible to have more concise error codes without too much effort, but I feel like I have to detach from this a bit before being able to come up with an alternative.

Completely got rid of the kernel_Error with the last push. Thanks for laying out your logic ryanofsky, I feel like this is cleaner now. When looking at the Rust wrapper, the code seems much clearer too. Errors are now communicated through nullptr or false values. Where required, so far only for the verification functions, a richer status code is communicated to the developer.

@DrahtBot DrahtBot mentioned this pull request Sep 2, 2024
@ryanofsky

Copy link
Copy Markdown
Contributor

Thanks for the update. It's good to drop the error codes so the C API can correspond 1:1 with the C++ API and not be tied to a more old fashioned and cumbersome error handling paradigm (for callers that want to know which errors are possible and not have to code defensively or fall back to failing generically).

I am still -0 on the approach of introducing a C API to begin with, but happy to help review this and get merged and maintain it if other developers think this is the right approach to take (short term or long term). It would be great to have more concept and approach ACKs for this PR particularly from the @theuni who commented earlier and @josibake who seems to have some projects built on this and linked in the PR description.

I think personally, if I wanted to use bitcoin core code from python or rust I would use tools like:

And interoperate with C++ directly, instead of wrapping the C++ interface in a C interface first. Tools like these do not support all C++ types and features, and can make it necessary to selectively wrap more complicated C++ interfaces with simpler C++ interfaces, or even C interfaces, but I don't think this would be a justification for preemptively requiring every C++ type and function to be wrapped in C before it can be exposed. I just think the resulting boilerplate code:

kernel_Warning cast_kernel_warning(kernel::Warning warning)
{
    switch (warning) {
    case kernel::Warning::UNKNOWN_NEW_RULES_ACTIVATED:
        return kernel_Warning::kernel_LARGE_WORK_INVALID_CHAIN;
    case kernel::Warning::LARGE_WORK_INVALID_CHAIN:
        return kernel_Warning::kernel_LARGE_WORK_INVALID_CHAIN;
    } // no default case, so the compiler can warn about missing cases
    assert(false);
}

and duplicative type definitions and documentation:

/**
 * A struct for holding the kernel notification callbacks. The user data pointer
 * may be used to point to user-defined structures to make processing the
 * notifications easier.
 */
typedef struct {
    void* user_data;                         //!< Holds a user-defined opaque structure that is passed to the notification callbacks.
    kernel_NotifyBlockTip block_tip;         //!< The chain's tip was updated to the provided block index.
    kernel_NotifyHeaderTip header_tip;       //!< A new best block header was added.
    kernel_NotifyProgress progress;          //!< Reports on current block synchronization progress.
    kernel_NotifyWarningSet warning_set;     //!< A warning issued by the kernel library during validation.
    kernel_NotifyWarningUnset warning_unset; //!< A previous condition leading to the issuance of a warning is no longer given.
    kernel_NotifyFlushError flush_error;     //!< An error encountered when flushing data to disk.
    kernel_NotifyFatalError fatal_error;     //!< A un-recoverable system error encountered by the library.
} kernel_NotificationInterfaceCallbacks;

are fundamentally unnecessary and not worth effort of writing and maintaining when C++ is not a new or unusual language and not meaningfully less accessible or interoperable than C is.

There are legitimate reasons to wrap C++ in C. One reason would be to provide ABI compatibility. Another would be to make code accessible with dlopen/dlsym. But I think even in these cases you would want to wrap C++ in C selectively, or just define an intermediate C interface to pass pointers but use C++ on either side of the interface. I don't think you would want to drop down to C when not otherwise needed.

This is just to explain my point of view though. Overall I think this is very nice work, and I want to help with it, not hold it up.

@ryanofsky

ryanofsky commented Sep 2, 2024

Copy link
Copy Markdown
Contributor

Another idea worth mentioning is that a bitcoin kernel C API could be implemented as a separate C library depending on the C++ library. The new code here does not necessarily need to be part of the main bitcoin core git repository, and it could be in a separate project. A benefit of this approach is it could relieve bitcoin core developers from the responsibility of updating the C API and API documention when they change the C++ code. But a drawback is that C API might not always be up to date with latest version of bitcoin core code and could be broken between releases. Also it might not be as well reviewed or understood and might have more bugs.

@sedited

sedited commented Nov 4, 2025

Copy link
Copy Markdown
Contributor Author

Thank you for the review @yuvicc,

e95efc0 -> 6c7a34f (kernelApi_80 -> kernelApi_81, compare)

  • Addressed a bunch of typo and documentation nits.
  • Addressed @yuvicc's comment, return int32_t when queried for the height.

@alexanderwiederin

Copy link
Copy Markdown
Contributor

re-ACK 6c7a34f

btck_NotifyWarningSet warning_set; //!< A warning issued by the kernel library during validation.
btck_NotifyWarningUnset warning_unset; //!< A previous condition leading to the issuance of a warning is no longer given.
btck_NotifyFlushError flush_error; //!< An error encountered when flushing data to disk.
btck_NotifyFatalError fatal_error; //!< A un-recoverable system error encountered by the library.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

llm-nit: [Only if you re-touch]:

  • A un-recoverable system error encountered by the library. -> An unrecoverable system error encountered by the library. [“A” before a vowel sound should be “An”; “un-recoverable” is more commonly written “unrecoverable” — the revised phrase is grammatical and clearer.]

@stringintech

Copy link
Copy Markdown
Contributor

re-ACK 6c7a34f

nits if/when you have to retouch
diff --git a/src/kernel/bitcoinkernel.cpp b/src/kernel/bitcoinkernel.cpp
index 8bba3cf1c0..07b59d9543 100644
--- a/src/kernel/bitcoinkernel.cpp
+++ b/src/kernel/bitcoinkernel.cpp
@@ -602,11 +602,11 @@ void btck_transaction_output_destroy(btck_TransactionOutput* output)
 }
 
 int btck_script_pubkey_verify(const btck_ScriptPubkey* script_pubkey,
-                              const int64_t amount,
+                              int64_t amount,
                               const btck_Transaction* tx_to,
                               const btck_TransactionOutput** spent_outputs_, size_t spent_outputs_len,
-                              const unsigned int input_index,
-                              const btck_ScriptVerificationFlags flags,
+                              unsigned int input_index,
+                              btck_ScriptVerificationFlags flags,
                               btck_ScriptVerifyStatus* status)
 {
     // Assert that all specified flags are part of the interface before continuing
@@ -1236,7 +1236,7 @@ const btck_BlockTreeEntry* btck_chain_get_tip(const btck_Chain* chain)
     return btck_BlockTreeEntry::ref(btck_Chain::get(chain).Tip());
 }
 
-int btck_chain_get_height(const btck_Chain* chain)
+int32_t btck_chain_get_height(const btck_Chain* chain)
 {
     LOCK(::cs_main);
     return btck_Chain::get(chain).Height();
diff --git a/src/kernel/bitcoinkernel.h b/src/kernel/bitcoinkernel.h
index 99ae2bd67a..afe7f38781 100644
--- a/src/kernel/bitcoinkernel.h
+++ b/src/kernel/bitcoinkernel.h
@@ -608,7 +608,7 @@ BITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_script_pubkey_verify
     const btck_Transaction* tx_to,
     const btck_TransactionOutput** spent_outputs, size_t spent_outputs_len,
     unsigned int input_index,
-    unsigned int flags,
+    btck_ScriptVerificationFlags flags,
     btck_ScriptVerifyStatus* status) BITCOINKERNEL_ARG_NONNULL(1, 3);
 
 /**

@laanwj

laanwj commented Nov 4, 2025

Copy link
Copy Markdown
Member

Code review ACK 6c7a34f

i think this is a good start for the C API, and ready for merge.

@ismaelsadeeq

Copy link
Copy Markdown
Member

reACK 6c7a34f 👾

There have been numerous changes to the header API since my last ACK.
I've reviewed the changes using the compare diff

Changes
  • Fixed typo in Write
  • LoggingConnection now does not take Logging Options; a clear error message is returned or thrown when the logger connection encounters an exception. @TheCharlatan would be nice if further the e.what() is also returned?
  • Improved LoggingConnection destructor; (for the sake of bikeshedding, the previous logging comment, "disconnected," will read better in logs than "disconnecting.")
  • KernelNotifications class is now final, and notifications are now executed with an explicit copy of the block's raw object.
  • m_signals is now instantiated only when the context options have a validation interface shared pointer, ensuring proper destruction of the context object.
  • btck_ChainParameters C++ type is now not a unique pointer; hence changes in the btck_chain_parameters_create, btck_chain_parameters_destroy, and btck_chain_parameters_copy function implementations.
  • btck_ScriptVerifyStatus_SCRIPT_VERIFY_OK is now btck_ScriptVerifyStatus_OK; we set the status to OK first in btck_script_pubkey_verify.
  • A convenient btck_logging_set_options function is now available.
  • btck_chain_get_tip, btck_chain_get_height, and btck_chain_get_genesis now lock cs_main.
  • Several typos and documentation improvements in the Bitcoin kernel header.
  • Improved comment in btck_ScriptVerifyStatus_OK.
  • The returned height in btck_chain_get_height is now int32_t.
  • We warn when the result is unused when we expect it to be used.
  • We now have an abstracted MAKE_RANGE_METHOD macro which is reused in multiple places.
  • Class Transaction and TransactionOutput forward declarations are now removed.
  • Multiple friend class relationships are now removed.
  • We now have a new convenient method CountEntries.
  • GetBlockTreeEntry returned value is now std::optional; Side note: There seems to be inconsistency in the returned value of things that can be nullptr. we return optional and sometimes throw in some cases? Shouldn't the user handle that? What safety assumption are you providing? I am a bit conflicted with the current approach; by throwing I assume it implies that the user doesn't need to check that returned values are null and can use them instantly, but here they have to.

@fanquake

fanquake commented Nov 4, 2025

Copy link
Copy Markdown
Member

ACK 6c7a34f - soon we'll be running bitcoin (kernel)

@yuvicc

yuvicc commented Nov 4, 2025

Copy link
Copy Markdown
Contributor

post-merge ACK 6c7a34f

@dongcarl

dongcarl commented Nov 5, 2025

Copy link
Copy Markdown
Contributor

What a milestone. Congrats @TheCharlatan!

@janb84 janb84 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Post merge ACK 6c7a34f

To test this PR I made a dotnet wrapper for libbitcoinkernel and that went pretty smooth, no major issues.

@maflcko maflcko left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

lgtm. Just left a few nits and questions. I am happy to address them myself, if applicable

Comment thread src/kernel/bitcoinkernel.cpp
Comment thread src/kernel/bitcoinkernel.cpp

LoggingConnection(btck_LogCallback callback, void* user_data, btck_DestroyCallback user_data_destroy_callback)
{
LOCK(cs_main);

@maflcko maflcko Nov 5, 2025

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit in 28d679b: Could add a comment explaining why cs_main is used here? Maybe a new logging-specific global mutex could be added here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Ideally this all goes away soon with a kernel/common logging split. Didn't feel like introducing a new global in the interim, since this is typically only done once.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ah, nice. Looks like it will go away with https://github.com/bitcoin/bitcoin/pull/34374/files

Comment thread src/kernel/bitcoinkernel.cpp
Comment thread src/kernel/bitcoinkernel.cpp
Comment thread src/kernel/bitcoinkernel.h
Comment thread src/test/kernel/test_kernel.cpp
Comment thread src/test/kernel/test_kernel.cpp
Comment thread src/test/kernel/test_kernel.cpp
":(exclude)src/ipc/libmultiprocess/",
":(exclude)src/util/fs.h",
":(exclude)src/test/kernel/test_kernel.cpp",
":(exclude)src/bitcoin-chainstate.cpp",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Seems fine for now, but it would be nice to check that non-ascii datadirs work on Windows. Though, I can't help here and in CI, the following diff seems to fail:

diff --git a/src/test/kernel/test_kernel.cpp b/src/test/kernel/test_kernel.cpp
index f31a9a0277..0e151c12c0 100644
--- a/src/test/kernel/test_kernel.cpp
+++ b/src/test/kernel/test_kernel.cpp
@@ -4,6 +4,7 @@
 
 #include <kernel/bitcoinkernel.h>
 #include <kernel/bitcoinkernel_wrapper.h>
+#include <util/fs.h>
 
 #define BOOST_TEST_MODULE Bitcoin Kernel Test Suite
 #include <boost/test/included/unit_test.hpp>
@@ -100,7 +101,7 @@ public:
 struct TestDirectory {
     std::filesystem::path m_directory;
     TestDirectory(std::string directory_name)
-        : m_directory{std::filesystem::temp_directory_path() / (directory_name + random_string(16))}
+        : m_directory{std::filesystem::temp_directory_path() / fs::PathFromString(" 🔥").std_path() /  (directory_name + random_string(16))}
     {
         std::filesystem::create_directories(m_directory);
     }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, and as you lay out, the real solution here would be including our existing filesystem and test utilities in lieu of std::filesystem. I tried doing that, but it would not work. I tried using strace to see whether the paths with unicode symbols get passed through the C API correctly, which indicated that they do. I wonder if the problem is in fsbridge's use of fopen when compiling for windows? Might this be a regression from 53e4951 ?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is there a tracking issue for this? I guess it is bitcoin_kernel_util from #28690?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

No, but I was preparing a patch for this, I'll pick it back up soon.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

See #34705

@sedited sedited left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thank you so much for taking another look @maflcko! I think these all deserve a follow up. I would suggest tackling the unicode path issues in a separate PR.

I've been exploring ways the past week to integrate these tighter into our existing test framework, while still linking as a shared library and exercising the external kernel headers. The main problem with that seems to be linking in a re-definition of the translation function.

Comment thread src/kernel/bitcoinkernel.cpp
Comment thread src/kernel/bitcoinkernel.cpp
Comment thread src/kernel/bitcoinkernel.cpp

LoggingConnection(btck_LogCallback callback, void* user_data, btck_DestroyCallback user_data_destroy_callback)
{
LOCK(cs_main);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Ideally this all goes away soon with a kernel/common logging split. Didn't feel like introducing a new global in the interim, since this is typically only done once.

Comment thread src/kernel/bitcoinkernel.cpp
Comment thread src/kernel/bitcoinkernel.h
Comment thread src/test/kernel/test_kernel.cpp
Comment thread src/test/kernel/test_kernel.cpp
":(exclude)src/ipc/libmultiprocess/",
":(exclude)src/util/fs.h",
":(exclude)src/test/kernel/test_kernel.cpp",
":(exclude)src/bitcoin-chainstate.cpp",

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, and as you lay out, the real solution here would be including our existing filesystem and test utilities in lieu of std::filesystem. I tried doing that, but it would not work. I tried using strace to see whether the paths with unicode symbols get passed through the C API correctly, which indicated that they do. I wonder if the problem is in fsbridge's use of fopen when compiling for windows? Might this be a regression from 53e4951 ?

Comment thread src/test/kernel/test_kernel.cpp
@sedited

sedited commented Feb 2, 2026

Copy link
Copy Markdown
Contributor Author

@maflcko do you mind me taking charge of implementing your suggestions, or do you already have the patches prepared?

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

Projects

Status: Done or Closed or Rethinking

Development

Successfully merging this pull request may close these issues.