Commit Graph

29326 Commits

Author SHA1 Message Date
TheCharlatan
5b89956eeb kernel: Allow null arguments for serialized data
An empty span constructed from an empty vector may have a null data
pointer depending on the implementation. Remove the
BITCOINKERNEL_ARG_NONNULL requirement for these arguments and instead
handle such null arguments in the implementation.
2025-11-11 12:35:15 +01:00
merge-script
b354d1ce5c Merge bitcoin/bitcoin#33820: kernel: trim Chain interface
66978a1a95 kernel: remove btck_chain_get_tip (stickies-v)
4dd7e6dc48 kernel: remove btck_chain_get_genesis (stickies-v)

Pull request description:

  Removes `btck_chain_get_genesis` and `btck_chain_get_tip`.

  They are trivially replaced with `btck_chain_get_by_height` (as indicated in the updated `bitcoinkernel_wrapper.h`), so I think it makes sense to trim the interface.

  For `btck_chain_get_tip`: on `master` we don't provide any guarantees that the returned block index still corresponds to the actual tip, so the extra call doesn't seem like a regression to me.

ACKs for top commit:
  TheCharlatan:
    ACK 66978a1a95
  janb84:
    ACK 66978a1a95

Tree-SHA512: f583fbb7f2e3f8f23afb57732b2cbe9e1d550bfc43c9a2619895ee30c27f5f3c5cd9e4ecb7e05b1f6ab9e11c368596ec9b733d67e06cfafb12326d88e8e4dd7d
2025-11-11 09:52:26 +00:00
Ava Chow
a4e96cae7d Merge bitcoin/bitcoin#33042: refactor: inline constant return values from dbwrapper write methods
743abbcbde refactor: inline constant return value of `BlockTreeDB::WriteBatchSync` and `BlockManager::WriteBlockIndexDB` and `BlockTreeDB::WriteFlag` (Lőrinc)
e030240e90 refactor: inline constant return value of `CDBWrapper::Erase` and `BlockTreeDB::WriteReindexing` (Lőrinc)
cdab9480e9 refactor: inline constant return value of `CDBWrapper::Write` (Lőrinc)
d1847cf5b5 refactor: inline constant return value of `TxIndex::DB::WriteTxs` (Lőrinc)
50b63a5698 refactor: inline constant return value of `CDBWrapper::WriteBatch` (Lőrinc)

Pull request description:

  Related to https://github.com/bitcoin/bitcoin/pull/31144#discussion_r2223587480

  ### Summary
  `WriteBatch` always returns `true` - the errors are handled by throwing `dbwrapper_error` instead.

  ### Context
  This boolean return value of the `Write` methods is confusing because it's inconsistent with `CDBWrapper::Read`, which catches exceptions and returns a boolean to indicate success/failure. It's bad that `Read` returns and `Write` throws - but it's a lot worse that `Write` advertises a return value when it actually communicates errors through exceptions.

  ### Solution
  This PR removes the constant return values from write methods and inlines `true` at their call sites. Many upstream methods had boolean return values only because they were propagating these constants - those have been cleaned up as well.

  Methods that returned a constant `true` value that now return `void`:
  - `CDBWrapper::WriteBatch`, `CDBWrapper::Write`, `CDBWrapper::Erase`
  - `TxIndex::DB::WriteTxs`
  - `BlockTreeDB::WriteReindexing`, `BlockTreeDB::WriteBatchSync`, `BlockTreeDB::WriteFlag`
  - `BlockManager::WriteBlockIndexDB`

  ### Note
  `CCoinsView::BatchWrite` (and transitively `CCoinsViewCache::Flush` & `CCoinsViewCache::Sync`) were intentionally not changed here. While all implementations return `true`, the base `CCoinsView::BatchWrite` returns `false`. Changing this would cause `coins_view` tests to fail with:
  > terminating due to uncaught exception of type std::logic_error: Not all unspent flagged entries were cleared

  We can fix that in a follow-up PR.

ACKs for top commit:
  achow101:
    ACK 743abbcbde
  janb84:
    ACK 743abbcbde
  TheCharlatan:
    ACK 743abbcbde
  sipa:
    ACK 743abbcbde

Tree-SHA512: b2a550bff066216f1958d2dd9a7ef6a9949de518cc636f8ab9c670e0b7a330c1eb8c838e458a8629acb8ac980cea6616955cd84436a7b8ab9096f6d648073b1e
2025-11-10 09:15:24 -08:00
Ava Chow
8c2710b041 Merge bitcoin/bitcoin#32517: rpc: add "ischange: true" to decoded tx outputs in wallet gettransaction response
060bb55508 rpc: add decoded tx details to gettransaction with extra wallet fields (Matthew Zipkin)
ad1c3bdba5 [move only] move DecodeTxDoc() to a common util file for sharing (Matthew Zipkin)
d633db5416 rpc: add "ischange: true" in wallet gettransaction decoded tx output (Matthew Zipkin)

Pull request description:

  This change is motivated by external RBF clients like https://github.com/CardCoins/additive-rbf-batcher/. It saves the user a redundant re-looping of tx outputs, calling `getaddressinfo` on each one, looking for the change output in order to adjust the fee.

  The field `"ischange"` only appears when `gettransaction` is called on a wallet, and is either `true` or not present at all. I chose not to include `ischange: false` because it is confusing to see that on *received* transactions.

  Example of the new field:

  ```
      "vout": [
        {
          "value": 1.00000000,
          "n": 0,
          "scriptPubKey": {
            "asm": "0 5483235e05c76273b3b50af62519738781aff021",
            "desc": "addr(bcrt1q2jpjxhs9ca388va4ptmz2xtns7q6lupppkw7wu)#d42g84j6",
            "hex": "00145483235e05c76273b3b50af62519738781aff021",
            "address": "bcrt1q2jpjxhs9ca388va4ptmz2xtns7q6lupppkw7wu",
            "type": "witness_v0_keyhash"
          }
        },
        {
          "value": 198.99859000,
          "n": 1,
          "scriptPubKey": {
            "asm": "0 870ab1ab58632b05a417d5295f4038500e407592",
            "desc": "addr(bcrt1qsu9tr26cvv4stfqh65547spc2q8yqavj7fnlju)#tgapemkv",
            "hex": "0014870ab1ab58632b05a417d5295f4038500e407592",
            "address": "bcrt1qsu9tr26cvv4stfqh65547spc2q8yqavj7fnlju",
            "type": "witness_v0_keyhash"
          },
          "ischange": true
        }
      ]

  ```

ACKs for top commit:
  furszy:
    ACK [060bb55](060bb55508)
  maflcko:
    review ACK 060bb55508 🌛
  achow101:
    ACK 060bb55508
  rkrux:
    lgtm ACK 060bb55508

Tree-SHA512: aae4854d2bb4e9a7bc1152691ea90e594e8da8a63c9c7fda72a504fb6a7e54ae274ed5fa98d35d270e0829cc8f8d2fd35a5fc9735c252a10aa42cc22828930e7
2025-11-10 08:58:34 -08:00
Ava Chow
1fe851a478 Merge bitcoin/bitcoin#32180: p2p: Advance pindexLastCommonBlock early after connecting blocks
01cc20f330 test: improve coverage for a resolved stalling situation (Martin Zumsande)
9af6daf07e test: remove magic number when checking for blocks that have arrived (Martin Zumsande)
3069d66dca p2p: During block download, adjust pindexLastCommonBlock better (Martin Zumsande)

Pull request description:

  As described in #32179, `pindexLastCommonBlock` is updated later than necessary
  in master.
  In case of a linear chain with no forks, it can be moved forward at the beginning of
  `FindNextBlocksToDownload`, so that the updated value can be used to better estimate `nWindowEnd`.
  This helps the node to request all blocks from peers within the correct 1024-block-window and avoids peers being incorrectly marked as stallers.

  I also changed `p2p_ibd_stalling.py` to cover the situation after a resolved situation, making sure that no additional peers are marked for stalling.

  Fixes #32179

ACKs for top commit:
  Crypt-iQ:
    crACK 01cc20f330
  stringintech:
    re-ACK 01cc20f
  achow101:
    ACK 01cc20f330
  sipa:
    utACK 01cc20f330

Tree-SHA512: a97f7a7ef5ded538ee35576e04b3fbcdd46a6d0189c7ba3abacc6e0d81e800aac5b0c2d2565d0462ef6fd4acc751989f577fd6adfd450171a7d6ab26f437df32
2025-11-10 08:48:49 -08:00
Ava Chow
5f0303b93f Merge bitcoin/bitcoin#33443: log: reduce excessive "rolling back/forward" messages during block replay
1fc7a81f1f log: reduce excessive messages during block replay (Lőrinc)

Pull request description:

  ### Summary
  After an incomplete reindex the blocks will need to be replayed.
  This results in excessive `Rolling back` and `Rolling forward` messages which quickly triggers the recently introduced log rate limiter.

  Change the logging strategy to:
  - Add single `LogInfo` messages showing the full range being replayed for both rollback and roll forward;
  - Log progress at `LogInfo` level only every 10,000 blocks to track the long operations.

  ### Reproducer:
  * Start a normal ibd, stop after some progress
  * Do a reindex, stop before it finishes
  * Restart the node normally without specifying the reindex parameter
  It should start rolling the blocks forward.

  Before this change the excessive logging would show:
  ```
  [*] Rolling forward 000000002f4f55aecfccc911076dc3f73ac0288c83dc1d79db0a026441031d40 (46245)
  [*] Rolling forward 0000000017ffcf34c8eac010c529670ba6745ea59cf1edf7b820928e3b40acf6 (46246)
  ```

  After the change it shows:
  ```
  Replaying blocks
  Rolling forward to 00000000000000001034012d7e4facaf16ca747ea94b8ea66743086cfe298ef8 (326223 to 340991)
  Rolling forward 00000000000000000faabab19f17c0178c754dbed023e6c871dcaf74159c5f02 (330000)
  Rolling forward 00000000000000000d9b2508615d569e18f00c034d71474fc44a43af8d4a5003 (340000)
  ...
  Rolled forward to 00000000000000001034012d7e4facaf16ca747ea94b8ea66743086cfe298ef8
  ```
  (similarly to rolling back)

ACKs for top commit:
  Crypt-iQ:
    crACK 1fc7a81f1f
  stickies-v:
    ACK 1fc7a81f1f
  achow101:
    ACK 1fc7a81f1f
  vasild:
    ACK 1fc7a81f1f
  hodlinator:
    Concept ACK 1fc7a81f1f

Tree-SHA512: 44ed1da8336de5a3d937e11a13e6f1789064e23eb70640a1c406fbb0074255344268f6eb6b06f036ca8d22bfeb4bdea319c3085a2139d848f6d36a4f8352b76a
2025-11-10 08:27:40 -08:00
merge-script
06e9458869 Merge bitcoin/bitcoin#32856: Update minisketch subtree
4543a3bde2 Squashed 'src/minisketch/' changes from ea8f66b1ea..d1bd01e189 (Hennadii Stepanov)

Pull request description:

  This PR updates the `minisketch` subtree to latest upstream, which includes:
      - https://github.com/bitcoin-core/minisketch/pull/75
      - https://github.com/bitcoin-core/minisketch/pull/98

ACKs for top commit:
  fanquake:
    ACK c235aa468b

Tree-SHA512: 856fb8b7dc2e743c9c67164023bf53faf8766079aeccc82a30c8b90c85920b31977b6a8b26e51e5485b20e445a3ca6ff806e701a53e95f70181ea30055e3528c
2025-11-10 14:06:00 +00:00
stickies-v
66978a1a95 kernel: remove btck_chain_get_tip
It is equivalent to calling btck_chain_get_by_height with the
height obtained from btck_chain_get_height. In neither case do we
provide guarantees that the returned block index still corresponds
to the actual tip.
2025-11-10 13:48:19 +01:00
stickies-v
4dd7e6dc48 kernel: remove btck_chain_get_genesis
It is equivalent to calling btck_chain_get_by_height(0).
2025-11-10 13:45:58 +01:00
merge-script
490cb056f6 Merge bitcoin/bitcoin#33785: util: Allow Assert (et al.) in contexts without __func__
fad6efd3be refactor: Use STR_INTERNAL_BUG macro where possible (MarcoFalke)
fada379589 doc: Remove unused bugprone-lambda-function-name suppression (MarcoFalke)
fae1d99651 refactor: Use const reference to std::source_location (MarcoFalke)
fa5fbcd615 util: Allow Assert() in contexts without __func__ (MarcoFalke)

Pull request description:

  Without this, compile warnings could be hit about `__func__` being only valid inside functions.

  ```
  warning: predefined identifier is only valid inside function [-Wpredefined-identifier-outside-function] note: expanded from macro Assert
    115 | #define Assert(val) inline_assertion_check<true>(val, __FILE__, __LINE__, __func__, #val)
        |                                                                           ^
  ```

  Ref https://github.com/bitcoin/bitcoin/pull/32740#discussion_r2486258473

  This also introduces a slight behaviour change, because `std::source_location::function_name` usually includes the entire function signature instead of just the name.

ACKs for top commit:
  l0rinc:
    Code review ACK fad6efd3be
  stickies-v:
    ACK fad6efd3be
  hodlinator:
    re-ACK fad6efd3be

Tree-SHA512: e78a2d812d5ae22e45c93db1661dafbcd22ef209b3d8d8d5f2ac514e92fd19a17c3f0a5db2ef5e7748aa2083b10c0465326eb36812e6a80e238972facd2c7e98
2025-11-10 11:56:09 +00:00
merge-script
ddd2afac10 Merge bitcoin/bitcoin#33676: interfaces: enable cancelling running waitNext calls
dcb56fd4cb interfaces: add interruptWait method (ismaelsadeeq)

Pull request description:

  This is an attempt to fix #33575 see the issue for background and the usefulness of this feature.

  This PR uses one of the suggested approaches: adding a new `interruptWaitNext()` method to the mining interface.

  It introduces a new boolean variable, `m_interrupt_wait`, which is set to `false` when the thread starts waiting. The `interruptWaitNext()` method wakes the thread and sets `m_interrupt_wait` to `true`.
  Whenever the thread wakes up, it checks whether the wait was aborted; if so, it simply set ` m_interrupt_wait ` to false and return`nullptr`.

  This PR also adds a functional test for the new method. The test uses `asyncio` to spawn two tasks and attempts to ensure that the wait is executed before the interrupt by using an event monitor. It adds a 0.1-second buffer to ensure the wait has started executing.
  If that buffer elapses without `waitNext` executing, the test will fail because a transaction is created after the buffer.

ACKs for top commit:
  furszy:
    Code ACK dcb56fd4cb
  ryanofsky:
    Code review ACK dcb56fd4cb, just tweaking semantics slightly since last review so if an `interruptWait` call is made shortly after a `waitNext` call it will reliably cause the `waitNext` call to return right away without blocking, even if the `waitNext` call had not begun to execute or wait yet.
  Sjors:
    tACK dcb56fd4cb
  TheCharlatan:
    ACK dcb56fd4cb

Tree-SHA512: a03f049e1f303b174a9e5d125733b6583dfd8effa12e7b6c37bd9b2cff9541100f5f4514e80f89005c44a57d7e47804afe87aa5fdb6831f3b0cd9b01d83e42be
2025-11-10 09:56:27 +00:00
MarcoFalke
fa1e8d8bad refactor: Add missing include in bitcoinkernel_wrapper.h 2025-11-08 12:31:18 +01:00
merge-script
93e79181da Merge bitcoin/bitcoin#33786: script: remove dead code in CountWitnessSigOps
24bcad3d4d refactor: remove dead code in `CountWitnessSigOps` (Lőrinc)

Pull request description:

  Found while reviewing #32840

  The `nullptr` witness path was dead in normal code paths: replacing it with reference enables us deleting unreachable logic.

  Code coverage proof:
  https://maflcko.github.io/b-c-cov/total.coverage/src/script/interpreter.cpp.gcov.html#L2135

ACKs for top commit:
  kevkevinpal:
    ACK [24bcad3](24bcad3d4d)
  maflcko:
    review ACK 24bcad3d4d 🐏
  darosior:
    Neat. utACK 24bcad3d4d.
  stickies-v:
    ACK 24bcad3d4d

Tree-SHA512: 92c87e431f06a15d8eeb02e20e9154b272c4586ddacf77c8d83783091485fb82c24ecbd711db7043a92cf6169746db24ad46a5904d694aea9d3c3aa96da725f0
2025-11-07 12:46:46 +00:00
merge-script
2b9c351198 Merge bitcoin/bitcoin#33768: refactor: remove dead branches in SingletonClusterImpl
2d23820ee1 refactor: remove dead branches in `SingletonClusterImpl` (Lőrinc)

Pull request description:

  Found during review: [cluster mempool: control/optimize TxGraph memory usage](https://github.com/bitcoin/bitcoin/pull/33157#discussion_r2423058928)

  ### Fixes
  `SplitAll()` always calls `ApplyRemovals()` first, for a singleton, it empties the cluster, therefore any `SingletonClusterImpl` passed to `Split()` must be empty.

  `TxGraphImpl::ApplyDependencies()` first merges each dependency group and asserts the group has at least one dependency. Since `parent` != `child`, `TxGraphImpl::Merge()` upgrades the merge target to `GenericClusterImpl`, therefore the `ApplyDependencies()` is never dispatched to `SingletonClusterImpl`.

  ### Coverage proof:
  * https://maflcko.github.io/b-c-cov/fuzz.coverage/src/txgraph.cpp.gcov.html#L1446
  * https://storage.googleapis.com/oss-fuzz-coverage/bitcoin-core/reports/20251103/linux/src/bitcoin-core/src/txgraph.cpp.html#L1446

ACKs for top commit:
  instagibbs:
    ACK 2d23820ee1
  sipa:
    ACK 2d23820ee1

Tree-SHA512: 5135913206c800d5344df61c6654f00917cb85567bc5b821576c7891805cf7689bf47968434a06517d09183dadfefc257d24c42b55a7b99486a4c9b11fc523af
2025-11-07 10:10:50 +00:00
MarcoFalke
fad6efd3be refactor: Use STR_INTERNAL_BUG macro where possible
This ensures a uniform bug template and allows to drop includes and
logic at the call sites.
2025-11-06 14:19:25 +01:00
MarcoFalke
fada379589 doc: Remove unused bugprone-lambda-function-name suppression
Now that the __func__ is no longer used, the
NOLINTBEGIN(bugprone-lambda-function-name) can be removed.

Also, re-format the NONFATAL_UNREACHABLE macro, while touching the
adjacent line.
2025-11-06 13:50:42 +01:00
TheCharlatan
ed5720509f kernel: Use enumeration type for flags argument 2025-11-05 12:37:28 +01:00
merge-script
50d106a4d6 Merge bitcoin/bitcoin#33781: clang-tidy: Remove no longer needed NOLINT
038849e2e0 clang-tidy: Remove no longer needed NOLINT (Hennadii Stepanov)

Pull request description:

  From https://github.com/bitcoin/bitcoin/pull/33714/files#r2491476516:
  > Actually, the `NOLINT` was fixed and can be removed? You've confirmed that it is undeclared on the listed platforms, so it can't be hit by `readability-redundant-declaration`

ACKs for top commit:
  maflcko:
    lgtm ACK 038849e2e0
  l0rinc:
    I wanted to ask the same on the original PR but forgot - ACK 038849e2e0

Tree-SHA512: c0b24235425e80baeac3158c7169122364f31140367bc289430d34f01cd38f9f6a3931319f6fe4e1dc86bc4d87e21a5b4b8a2263c199e8083593f89ce592a177
2025-11-05 10:06:36 +00:00
MarcoFalke
fae1d99651 refactor: Use const reference to std::source_location
Performance likely does not matter here, but from a perspective of
code-readablilty, a const reference should be preferred for read-only
access.

So use it here.

This requires to set -Wno-error=dangling-reference for GCC 13.1
compilations, but this false-positive is fixed in later GCC versions.

See also https://godbolt.org/z/fjc6be65M
2025-11-05 08:42:29 +01:00
MarcoFalke
fa5fbcd615 util: Allow Assert() in contexts without __func__
Without this, compile warnings could be hit about __func__ being only
valid inside functions.

warning: predefined identifier is only valid inside function [-Wpredefined-identifier-outside-function]
note: expanded from macro Assert
  115 | #define Assert(val) inline_assertion_check<true>(val, __FILE__, __LINE__, __func__, #val)
      |                                                                           ^

Ref https://github.com/bitcoin/bitcoin/pull/32740#discussion_r2486258473
2025-11-05 08:42:24 +01:00
Lőrinc
24bcad3d4d refactor: remove dead code in CountWitnessSigOps
Found while reviewing #32840

The `nullptr` witness path was dead in normal code paths: removing it deletes unreachable logic.

Code coverage proof:
https://maflcko.github.io/b-c-cov/total.coverage/src/script/interpreter.cpp.gcov.html#L2135
2025-11-04 22:51:25 +01:00
Hennadii Stepanov
33389f1144 Merge bitcoin-core/gui#899: Modernize custom filtering
e15e8cbada qt: Modernize custom filtering (Hennadii Stepanov)

Pull request description:

  In [`QSortFilterProxyModel::invalidateFilter()`](https://doc.qt.io/qt-6/qsortfilterproxymodel.html#invalidateFilter) is scheduled for deprecation in Qt 6.13. and emits warnings in Qt 6.10

  [`QSortFilterProxyModel::beginFilterChange()`](https://doc.qt.io/qt-6/qsortfilterproxymodel.html#beginFilterChange) was introduced in Qt 6.9.

  [`QSortFilterProxyModel::endFilterChange()`](https://doc.qt.io/qt-6/qsortfilterproxymodel.html#endFilterChange) was introduced in Qt 6.10.

  Fixes https://github.com/bitcoin/bitcoin/issues/33571.

  <img width="724" height="509" alt="image" src="https://github.com/user-attachments/assets/877740c4-7fdf-4478-963c-c639f0b80ad9" />

ACKs for top commit:
  maflcko:
    re-review ACK e15e8cbada 🌿
  pablomartin4btc:
    re-ACK e15e8cbada

Tree-SHA512: d31829f33292b3f9cdfb025d7b0db5fe50033752f58dbb634384ddaea0cac6f304dba7f2c8e706d1bc8bef15a4cb9162defdb7e7fee3433cd832ccc4ada737bb
2025-11-04 20:29:27 +00:00
Hennadii Stepanov
038849e2e0 clang-tidy: Remove no longer needed NOLINT 2025-11-04 17:38:45 +00:00
merge-script
4da01123df Merge bitcoin/bitcoin#30595: kernel: Introduce C header API
6c7a34f3b0 kernel: Add Purpose section to header documentation (TheCharlatan)
7e9f00bcc1 kernel: Allowing reducing exports (TheCharlatan)
7990463b10 kernel: Add pure kernel bitcoin-chainstate (TheCharlatan)
36ec9a3ea2 Kernel: Add functions for working with outpoints (TheCharlatan)
5eec7fa96a kernel: Add block hash type and block tree utility functions to C header (TheCharlatan)
f5d5d1213c kernel: Add function to read block undo data from disk to C header (TheCharlatan)
09d0f62638 kernel: Add functions to read block from disk to C header (TheCharlatan)
a263a4caf2 kernel: Add function for copying block data to C header (TheCharlatan)
b30e15f432 kernel: Add functions for the block validation state to C header (TheCharlatan)
aa262da7bc kernel: Add validation interface to C header (TheCharlatan)
d27e27758d kernel: Add interrupt function to C header (TheCharlatan)
1976b13be9 kernel: Add import blocks function to C header (TheCharlatan)
a747ca1f51 kernel: Add chainstate load options for in-memory dbs in C header (TheCharlatan)
070e77732c kernel: Add options for reindexing in C header (TheCharlatan)
ad80abc73d kernel: Add block validation to C header (TheCharlatan)
cb1590b05e kernel: Add chainstate loading when instantiating a ChainstateManager (TheCharlatan)
e2c1bd3d71 kernel: Add chainstate manager option for setting worker threads (TheCharlatan)
65571c36a2 kernel: Add chainstate manager object to C header (TheCharlatan)
c62f657ba3 kernel: Add notifications context option to C header (TheCharlatan)
9e1bac4585 kernel: Add chain params context option to C header (TheCharlatan)
337ea860df kernel: Add kernel library context object (TheCharlatan)
28d679bad9 kernel: Add logging to kernel library C header (TheCharlatan)
2cf136dec4 kernel: Introduce initial kernel C header API (TheCharlatan)

Pull request description:

  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:

  * A re-implementation (part of this pull request) of [bitcoin-chainstate](https://github.com/bitcoin/bitcoin/blob/master/src/bitcoin-chainstate.cpp).
  * A re-implementation of the python [block linearize](https://github.com/bitcoin/bitcoin/tree/master/contrib/linearize) scripts: https://github.com/TheCharlatan/bitcoin/tree/kernelLinearize
  * A silent payment scanner: https://github.com/josibake/silent-payments-scanner
  * An electrs index builder: https://github.com/josibake/electrs/commits/electrs-kernel-integration
  * A rust bitcoin node: https://github.com/TheCharlatan/kernel-node
  * A reindexer: https://github.com/TheCharlatan/bitcoin/tree/kernelApi_Reindexer

  The library has also been used by other developers already:

  * A historical block analysis tool: https://github.com/ismaelsadeeq/mining-analysis
  * A swiftsync hints generator: https://github.com/theStack/swiftsync-hints-gen
  * Fast script validation in floresta: https://github.com/vinteumorg/Floresta/pull/456
  * A swiftsync node implementation: https://github.com/2140-dev/swiftsync/tree/master/node

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

  * Rust: https://github.com/TheCharlatan/rust-bitcoinkernel
  * Python: https://github.com/stickies-v/py-bitcoinkernel
  * Go: https://github.com/stringintech/go-bitcoinkernel
  * Java: https://github.com/yuvicc/java-bitcoinkernel

  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](https://thecharlatan.ch/kernel-docs/index.html). The docs are generated from the following repository (which also holds the examples): [github.com/TheCharlatan/kernel-docs](https://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 https://github.com/bitcoin/bitcoin/pull/30595#issuecomment-2285719575.

  #### 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](https://sans-io.readthedocs.io/how-to-sans-io.html)" 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 #32427.
  * The fatal error handling through the notifications is awkward. This is partly improved through #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 #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.

ACKs for top commit:
  alexanderwiederin:
    re-ACK 6c7a34f3b0
  stringintech:
    re-ACK 6c7a34f
  laanwj:
    Code review ACK 6c7a34f3b0
  ismaelsadeeq:
    reACK 6c7a34f3b0 👾
  fanquake:
    ACK 6c7a34f3b0 - soon we'll be running bitcoin (kernel)

Tree-SHA512: ffe7d4581facb7017d06da8b685b81f4b5e4840576e878bb6845595021730eab808d8f9780ed0eb0d2b57f2647c85dcb36b6325180caaac469eaf339f7258030
2025-11-04 15:38:42 +00:00
Hennadii Stepanov
96614fff63 Merge bitcoin/bitcoin#33714: random: scope environ extern to macOS, BSDs and Illumos
79d6f458e2 random: scope environ extern to macOS, BSDs and Illumos (fanquake)

Pull request description:

  These platforms fail to compile with it removed.
  macOS: #33675
  BSDs / Illumos: https://github.com/hebasto/bitcoin-core-nightly/pull/79.

ACKs for top commit:
  l0rinc:
    ACK 79d6f458e2
  hebasto:
    re-ACK 79d6f458e2.

Tree-SHA512: dcaa15f0939d65a804107ceb110037f44d0ff70759f4d42fcc497a9c173ac28b1287b867f01732224788d1c1f9c883565bafc3abed3ccf28f1b67f23997ce3cf
2025-11-04 15:10:04 +00:00
merge-script
1cd8d9fe5c Merge bitcoin/bitcoin#33445: ci: Update Clang in "tidy" job
5d784bebaf clang-tidy: Disable `ArrayBound` check in src/ipc and src/test (Hennadii Stepanov)
5efdb0ef30 ci: Update Clang in "tidy" job (Hennadii Stepanov)

Pull request description:

  This PR:

  1. Updates to [IWYU 0.25](https://github.com/include-what-you-use/include-what-you-use/releases/tag/0.25), which is compatible with Clang 21.

  2. Fixes new "modernize-use-default-member-init" warnings. The warning in `interpreter.cpp` is a [false positive](https://github.com/llvm/llvm-project/issues/160394), so it has been suppressed.

ACKs for top commit:
  maflcko:
    review ACK 5d784bebaf 🎒
  ryanofsky:
    Code review ACK 5d784bebaf, just adding clang version comment since last review.

Tree-SHA512: a1d853675ec064170ee0f1cd16be6a900676588d4a1e7b5def8733933b140ba1a9520ec6f6a42bf7638b2ff7cf2fe4d5866d407f68b677b49d2bd68ff345f735
2025-11-04 10:16:06 +00:00
TheCharlatan
6c7a34f3b0 kernel: Add Purpose section to header documentation 2025-11-04 08:32:15 +01:00
TheCharlatan
7e9f00bcc1 kernel: Allowing reducing exports
Now that an API has been defined, remove the override for symbol
visibility of the library. It is now possible to build the library with
reduced exports.
2025-11-04 08:32:14 +01:00
TheCharlatan
7990463b10 kernel: Add pure kernel bitcoin-chainstate
Re-write the bitcoin-chainstate utility by only using the kernel C++ API
header instead of internal Bitcoin Core code.
2025-11-04 08:32:13 +01:00
TheCharlatan
36ec9a3ea2 Kernel: Add functions for working with outpoints
This introduces the transaction outpoint, input and id types. This now
allows a user to retrieve a transaction output from a prior transaction
that a transaction outpoint is pointing to by either scanning through
all available transactions, or maintaining a data structure for lookups.

This is exercised in the tests by verifying the script of every
transaction in the test chain.
2025-11-04 08:32:12 +01:00
TheCharlatan
5eec7fa96a kernel: Add block hash type and block tree utility functions to C header
Introduce btck_BlockHash as a type-safe identifier for a block. Adds
functions to retrieve block tree entries by hash or height, get block
hashes and heights from entries. access the genesis block, and check if
blocks are in the active chain.
2025-11-04 08:32:11 +01:00
TheCharlatan
f5d5d1213c kernel: Add function to read block undo data from disk to C header
This adds functions for reading the undo data from disk with a retrieved
block tree entry. The undo data of a block contains all the spent
script pubkeys of all the transactions in a block. For ease of
understanding the undo data is renamed to spent outputs with seperate
data structures exposed for a block's and a transaction's spent outputs.

In normal operations undo data is used during re-orgs. This data might
also be useful for building external indexes, or to scan for silent
payment transactions.

Internally the block undo data contains a vector of transaction undo
data which contains a vector of the coins consumed. The coins are all
int the order of the transaction inputs of the consuming transactions.
Each coin can be used to retrieve a transaction output and in turn a
script pubkey and amount.

This translates to the three-level hierarchy the api provides: Block
spent outputs contain transaction spent outputs, which contain
individual coins. Each coin includes the associated output, the height
of the block is contained in, and whether it is from a coinbase
transaction.
2025-11-04 08:32:10 +01:00
TheCharlatan
09d0f62638 kernel: Add functions to read block from disk to C header
This adds functions for reading a block from disk with a retrieved block
tree entry. External services that wish to build their own index, or
analyze blocks can use this to retrieve block data.

The block tree can now be traversed from the tip backwards. This is
guaranteed to work, since the chainstate maintains an internal block
tree index in memory and every block (besides the genesis) has an
ancestor.

The user can use this function to iterate through all blocks in the
chain (starting from the tip). The tip is retrieved from a separate
`Chain` object, which allows distinguishing whether entries are
currently in the best chain. Once the block tree entry for the genesis
block is reached a nullptr is returned if the user attempts to get the
previous entry.
2025-11-04 08:32:09 +01:00
TheCharlatan
a263a4caf2 kernel: Add function for copying block data to C header
This adds a function for streaming bytes into a user-owned data
structure.

Use it in the tests for verifying the implementation of the validation
interface's `BlockChecked` method.
2025-11-04 08:32:08 +01:00
TheCharlatan
b30e15f432 kernel: Add functions for the block validation state to C header
These allow for the interpretation of the data in a `BlockChecked`
validation interface callback. The validation state passed through
`BlockChecked` is the source of truth for the validity of a block (the
mode). It is
also useful to get richer information in case a block failed to
validate (the result).
2025-11-04 08:32:07 +01:00
TheCharlatan
aa262da7bc kernel: Add validation interface to C header
This adds the infrastructure required to process validation events. For
now the external validation interface only has support for the
`BlockChecked` , `NewPoWValidBlock`, `BlockConnected`, and
`BlockDisconnected` callback. Support for the other internal
validation interface methods can be added in the future.

The validation interface follows an architecture for defining its
callbacks and ownership that is similar to the notifications.

The task runner is created internally with a context, which itself
internally creates a unique ValidationSignals object. When the user
creates a new chainstate manager the validation signals are internally
passed to the chainstate manager through the context.

A validation interface can register for validation events with a
context. Internally the passed in validation interface is registerd with
the validation signals of a context.

The callbacks block any further validation execution when they are
called. It is up to the user to either multiplex them, or use them
otherwise in a multithreaded mechanism to make processing the validation
events non-blocking.

I.e. for a synchronous mechanism, the user executes instructions
directly at the end of the callback function:

```mermaid
sequenceDiagram
    participant V as Validation
    participant C as Callback
    V->>C: Call callback
    Note over C: Process event (blocks)
    C-->>V: Return
    Note over V: Validation resumes

```

To avoid blocking, the user can submit the data to e.g. a worker thread
or event manager, so processing happens asynchronously:

```mermaid
sequenceDiagram
    participant V as Validation
    participant C as Callback
    participant W as Worker Thread
    V->>C: Call callback
    C->>W: Submit to worker thread
    C-->>V: Return immediately
    Note over V: Validation continues
    Note over W: Process event async
```
2025-11-04 08:32:06 +01:00
TheCharlatan
d27e27758d kernel: Add interrupt function to C header
Calling interrupt can halt long-running functions associated with
objects that were created through the passed-in context.
2025-11-04 08:32:06 +01:00
TheCharlatan
1976b13be9 kernel: Add import blocks function to C header
Add `btck_import_blocks` to import block data and rebuild indexes. The
function can either reindex all existing block files if the indexes were
previously wiped through the chainstate manager options, or import
blocks from specified file paths.
2025-11-04 08:32:05 +01:00
TheCharlatan
a747ca1f51 kernel: Add chainstate load options for in-memory dbs in C header
This allows a user to run the kernel without creating on-disk files for
the block tree and chainstate indexes. This is potentially useful in
scenarios where the user needs to do some ephemeral validation
operations.

One specific use case is when linearizing the blocks on disk. The block
files store blocks out of order, so a program may utilize the library
and its header to read the blocks with one chainstate manager, and then
write them back in order, and without orphans, with another chainstate
maanger. To save disk resources and if the indexes are not required once
done, it may be beneficial to keep the indexes in memory for the
chainstate manager that writes the blocks back again.
2025-11-04 08:32:04 +01:00
TheCharlatan
070e77732c kernel: Add options for reindexing in C header
Adds options for wiping the chainstate and block tree indexes to the
chainstate manager options. In combination and once the
`*_import_blocks(...)` function is added in a later commit, this
triggers a reindex. For now, it just wipes the existing data.
2025-11-04 08:32:03 +01:00
TheCharlatan
ad80abc73d kernel: Add block validation to C header
The added function allows the user process and validate a given block
with the chainstate manager. The *_process_block(...) function does some
preliminary checks on the block before passing it to
`ProcessNewBlock(...)`. These are similar to the checks in the
`submitblock()` rpc.

Richer processing of the block validation result will be made available
in the following commits through the validation interface.

The commits also adds a utility for deserializing a `CBlock`
(`kernel_block_create()`) that may then be passed to the library for
processing.

The tests exercise the function for both mainnet and regtest. The
commit also adds the data of 206 regtest blocks (some blocks also
contain transactions).
2025-11-04 08:32:02 +01:00
TheCharlatan
cb1590b05e kernel: Add chainstate loading when instantiating a ChainstateManager
The library will now internally load the chainstate when a new
ChainstateManager is instantiated.

Options for controlling details of loading the chainstate will be added
over the next few commits.
2025-11-04 08:32:01 +01:00
TheCharlatan
e2c1bd3d71 kernel: Add chainstate manager option for setting worker threads
Re-use the same pattern used for the context options. This allows users
to set the number of threads used in the validation thread pool.
2025-11-04 08:32:00 +01:00
TheCharlatan
65571c36a2 kernel: Add chainstate manager object to C header
This is the main driver class for anything validation related, so expose
it here.

Creating the chainstate manager options will currently also trigger the
creation of their respectively configured directories.

The chainstate manager and block manager options are consolidated into a
single object. The kernel might eventually introduce a separate block
manager object for the purposes of being a light-weight block store
reader.

The chainstate manager will associate with the context with which it was
created for the duration of its lifetime and it keeps it in memory with
a shared pointer.

The tests now also create dedicated temporary directories. This is
similar to the behaviour in the existing unit test framework.

Co-authored-by: stickies-v <stickies-v@protonmail.com>
2025-11-04 08:31:59 +01:00
TheCharlatan
c62f657ba3 kernel: Add notifications context option to C header
The notifications are used for notifying on connected blocks and on
warning and fatal error conditions.

The user of the C header may define callbacks that gets passed to the
internal notification object in the
`kernel_NotificationInterfaceCallbacks` struct.

Each of the callbacks take a `user_data` argument that gets populated
from the `user_data` value in the struct. It can be used to recreate the
structure containing the callbacks on the user's side, or to give the
callbacks additional contextual information.
2025-11-04 08:31:58 +01:00
TheCharlatan
9e1bac4585 kernel: Add chain params context option to C header
As a first option, add the chainparams. For now these can only be
instantiated with default values. In future they may be expanded to take
their own options for regtest and signet configurations.

This commit also introduces a unique pattern for setting the option
values when calling the `*_set(...)` function.
2025-11-04 08:31:58 +01:00
TheCharlatan
337ea860df kernel: Add kernel library context object
The context introduced here holds the objects that will be required for
running validation tasks, such as the chosen chain parameters, callbacks
for validation events, and interrupt handling. These will be used by the
chainstate manager introduced in subsequent commits.

This commit also introduces conventions for defining option objects. A
common pattern throughout the C header will be:
```
options = object_option_create();
object = object_create(options);
```
This allows for more consistent usage of a "builder pattern" for
objects where options can be configured independently from
instantiation.
2025-11-04 08:31:57 +01:00
TheCharlatan
28d679bad9 kernel: Add logging to kernel library C header
Exposing logging in the kernel library allows users to follow
operations. Users of the C header can use
`kernel_logging_connection_create(...)` to pass a callback function to
Bitcoin Core's internal logger. Additionally the level and category can
be globally configured.

By default, the logger buffers messages until
`kernel_loggin_connection_create(...)` is called. If the user does not
want any logging messages, it is recommended that
`kernel_disable_logging()` is called, which permanently disables the
logging and any buffering of messages.

Co-authored-by: stringintech <stringintech@gmail.com>
2025-11-04 08:31:56 +01:00
TheCharlatan
2cf136dec4 kernel: Introduce initial kernel C header API
As a first step, implement the equivalent of what was implemented in the
now deprecated libbitcoinconsensus header. Also add a test binary to
exercise the header and library.

Unlike the deprecated libbitcoinconsensus the kernel library can now use
the hardware-accelerated sha256 implementations thanks for its
statically-initialzed context. The functions kept around for
backwards-compatibility in the libbitcoinconsensus header are not ported
over. As a new header, it should not be burdened by previous
implementations. Also add a new error code for handling invalid flag
combinations, which would otherwise cause a crash.

The macros used in the new C header were adapted from the libsecp256k1
header.

To make use of the C header from C++ code, a C++ header is also
introduced for wrapping the C header. This makes it safer and easier to
use from C++ code.

Co-authored-by: stickies-v <stickies-v@protonmail.com>
2025-11-04 08:31:51 +01:00
Hennadii Stepanov
e15e8cbada qt: Modernize custom filtering
In `QSortFilterProxyModel`, `invalidateFilter()` is scheduled for
deprecation in Qt 6.13.
`beginFilterChange()` was introduced in Qt 6.9.
`endFilterChange()` was introduced in Qt 6.10.
2025-11-03 16:45:17 +00:00