LCOV - code coverage report
Current view: top level - src/kernel - bitcoinkernel.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 83.1 % 854 710
Test Date: 2026-11-27 06:15:43 Functions: 94.2 % 243 229
Branches: 53.2 % 682 363

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2022-present The Bitcoin Core developers
       2                 :             : // Distributed under the MIT software license, see the accompanying
       3                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :             : 
       5                 :             : #define BITCOINKERNEL_BUILD
       6                 :             : 
       7                 :             : #include <kernel/bitcoinkernel.h>
       8                 :             : 
       9                 :             : #include <attributes.h>
      10                 :             : #include <chain.h>
      11                 :             : #include <coins.h>
      12                 :             : #include <consensus/tx_check.h>
      13                 :             : #include <consensus/validation.h>
      14                 :             : #include <dbwrapper.h>
      15                 :             : #include <kernel/caches.h>
      16                 :             : #include <kernel/chainparams.h>
      17                 :             : #include <kernel/checks.h>
      18                 :             : #include <kernel/context.h>
      19                 :             : #include <kernel/notifications_interface.h>
      20                 :             : #include <kernel/warning.h>
      21                 :             : #include <node/blockstorage.h>
      22                 :             : #include <node/chainstate.h>
      23                 :             : #include <primitives/block.h>
      24                 :             : #include <primitives/transaction.h>
      25                 :             : #include <script/interpreter.h>
      26                 :             : #include <script/script.h>
      27                 :             : #include <script/verify_flags.h>
      28                 :             : #include <serialize.h>
      29                 :             : #include <streams.h>
      30                 :             : #include <sync.h>
      31                 :             : #include <uint256.h>
      32                 :             : #include <undo.h>
      33                 :             : #include <util/check.h>
      34                 :             : #include <util/fs.h>
      35                 :             : #include <util/log.h>
      36                 :             : #include <util/result.h>
      37                 :             : #include <util/signalinterrupt.h>
      38                 :             : #include <util/stdmutex.h>
      39                 :             : #include <util/string.h>
      40                 :             : #include <util/task_runner.h>
      41                 :             : #include <util/time.h>
      42                 :             : #include <util/translation.h>
      43                 :             : #include <validation.h>
      44                 :             : #include <validationinterface.h>
      45                 :             : 
      46                 :             : #include <atomic>
      47                 :             : #include <cstddef>
      48                 :             : #include <cstring>
      49                 :             : #include <exception>
      50                 :             : #include <iterator>
      51                 :             : #include <limits>
      52                 :             : #include <list>
      53                 :             : #include <memory>
      54                 :             : #include <optional>
      55                 :             : #include <span>
      56                 :             : #include <stdexcept>
      57                 :             : #include <string>
      58                 :             : #include <string_view>
      59                 :             : #include <tuple>
      60                 :             : #include <utility>
      61                 :             : #include <vector>
      62                 :             : 
      63                 :             : namespace Consensus {
      64                 :             : struct Params;
      65                 :             : } // namespace Consensus
      66                 :             : 
      67                 :             : using kernel::ChainstateRole;
      68                 :             : using util::ImmediateTaskRunner;
      69                 :             : 
      70                 :             : // Define G_TRANSLATION_FUN symbol in libbitcoinkernel library so users of the
      71                 :             : // library aren't required to export this symbol
      72                 :             : extern const TranslateFn G_TRANSLATION_FUN{nullptr};
      73                 :             : 
      74                 :             : static const kernel::Context btck_context_static{};
      75                 :             : 
      76                 :             : namespace {
      77                 :             : 
      78                 :          80 : bool is_valid_flag_combination(script_verify_flags flags)
      79                 :             : {
      80   [ -  +  -  - ]:          80 :     if (flags & SCRIPT_VERIFY_CLEANSTACK && ~flags & (SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS)) return false;
      81   [ +  +  -  + ]:          80 :     if (flags & SCRIPT_VERIFY_WITNESS && ~flags & SCRIPT_VERIFY_P2SH) return false;
      82                 :             :     return true;
      83                 :             : }
      84                 :             : 
      85                 :             : class WriterStream
      86                 :             : {
      87                 :             : private:
      88                 :             :     btck_WriteBytes m_writer;
      89                 :             :     void* m_user_data;
      90                 :             : 
      91                 :             : public:
      92                 :          36 :     WriterStream(btck_WriteBytes writer, void* user_data)
      93                 :          36 :         : m_writer{writer}, m_user_data{user_data} {}
      94                 :             : 
      95                 :             :     //
      96                 :             :     // Stream subset
      97                 :             :     //
      98                 :         768 :     void write(std::span<const std::byte> src)
      99                 :             :     {
     100         [ -  + ]:         768 :         if (m_writer(src.data(), src.size(), m_user_data) != 0) {
     101         [ #  # ]:           0 :             throw std::runtime_error("Failed to write serialization data");
     102                 :             :         }
     103                 :         768 :     }
     104                 :             : 
     105                 :             :     template <typename T>
     106                 :          36 :     WriterStream& operator<<(const T& obj)
     107                 :             :     {
     108   [ +  -  +  - ]:          36 :         ::Serialize(*this, obj);
     109                 :          36 :         return *this;
     110                 :             :     }
     111                 :             : };
     112                 :             : 
     113                 :             : template <typename C, typename CPP>
     114                 :             : struct Handle {
     115                 :             :     static C* ref(CPP* cpp_type)
     116                 :             :     {
     117                 :             :         return reinterpret_cast<C*>(cpp_type);
     118                 :             :     }
     119                 :             : 
     120                 :             :     static const C* ref(const CPP* cpp_type)
     121                 :             :     {
     122                 :             :         return reinterpret_cast<const C*>(cpp_type);
     123                 :             :     }
     124                 :             : 
     125                 :             :     template <typename... Args>
     126                 :        8760 :     static C* create(Args&&... args)
     127                 :             :     {
     128                 :        8760 :         auto cpp_obj{std::make_unique<CPP>(std::forward<Args>(args)...)};
     129                 :       17520 :         return ref(cpp_obj.release());
     130                 :        8760 :     }
     131                 :             : 
     132                 :         835 :     static C* copy(const C* ptr)
     133                 :             :     {
     134                 :         835 :         auto cpp_obj{std::make_unique<CPP>(get(ptr))};
     135                 :        1670 :         return ref(cpp_obj.release());
     136                 :         835 :     }
     137                 :             : 
     138                 :             :     static const CPP& get(const C* ptr)
     139                 :             :     {
     140                 :             :         return *reinterpret_cast<const CPP*>(ptr);
     141                 :             :     }
     142                 :             : 
     143                 :             :     static CPP& get(C* ptr)
     144                 :             :     {
     145                 :             :         return *reinterpret_cast<CPP*>(ptr);
     146                 :             :     }
     147                 :             : 
     148                 :        9617 :     static void operator delete(void* ptr)
     149                 :             :     {
     150         [ +  - ]:       17993 :         delete reinterpret_cast<CPP*>(ptr);
     151                 :        9617 :     }
     152                 :             : };
     153                 :             : 
     154                 :             : } // namespace
     155                 :             : 
     156                 :             : struct btck_BlockTreeEntry: Handle<btck_BlockTreeEntry, CBlockIndex> {};
     157                 :             : struct btck_LogEntry : Handle<btck_LogEntry, util::log::Entry> {};
     158                 :             : struct btck_Block : Handle<btck_Block, std::shared_ptr<const CBlock>> {};
     159                 :             : struct btck_BlockValidationState : Handle<btck_BlockValidationState, BlockValidationState> {};
     160                 :             : struct btck_TxValidationState : Handle<btck_TxValidationState, TxValidationState> {};
     161                 :             : 
     162                 :             : namespace {
     163                 :             : 
     164                 :           3 : constexpr util::log::Level to_util(btck_LogLevel level)
     165                 :             : {
     166   [ +  +  -  -  :           3 :     switch (level) {
                   -  - ]
     167                 :             :     case btck_LogLevel_TRACE: {
     168                 :             :         return util::log::Level::Trace;
     169                 :             :     }
     170                 :           1 :     case btck_LogLevel_DEBUG: {
     171                 :           1 :         return util::log::Level::Debug;
     172                 :             :     }
     173                 :           2 :     case btck_LogLevel_INFO: {
     174                 :           2 :         return util::log::Level::Info;
     175                 :             :     }
     176                 :           0 :     case btck_LogLevel_WARNING: {
     177                 :           0 :         return util::log::Level::Warning;
     178                 :             :     }
     179                 :           0 :     case btck_LogLevel_ERROR: {
     180                 :           0 :         return util::log::Level::Error;
     181                 :             :     }
     182                 :             :     }
     183                 :           0 :     AssertUnreachable();
     184                 :             : }
     185                 :             : 
     186                 :         859 : btck_SynchronizationState cast_state(SynchronizationState state)
     187                 :             : {
     188   [ +  -  -  + ]:         859 :     switch (state) {
     189                 :             :     case SynchronizationState::INIT_REINDEX:
     190                 :             :         return btck_SynchronizationState_INIT_REINDEX;
     191                 :         856 :     case SynchronizationState::INIT_DOWNLOAD:
     192                 :         856 :         return btck_SynchronizationState_INIT_DOWNLOAD;
     193                 :           0 :     case SynchronizationState::POST_INIT:
     194                 :           0 :         return btck_SynchronizationState_POST_INIT;
     195                 :             :     } // no default case, so the compiler can warn about missing cases
     196                 :           0 :     AssertUnreachable();
     197                 :             : }
     198                 :             : 
     199                 :         435 : btck_Warning cast_btck_warning(kernel::Warning warning)
     200                 :             : {
     201      [ +  -  - ]:         435 :     switch (warning) {
     202                 :             :     case kernel::Warning::UNKNOWN_NEW_RULES_ACTIVATED:
     203                 :             :         return btck_Warning_UNKNOWN_NEW_RULES_ACTIVATED;
     204                 :         435 :     case kernel::Warning::LARGE_WORK_INVALID_CHAIN:
     205                 :         435 :         return btck_Warning_LARGE_WORK_INVALID_CHAIN;
     206                 :             :     } // no default case, so the compiler can warn about missing cases
     207                 :           0 :     AssertUnreachable();
     208                 :             : }
     209                 :             : 
     210                 :         372 : constexpr btck_LogLevel to_btck(util::log::Level level)
     211                 :             : {
     212   [ -  +  -  +  :         372 :     switch (level) {
                   -  - ]
     213                 :             :     case util::log::Level::Trace: {
     214                 :             :         return btck_LogLevel_TRACE;
     215                 :             :     }
     216                 :           0 :     case util::log::Level::Debug: {
     217                 :           0 :         return btck_LogLevel_DEBUG;
     218                 :             :     }
     219                 :         366 :     case util::log::Level::Info: {
     220                 :         366 :         return btck_LogLevel_INFO;
     221                 :             :     }
     222                 :           0 :     case util::log::Level::Warning: {
     223                 :           0 :         return btck_LogLevel_WARNING;
     224                 :             :     }
     225                 :           6 :     case util::log::Level::Error: {
     226                 :           6 :         return btck_LogLevel_ERROR;
     227                 :             :     }
     228                 :             :     } // no default case, so the compiler can warn about missing cases
     229                 :           0 :     AssertUnreachable();
     230                 :             : }
     231                 :             : 
     232                 :         378 : constexpr btck_StringView to_btck(std::string_view str)
     233                 :             : {
     234                 :         378 :     return {.data = str.data(), .len = str.size()};
     235                 :             : }
     236                 :             : 
     237                 :         372 : constexpr btck_LogCategory to_btck(BCLog::LogFlags flag)
     238                 :             : {
     239   [ -  -  -  -  :         372 :     switch (flag) {
          -  -  -  -  -  
             -  -  -  + ]
     240                 :             :     case BCLog::LogFlags::ALL: {
     241                 :             :         return btck_LogCategory_NONE;
     242                 :             :     }
     243                 :           0 :     case BCLog::LogFlags::BENCH: {
     244                 :           0 :         return btck_LogCategory_BENCH;
     245                 :             :     }
     246                 :           0 :     case BCLog::LogFlags::BLOCKSTORAGE: {
     247                 :           0 :         return btck_LogCategory_BLOCKSTORAGE;
     248                 :             :     }
     249                 :           0 :     case BCLog::LogFlags::COINDB: {
     250                 :           0 :         return btck_LogCategory_COINDB;
     251                 :             :     }
     252                 :           0 :     case BCLog::LogFlags::LEVELDB: {
     253                 :           0 :         return btck_LogCategory_LEVELDB;
     254                 :             :     }
     255                 :             : #ifdef DEBUG_LOCKCONTENTION
     256                 :             :     case BCLog::LogFlags::LOCK: {
     257                 :             :         return btck_LogCategory_LOCK;
     258                 :             :     }
     259                 :             : #endif
     260                 :           0 :     case BCLog::LogFlags::MEMPOOL: {
     261                 :           0 :         return btck_LogCategory_MEMPOOL;
     262                 :             :     }
     263                 :           0 :     case BCLog::LogFlags::PRUNE: {
     264                 :           0 :         return btck_LogCategory_PRUNE;
     265                 :             :     }
     266                 :           0 :     case BCLog::LogFlags::RAND: {
     267                 :           0 :         return btck_LogCategory_RAND;
     268                 :             :     }
     269                 :           0 :     case BCLog::LogFlags::REINDEX: {
     270                 :           0 :         return btck_LogCategory_REINDEX;
     271                 :             :     }
     272                 :           0 :     case BCLog::LogFlags::TXPACKAGES: {
     273                 :           0 :         return btck_LogCategory_TXPACKAGES;
     274                 :             :     }
     275                 :           0 :     case BCLog::LogFlags::VALIDATION: {
     276                 :           0 :         return btck_LogCategory_VALIDATION;
     277                 :             :     }
     278                 :           0 :     case BCLog::LogFlags::KERNEL: {
     279                 :           0 :         return btck_LogCategory_KERNEL;
     280                 :             :     }
     281                 :           0 :     default: {
     282                 :             :         // Every category the kernel library can emit must be mapped above. This cannot be enforced
     283                 :             :         // at compile time, so abort in debug builds to catch it early, and deliver the entry as
     284                 :             :         // uncategorized otherwise.
     285                 :           0 :         Assume(false);
     286                 :           0 :         return btck_LogCategory_NONE;
     287                 :             :     }
     288                 :             :     }
     289                 :             : }
     290                 :             : 
     291                 :             : class KernelNotifications final : public kernel::Notifications
     292                 :             : {
     293                 :             : private:
     294                 :             :     btck_NotificationInterfaceCallbacks m_cbs;
     295                 :             : 
     296                 :             : public:
     297                 :          20 :     KernelNotifications(btck_NotificationInterfaceCallbacks cbs)
     298                 :          20 :         : m_cbs{cbs}
     299                 :             :     {
     300                 :             :     }
     301                 :             : 
     302                 :          20 :     ~KernelNotifications()
     303                 :          20 :     {
     304   [ +  +  +  - ]:          20 :         if (m_cbs.user_data && m_cbs.user_data_destroy) {
     305                 :          14 :             m_cbs.user_data_destroy(m_cbs.user_data);
     306                 :             :         }
     307                 :          20 :         m_cbs.user_data_destroy = nullptr;
     308                 :          20 :         m_cbs.user_data = nullptr;
     309                 :          20 :     }
     310                 :             : 
     311                 :         437 :     kernel::InterruptResult blockTip(SynchronizationState state, const CBlockIndex& index, double verification_progress) override
     312                 :             :     {
     313         [ +  + ]:         437 :         if (m_cbs.block_tip) m_cbs.block_tip(m_cbs.user_data, cast_state(state), btck_BlockTreeEntry::ref(&index), verification_progress);
     314                 :         437 :         return {};
     315                 :             :     }
     316                 :         424 :     void headerTip(SynchronizationState state, int64_t height, int64_t timestamp, bool presync) override
     317                 :             :     {
     318   [ +  -  +  - ]:         848 :         if (m_cbs.header_tip) m_cbs.header_tip(m_cbs.user_data, cast_state(state), height, timestamp, presync ? 1 : 0);
     319                 :         424 :     }
     320                 :          63 :     void progress(const bilingual_str& title, int progress_percent, bool resume_possible) override
     321                 :             :     {
     322   [ +  +  +  -  :         124 :         if (m_cbs.progress) m_cbs.progress(m_cbs.user_data, title.original.c_str(), title.original.length(), progress_percent, resume_possible ? 1 : 0);
                   -  + ]
     323                 :          63 :     }
     324                 :           0 :     void warningSet(kernel::Warning id, const bilingual_str& message) override
     325                 :             :     {
     326   [ #  #  #  # ]:           0 :         if (m_cbs.warning_set) m_cbs.warning_set(m_cbs.user_data, cast_btck_warning(id), message.original.c_str(), message.original.length());
     327                 :           0 :     }
     328                 :         437 :     void warningUnset(kernel::Warning id) override
     329                 :             :     {
     330         [ +  + ]:         437 :         if (m_cbs.warning_unset) m_cbs.warning_unset(m_cbs.user_data, cast_btck_warning(id));
     331                 :         437 :     }
     332                 :           0 :     void flushError(const bilingual_str& message) override
     333                 :             :     {
     334   [ #  #  #  # ]:           0 :         if (m_cbs.flush_error) m_cbs.flush_error(m_cbs.user_data, message.original.c_str(), message.original.length());
     335                 :           0 :     }
     336                 :           0 :     void fatalError(const bilingual_str& message) override
     337                 :             :     {
     338   [ #  #  #  # ]:           0 :         if (m_cbs.fatal_error) m_cbs.fatal_error(m_cbs.user_data, message.original.c_str(), message.original.length());
     339                 :           0 :     }
     340                 :             : };
     341                 :             : 
     342                 :             : class KernelValidationInterface final : public CValidationInterface
     343                 :             : {
     344                 :             : public:
     345                 :             :     btck_ValidationInterfaceCallbacks m_cbs;
     346                 :             : 
     347                 :           6 :     explicit KernelValidationInterface(const btck_ValidationInterfaceCallbacks vi_cbs) : m_cbs{vi_cbs} {}
     348                 :             : 
     349                 :           6 :     ~KernelValidationInterface()
     350                 :           6 :     {
     351   [ +  -  +  - ]:           6 :         if (m_cbs.user_data && m_cbs.user_data_destroy) {
     352                 :           6 :             m_cbs.user_data_destroy(m_cbs.user_data);
     353                 :             :         }
     354                 :           6 :         m_cbs.user_data = nullptr;
     355                 :           6 :         m_cbs.user_data_destroy = nullptr;
     356                 :           6 :     }
     357                 :             : 
     358                 :             : protected:
     359                 :           5 :     void BlockChecked(const std::shared_ptr<const CBlock>& block, const BlockValidationState& stateIn) override
     360                 :             :     {
     361         [ +  - ]:           5 :         if (m_cbs.block_checked) {
     362                 :           5 :             m_cbs.block_checked(m_cbs.user_data,
     363                 :             :                                 btck_Block::copy(btck_Block::ref(&block)),
     364                 :             :                                 btck_BlockValidationState::ref(&stateIn));
     365                 :             :         }
     366                 :           5 :     }
     367                 :             : 
     368                 :           0 :     void NewPoWValidBlock(const CBlockIndex* pindex, const std::shared_ptr<const CBlock>& block) override
     369                 :             :     {
     370         [ #  # ]:           0 :         if (m_cbs.pow_valid_block) {
     371                 :           0 :             m_cbs.pow_valid_block(m_cbs.user_data,
     372                 :             :                                   btck_Block::copy(btck_Block::ref(&block)),
     373                 :             :                                   btck_BlockTreeEntry::ref(pindex));
     374                 :             :         }
     375                 :           0 :     }
     376                 :             : 
     377                 :           4 :     void BlockConnected(const ChainstateRole& role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) override
     378                 :             :     {
     379         [ +  - ]:           4 :         if (m_cbs.block_connected) {
     380                 :           4 :             m_cbs.block_connected(m_cbs.user_data,
     381                 :             :                                   btck_Block::copy(btck_Block::ref(&block)),
     382                 :             :                                   btck_BlockTreeEntry::ref(pindex));
     383                 :             :         }
     384                 :           4 :     }
     385                 :             : 
     386                 :           0 :     void BlockDisconnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) override
     387                 :             :     {
     388         [ #  # ]:           0 :         if (m_cbs.block_disconnected) {
     389                 :           0 :             m_cbs.block_disconnected(m_cbs.user_data,
     390                 :             :                                      btck_Block::copy(btck_Block::ref(&block)),
     391                 :             :                                      btck_BlockTreeEntry::ref(pindex));
     392                 :             :         }
     393                 :           0 :     }
     394                 :             : };
     395                 :             : 
     396                 :          20 : struct ContextOptions {
     397                 :             :     mutable Mutex m_mutex;
     398                 :             :     std::unique_ptr<const CChainParams> m_chainparams GUARDED_BY(m_mutex);
     399                 :             :     std::shared_ptr<KernelNotifications> m_notifications GUARDED_BY(m_mutex);
     400                 :             :     std::shared_ptr<KernelValidationInterface> m_validation_interface GUARDED_BY(m_mutex);
     401                 :             : };
     402                 :             : 
     403                 :             : class Context
     404                 :             : {
     405                 :             : public:
     406                 :             :     std::unique_ptr<kernel::Context> m_context;
     407                 :             : 
     408                 :             :     std::shared_ptr<KernelNotifications> m_notifications;
     409                 :             : 
     410                 :             :     std::unique_ptr<util::SignalInterrupt> m_interrupt;
     411                 :             : 
     412                 :             :     std::unique_ptr<ValidationSignals> m_signals;
     413                 :             : 
     414                 :             :     std::unique_ptr<const CChainParams> m_chainparams;
     415                 :             : 
     416                 :             :     std::shared_ptr<KernelValidationInterface> m_validation_interface;
     417                 :             : 
     418                 :          20 :     Context(const ContextOptions* options, bool& sane)
     419                 :          20 :         : m_context{std::make_unique<kernel::Context>()},
     420   [ +  -  +  - ]:          20 :           m_interrupt{std::make_unique<util::SignalInterrupt>()}
     421                 :             :     {
     422         [ +  - ]:          20 :         if (options) {
     423         [ +  - ]:          20 :             LOCK(options->m_mutex);
     424         [ +  + ]:          20 :             if (options->m_chainparams) {
     425         [ +  - ]:          14 :                 m_chainparams = std::make_unique<const CChainParams>(*options->m_chainparams);
     426                 :             :             }
     427         [ +  + ]:          20 :             if (options->m_notifications) {
     428                 :          14 :                 m_notifications = options->m_notifications;
     429                 :             :             }
     430         [ +  + ]:          20 :             if (options->m_validation_interface) {
     431   [ +  -  +  - ]:           6 :                 m_signals = std::make_unique<ValidationSignals>(std::make_unique<ImmediateTaskRunner>());
     432                 :           6 :                 m_validation_interface = options->m_validation_interface;
     433   [ +  -  +  - ]:          18 :                 m_signals->RegisterSharedValidationInterface(m_validation_interface);
     434                 :             :             }
     435                 :          20 :         }
     436                 :             : 
     437         [ +  + ]:          20 :         if (!m_chainparams) {
     438         [ +  - ]:           6 :             m_chainparams = CChainParams::Main();
     439                 :             :         }
     440         [ +  + ]:          20 :         if (!m_notifications) {
     441         [ +  - ]:          12 :             m_notifications = std::make_shared<KernelNotifications>(btck_NotificationInterfaceCallbacks{
     442         [ -  + ]:           6 :                 nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr});
     443                 :             :         }
     444                 :             : 
     445   [ +  -  -  + ]:          20 :         if (!kernel::SanityChecks(*m_context)) {
     446                 :           0 :             sane = false;
     447                 :             :         }
     448   [ -  -  -  - ]:          20 :     }
     449                 :             : 
     450                 :          20 :     ~Context()
     451                 :             :     {
     452         [ +  + ]:          20 :         if (m_signals) {
     453   [ +  -  +  - ]:          18 :             m_signals->UnregisterSharedValidationInterface(m_validation_interface);
     454                 :             :         }
     455   [ +  +  +  - ]:          46 :     }
     456                 :             : };
     457                 :             : 
     458                 :             : //! Helper struct to wrap the ChainstateManager-related Options
     459                 :             : struct ChainstateManagerOptions {
     460                 :             :     mutable Mutex m_mutex;
     461                 :             :     ChainstateManager::Options m_chainman_options GUARDED_BY(m_mutex);
     462                 :             :     node::BlockManager::Options m_blockman_options GUARDED_BY(m_mutex);
     463                 :             :     std::shared_ptr<const Context> m_context;
     464                 :             :     node::ChainstateLoadOptions m_chainstate_load_options GUARDED_BY(m_mutex);
     465                 :             :     uint64_t m_db_cache_bytes GUARDED_BY(m_mutex){DEFAULT_KERNEL_CACHE};
     466                 :             : 
     467                 :          17 :     ChainstateManagerOptions(const std::shared_ptr<const Context>& context, const fs::path& data_dir, const fs::path& blocks_dir)
     468         [ +  - ]:          17 :         : m_chainman_options{ChainstateManager::Options{
     469                 :          17 :               .chainparams = *context->m_chainparams,
     470                 :             :               .datadir = data_dir,
     471         [ +  - ]:          17 :               .notifications = *context->m_notifications,
     472         [ +  - ]:          17 :               .signals = context->m_signals.get()}},
     473         [ +  - ]:          34 :           m_blockman_options{node::BlockManager::Options{
     474         [ +  - ]:          17 :               .chainparams = *context->m_chainparams,
     475                 :             :               .blocks_dir = blocks_dir,
     476         [ +  - ]:          17 :               .notifications = *context->m_notifications,
     477                 :             :               .block_tree_db_params = DBParams{
     478   [ +  -  +  - ]:          51 :                   .path = data_dir / "blocks" / "index",
     479                 :          17 :                   .cache_bytes = kernel::CacheSizes{DEFAULT_KERNEL_CACHE}.block_tree_db,
     480                 :             :               }}},
     481         [ +  - ]:          51 :           m_context{context}, m_chainstate_load_options{node::ChainstateLoadOptions{}}
     482                 :             :     {
     483                 :          17 :     }
     484                 :             : };
     485                 :             : 
     486                 :             : struct ChainMan {
     487                 :             :     std::unique_ptr<ChainstateManager> m_chainman;
     488                 :             :     std::shared_ptr<const Context> m_context;
     489                 :             : 
     490                 :          17 :     ChainMan(std::unique_ptr<ChainstateManager> chainman, std::shared_ptr<const Context> context)
     491                 :          17 :         : m_chainman(std::move(chainman)), m_context(std::move(context)) {}
     492                 :             : };
     493                 :             : 
     494                 :             : struct UserDataDeleter {
     495                 :             :     btck_DestroyCallback destroy;
     496                 :           9 :     void operator()(void* user_data) const
     497                 :             :     {
     498         [ +  - ]:           9 :         if (destroy) destroy(user_data);
     499                 :             :     }
     500                 :             : };
     501                 :             : //! Owns a caller-provided user_data pointer and frees it with its destroy callback.
     502                 :             : using UserData = std::unique_ptr<void, UserDataDeleter>;
     503                 :             : 
     504                 :             : //! Holds state for kernel logging subscribers: the registered callbacks and the minimum level.
     505                 :             : //! Shared by all btck_LoggingConnection instances.
     506                 :           6 : class KernelLogger
     507                 :             : {
     508                 :             :     //! A registered btck_LogCallback. Owns user_data.
     509                 :          18 :     struct Callback {
     510                 :             :         btck_LogCallback fn;
     511                 :             :         UserData user_data;
     512                 :             : 
     513                 :         378 :         void operator()(const btck_LogEntry* entry) const { fn(user_data.get(), entry); }
     514                 :             :     };
     515                 :             : 
     516                 :             :     mutable StdMutex m_mutex;
     517                 :             :     //! All registered callbacks that are executed through Log.
     518                 :             :     std::list<Callback> m_callbacks GUARDED_BY(m_mutex);
     519                 :             :     //! Size of m_callbacks. Can be stale when read without m_mutex.
     520                 :             :     std::atomic<size_t> m_callback_count{0};
     521                 :             :     //! Entries below this level are not delivered.
     522                 :             :     std::atomic<util::log::Level> m_min_level{util::log::Level::Info};
     523                 :             : 
     524                 :             :     //! Unregisters and destroys the callback. Waits for an in-flight Log to finish, then destroys
     525                 :             :     //! the callback (and its user_data) outside m_mutex.
     526                 :             :     void UnregisterCallback(std::list<Callback>::iterator it) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
     527                 :             : 
     528                 :             : public:
     529                 :             :     //! Owns a registered logging callback. Unregisters it on destruction. A moved-from handle
     530                 :             :     //! owns nothing and does not unregister.
     531                 :             :     class CallbackHandle
     532                 :             :     {
     533                 :             :         KernelLogger* m_logger;
     534                 :             :         std::list<Callback>::iterator m_it;
     535                 :             : 
     536                 :             :     public:
     537                 :           9 :         CallbackHandle(KernelLogger& logger LIFETIMEBOUND, std::list<Callback>::iterator it)
     538                 :           9 :             : m_logger{&logger}, m_it{it} {}
     539                 :           9 :         CallbackHandle(CallbackHandle&& other) noexcept
     540                 :           9 :             : m_logger{std::exchange(other.m_logger, nullptr)}, m_it{other.m_it} {}
     541                 :             :         CallbackHandle& operator=(CallbackHandle&&) = delete;
     542                 :          18 :         ~CallbackHandle()
     543                 :             :         {
     544         [ +  + ]:          18 :             if (m_logger) m_logger->UnregisterCallback(m_it);
     545                 :          18 :         }
     546                 :             :     };
     547                 :             : 
     548                 :             :     //! Registers a logging callback. Takes ownership of user_data, also when registration fails.
     549                 :             :     [[nodiscard]] CallbackHandle RegisterCallback(btck_LogCallback fn, UserData user_data) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
     550                 :             :     //! Set the minimum log level.
     551                 :           3 :     void SetMinLevel(btck_LogLevel level)
     552                 :             :     {
     553                 :           3 :         m_min_level.store(to_util(level), std::memory_order_relaxed);
     554                 :           3 :     }
     555                 :             : 
     556                 :             :     //! True if level is not below minimum level and at least one callback is registered.
     557                 :        7160 :     bool ShouldLog(util::log::Level level) const
     558                 :             :     {
     559   [ +  +  +  + ]:        7160 :         return level >= m_min_level.load(std::memory_order_relaxed) &&
     560         [ +  + ]:        1155 :                m_callback_count.load(std::memory_order_relaxed) > 0;
     561                 :             :     }
     562                 :             :     //! Deliver the entry to every registered callback while holding m_mutex, regardless of its
     563                 :             :     //! level. Exceptions from callbacks are swallowed.
     564                 :             :     void Log(const util::log::Entry& entry) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
     565                 :             :     //! Log() the entry if ShouldLog() passes for its level.
     566                 :        1151 :     void MaybeLog(const util::log::Entry& entry) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
     567                 :             :     {
     568         [ +  + ]:        1151 :         if (ShouldLog(entry.level)) {
     569                 :         376 :             Log(entry);
     570                 :             :         }
     571                 :        1151 :     }
     572                 :             : };
     573                 :             : 
     574                 :           9 : KernelLogger::CallbackHandle KernelLogger::RegisterCallback(btck_LogCallback fn, UserData user_data)
     575                 :             : {
     576                 :             :     // Construct before locking so that a failed push_back destroys user_data outside m_mutex.
     577         [ +  - ]:           9 :     Callback cb{fn, std::move(user_data)};
     578         [ +  - ]:           9 :     STDLOCK(m_mutex);
     579         [ +  - ]:           9 :     m_callbacks.push_back(std::move(cb));
     580                 :           9 :     m_callback_count.fetch_add(1, std::memory_order_relaxed);
     581                 :           9 :     return {*this, std::prev(m_callbacks.end())};
     582                 :           9 : }
     583                 :             : 
     584                 :           9 : void KernelLogger::UnregisterCallback(std::list<Callback>::iterator it)
     585                 :             : {
     586                 :             :     // Avoid running the callback destructor while holding m_mutex.
     587         [ +  - ]:           9 :     std::list<Callback> dying;
     588                 :           9 :     {
     589         [ +  - ]:           9 :         STDLOCK(m_mutex);
     590                 :           9 :         dying.splice(dying.begin(), m_callbacks, it);
     591                 :           9 :         m_callback_count.fetch_sub(1, std::memory_order_relaxed);
     592                 :           9 :     }
     593                 :           9 : }
     594                 :             : 
     595                 :         376 : void KernelLogger::Log(const util::log::Entry& entry) const
     596                 :             : {
     597                 :         376 :     STDLOCK(m_mutex);
     598         [ +  + ]:         754 :     for (const auto& callback : m_callbacks) {
     599                 :         378 :         try {
     600         [ +  - ]:         378 :             callback(btck_LogEntry::ref(&entry));
     601                 :           0 :         } catch (...) {
     602                 :             :             // Can't log the error here because we're already inside the logging path (would
     603                 :             :             // deadlock on m_mutex).
     604         [ -  - ]:           0 :         }
     605                 :             :     }
     606                 :         376 : }
     607                 :             : 
     608                 :             : } // namespace
     609                 :             : 
     610                 :             : struct btck_Transaction : Handle<btck_Transaction, std::shared_ptr<const CTransaction>> {};
     611                 :             : struct btck_TransactionOutput : Handle<btck_TransactionOutput, CTxOut> {};
     612                 :             : struct btck_ScriptPubkey : Handle<btck_ScriptPubkey, CScript> {};
     613                 :             : struct btck_LoggingConnection : Handle<btck_LoggingConnection, KernelLogger::CallbackHandle> {};
     614                 :             : struct btck_ContextOptions : Handle<btck_ContextOptions, ContextOptions> {};
     615                 :             : struct btck_Context : Handle<btck_Context, std::shared_ptr<const Context>> {};
     616                 :             : struct btck_ChainParameters : Handle<btck_ChainParameters, CChainParams> {};
     617                 :             : struct btck_ChainstateManagerOptions : Handle<btck_ChainstateManagerOptions, ChainstateManagerOptions> {};
     618                 :             : struct btck_ChainstateManager : Handle<btck_ChainstateManager, ChainMan> {};
     619                 :             : struct btck_Chain : Handle<btck_Chain, CChain> {};
     620                 :             : struct btck_BlockSpentOutputs : Handle<btck_BlockSpentOutputs, std::shared_ptr<CBlockUndo>> {};
     621                 :             : struct btck_TransactionSpentOutputs : Handle<btck_TransactionSpentOutputs, CTxUndo> {};
     622                 :             : struct btck_Coin : Handle<btck_Coin, Coin> {};
     623                 :             : struct btck_BlockHash : Handle<btck_BlockHash, uint256> {};
     624                 :             : struct btck_TransactionInput : Handle<btck_TransactionInput, CTxIn> {};
     625                 :             : struct btck_WitnessStack : Handle<btck_WitnessStack, CScriptWitness> {};
     626                 :             : struct btck_TransactionOutPoint: Handle<btck_TransactionOutPoint, COutPoint> {};
     627                 :             : struct btck_Txid: Handle<btck_Txid, Txid> {};
     628                 :             : struct btck_Wtxid: Handle<btck_Wtxid, Wtxid> {};
     629                 :             : struct btck_PrecomputedTransactionData : Handle<btck_PrecomputedTransactionData, PrecomputedTransactionData> {};
     630                 :             : struct btck_BlockHeader: Handle<btck_BlockHeader, CBlockHeader> {};
     631                 :             : struct btck_ConsensusParams: Handle<btck_ConsensusParams, Consensus::Params> {};
     632                 :             : 
     633                 :          31 : btck_Transaction* btck_transaction_create(const void* raw_transaction, size_t raw_transaction_len)
     634                 :             : {
     635         [ -  + ]:          31 :     assert(raw_transaction != nullptr || raw_transaction_len == 0);
     636                 :          31 :     try {
     637         [ +  + ]:          31 :         SpanReader stream{std::span{reinterpret_cast<const std::byte*>(raw_transaction), raw_transaction_len}};
     638   [ +  +  +  -  :          31 :         return btck_Transaction::create(std::make_shared<const CTransaction>(deserialize, TX_WITH_WITNESS, stream));
                   -  + ]
     639                 :           3 :     } catch (...) {
     640                 :           3 :         return nullptr;
     641                 :           3 :     }
     642                 :             : }
     643                 :             : 
     644                 :         287 : size_t btck_transaction_count_outputs(const btck_Transaction* transaction)
     645                 :             : {
     646         [ -  + ]:         287 :     return btck_Transaction::get(transaction)->vout.size();
     647                 :             : }
     648                 :             : 
     649                 :         601 : const btck_TransactionOutput* btck_transaction_get_output_at(const btck_Transaction* transaction, size_t output_index)
     650                 :             : {
     651         [ -  + ]:         601 :     const CTransaction& tx = *btck_Transaction::get(transaction);
     652   [ -  +  -  + ]:         601 :     assert(output_index < tx.vout.size());
     653                 :         601 :     return btck_TransactionOutput::ref(&tx.vout[output_index]);
     654                 :             : }
     655                 :             : 
     656                 :         284 : size_t btck_transaction_count_inputs(const btck_Transaction* transaction)
     657                 :             : {
     658         [ -  + ]:         284 :     return btck_Transaction::get(transaction)->vin.size();
     659                 :             : }
     660                 :             : 
     661                 :         282 : const btck_TransactionInput* btck_transaction_get_input_at(const btck_Transaction* transaction, size_t input_index)
     662                 :             : {
     663   [ -  +  -  + ]:         282 :     assert(input_index < btck_Transaction::get(transaction)->vin.size());
     664                 :         282 :     return btck_TransactionInput::ref(&btck_Transaction::get(transaction)->vin[input_index]);
     665                 :             : }
     666                 :             : 
     667                 :           3 : uint32_t btck_transaction_get_version(const btck_Transaction* transaction)
     668                 :             : {
     669                 :           3 :     return btck_Transaction::get(transaction)->version;
     670                 :             : }
     671                 :             : 
     672                 :           1 : uint32_t btck_transaction_get_locktime(const btck_Transaction* transaction)
     673                 :             : {
     674                 :           1 :     return btck_Transaction::get(transaction)->nLockTime;
     675                 :             : }
     676                 :             : 
     677                 :        7646 : const btck_Txid* btck_transaction_get_txid(const btck_Transaction* transaction)
     678                 :             : {
     679                 :        7646 :     return btck_Txid::ref(&btck_Transaction::get(transaction)->GetHash());
     680                 :             : }
     681                 :             : 
     682                 :           2 : int btck_transaction_has_witness(const btck_Transaction* transaction)
     683                 :             : {
     684         [ +  + ]:           2 :     return btck_Transaction::get(transaction)->HasWitness() ? 1 : 0;
     685                 :             : }
     686                 :             : 
     687                 :          10 : const btck_Wtxid* btck_transaction_get_wtxid(const btck_Transaction* transaction)
     688                 :             : {
     689                 :          10 :     return btck_Wtxid::ref(&btck_Transaction::get(transaction)->GetWitnessHash());
     690                 :             : }
     691                 :             : 
     692                 :         384 : btck_Transaction* btck_transaction_copy(const btck_Transaction* transaction)
     693                 :             : {
     694                 :         384 :     return btck_Transaction::copy(transaction);
     695                 :             : }
     696                 :             : 
     697                 :          14 : int btck_transaction_to_bytes(const btck_Transaction* transaction, btck_WriteBytes writer, void* user_data)
     698                 :             : {
     699                 :          14 :     try {
     700                 :          14 :         WriterStream ws{writer, user_data};
     701         [ +  - ]:          28 :         ws << TX_WITH_WITNESS(btck_Transaction::get(transaction));
     702                 :             :         return 0;
     703                 :           0 :     } catch (...) {
     704                 :           0 :         return -1;
     705                 :           0 :     }
     706                 :             : }
     707                 :             : 
     708                 :         473 : void btck_transaction_destroy(btck_Transaction* transaction)
     709                 :             : {
     710         [ +  + ]:         473 :     delete transaction;
     711                 :         473 : }
     712                 :             : 
     713                 :          11 : btck_ScriptPubkey* btck_script_pubkey_create(const void* script_pubkey, size_t script_pubkey_len)
     714                 :             : {
     715         [ -  + ]:          11 :     assert(script_pubkey != nullptr || script_pubkey_len == 0);
     716                 :          11 :     auto data = std::span{reinterpret_cast<const uint8_t*>(script_pubkey), script_pubkey_len};
     717                 :          11 :     return btck_ScriptPubkey::create(data.begin(), data.end());
     718                 :             : }
     719                 :             : 
     720                 :         555 : int btck_script_pubkey_to_bytes(const btck_ScriptPubkey* script_pubkey_, btck_WriteBytes writer, void* user_data)
     721                 :             : {
     722                 :         555 :     const auto& script_pubkey{btck_ScriptPubkey::get(script_pubkey_)};
     723   [ +  +  +  + ]:        1317 :     return writer(script_pubkey.data(), script_pubkey.size(), user_data);
     724                 :             : }
     725                 :             : 
     726                 :          12 : btck_ScriptPubkey* btck_script_pubkey_copy(const btck_ScriptPubkey* script_pubkey)
     727                 :             : {
     728                 :          12 :     return btck_ScriptPubkey::copy(script_pubkey);
     729                 :             : }
     730                 :             : 
     731                 :          27 : void btck_script_pubkey_destroy(btck_ScriptPubkey* script_pubkey)
     732                 :             : {
     733         [ +  + ]:          27 :     delete script_pubkey;
     734                 :          27 : }
     735                 :             : 
     736                 :           5 : btck_TransactionOutput* btck_transaction_output_create(const btck_ScriptPubkey* script_pubkey, int64_t amount)
     737                 :             : {
     738                 :           5 :     return btck_TransactionOutput::create(amount, btck_ScriptPubkey::get(script_pubkey));
     739                 :             : }
     740                 :             : 
     741                 :          66 : btck_TransactionOutput* btck_transaction_output_copy(const btck_TransactionOutput* output)
     742                 :             : {
     743                 :          66 :     return btck_TransactionOutput::copy(output);
     744                 :             : }
     745                 :             : 
     746                 :         585 : const btck_ScriptPubkey* btck_transaction_output_get_script_pubkey(const btck_TransactionOutput* output)
     747                 :             : {
     748                 :         585 :     return btck_ScriptPubkey::ref(&btck_TransactionOutput::get(output).scriptPubKey);
     749                 :             : }
     750                 :             : 
     751                 :         388 : int64_t btck_transaction_output_get_amount(const btck_TransactionOutput* output)
     752                 :             : {
     753                 :         388 :     return btck_TransactionOutput::get(output).nValue;
     754                 :             : }
     755                 :             : 
     756                 :          80 : void btck_transaction_output_destroy(btck_TransactionOutput* output)
     757                 :             : {
     758         [ +  + ]:          80 :     delete output;
     759                 :          80 : }
     760                 :             : 
     761                 :         266 : btck_PrecomputedTransactionData* btck_precomputed_transaction_data_create(
     762                 :             :     const btck_Transaction* tx_to,
     763                 :             :     const btck_TransactionOutput** spent_outputs_, size_t spent_outputs_len)
     764                 :             : {
     765                 :         266 :     try {
     766         [ +  - ]:         266 :         const CTransaction& tx{*btck_Transaction::get(tx_to)};
     767         [ +  - ]:         266 :         auto txdata{btck_PrecomputedTransactionData::create()};
     768         [ +  + ]:         266 :         if (spent_outputs_ != nullptr && spent_outputs_len > 0) {
     769   [ -  +  -  + ]:          55 :             assert(spent_outputs_len == tx.vin.size());
     770                 :          55 :             std::vector<CTxOut> spent_outputs;
     771         [ +  - ]:          55 :             spent_outputs.reserve(spent_outputs_len);
     772         [ +  + ]:         117 :             for (size_t i = 0; i < spent_outputs_len; i++) {
     773                 :          62 :                 const CTxOut& tx_out{btck_TransactionOutput::get(spent_outputs_[i])};
     774         [ +  - ]:          62 :                 spent_outputs.push_back(tx_out);
     775                 :             :             }
     776         [ +  - ]:          55 :             btck_PrecomputedTransactionData::get(txdata).Init(tx, std::move(spent_outputs));
     777                 :          55 :         } else {
     778         [ +  - ]:         211 :             btck_PrecomputedTransactionData::get(txdata).Init(tx, {});
     779                 :             :         }
     780                 :             : 
     781                 :             :         return txdata;
     782                 :           0 :     } catch (...) {
     783                 :           0 :         return nullptr;
     784                 :           0 :     }
     785                 :             : }
     786                 :             : 
     787                 :           5 : btck_PrecomputedTransactionData* btck_precomputed_transaction_data_copy(const btck_PrecomputedTransactionData* precomputed_txdata)
     788                 :             : {
     789                 :           5 :     return btck_PrecomputedTransactionData::copy(precomputed_txdata);
     790                 :             : }
     791                 :             : 
     792                 :         273 : void btck_precomputed_transaction_data_destroy(btck_PrecomputedTransactionData* precomputed_txdata)
     793                 :             : {
     794         [ +  + ]:         273 :     delete precomputed_txdata;
     795                 :         273 : }
     796                 :             : 
     797                 :          80 : int btck_script_pubkey_verify(const btck_ScriptPubkey* script_pubkey,
     798                 :             :                               const int64_t amount,
     799                 :             :                               const btck_Transaction* tx_to,
     800                 :             :                               const btck_PrecomputedTransactionData* precomputed_txdata,
     801                 :             :                               const unsigned int input_index,
     802                 :             :                               const btck_ScriptVerificationFlags flags,
     803                 :             :                               btck_ScriptVerifyStatus* status)
     804                 :             : {
     805                 :             :     // Assert that all specified flags are part of the interface before continuing
     806         [ -  + ]:          80 :     assert((flags & ~btck_ScriptVerificationFlags_ALL) == 0);
     807                 :             : 
     808         [ -  + ]:          80 :     if (!is_valid_flag_combination(script_verify_flags::from_int(flags))) {
     809         [ #  # ]:           0 :         if (status) *status = btck_ScriptVerifyStatus_ERROR_INVALID_FLAGS_COMBINATION;
     810                 :           0 :         return 0;
     811                 :             :     }
     812                 :             : 
     813         [ -  + ]:          80 :     const CTransaction& tx{*btck_Transaction::get(tx_to)};
     814   [ -  +  -  + ]:          80 :     assert(input_index < tx.vin.size());
     815                 :             : 
     816         [ +  + ]:          80 :     const PrecomputedTransactionData& txdata{precomputed_txdata ? btck_PrecomputedTransactionData::get(precomputed_txdata) : PrecomputedTransactionData(tx)};
     817                 :             : 
     818   [ +  +  +  + ]:          80 :     if (flags & btck_ScriptVerificationFlags_TAPROOT && txdata.m_spent_outputs.empty()) {
     819         [ +  - ]:           4 :         if (status) *status = btck_ScriptVerifyStatus_ERROR_SPENT_OUTPUTS_REQUIRED;
     820                 :           4 :         return 0;
     821                 :             :     }
     822                 :             : 
     823         [ +  - ]:          76 :     if (status) *status = btck_ScriptVerifyStatus_OK;
     824                 :             : 
     825         [ +  - ]:          76 :     bool result = VerifyScript(tx.vin[input_index].scriptSig,
     826                 :             :                                btck_ScriptPubkey::get(script_pubkey),
     827         [ +  - ]:          76 :                                &tx.vin[input_index].scriptWitness,
     828                 :             :                                script_verify_flags::from_int(flags),
     829         [ +  - ]:          76 :                                TransactionSignatureChecker(&tx, input_index, amount, txdata, MissingDataBehavior::FAIL),
     830                 :             :                                nullptr);
     831         [ -  + ]:          76 :     return result ? 1 : 0;
     832                 :          80 : }
     833                 :             : 
     834                 :          66 : btck_TransactionInput* btck_transaction_input_copy(const btck_TransactionInput* input)
     835                 :             : {
     836                 :          66 :     return btck_TransactionInput::copy(input);
     837                 :             : }
     838                 :             : 
     839                 :         268 : const btck_TransactionOutPoint* btck_transaction_input_get_out_point(const btck_TransactionInput* input)
     840                 :             : {
     841                 :         268 :     return btck_TransactionOutPoint::ref(&btck_TransactionInput::get(input).prevout);
     842                 :             : }
     843                 :             : 
     844                 :           1 : uint32_t btck_transaction_input_get_sequence(const btck_TransactionInput* input)
     845                 :             : {
     846                 :           1 :     return btck_TransactionInput::get(input).nSequence;
     847                 :             : }
     848                 :             : 
     849                 :           2 : const btck_WitnessStack* btck_transaction_input_get_witness_stack(const btck_TransactionInput* input)
     850                 :             : {
     851                 :           2 :     return btck_WitnessStack::ref(&btck_TransactionInput::get(input).scriptWitness);
     852                 :             : }
     853                 :             : 
     854                 :           3 : int btck_transaction_input_get_script_sig(const btck_TransactionInput* input, btck_WriteBytes writer, void* user_data)
     855                 :             : {
     856                 :           3 :     const auto& script_sig{btck_TransactionInput::get(input).scriptSig};
     857   [ +  +  +  + ]:           8 :     return writer(script_sig.data(), script_sig.size(), user_data);
     858                 :             : }
     859                 :             : 
     860                 :          74 : void btck_transaction_input_destroy(btck_TransactionInput* input)
     861                 :             : {
     862         [ +  + ]:          74 :     delete input;
     863                 :          74 : }
     864                 :             : 
     865                 :           9 : size_t btck_witness_stack_count_items(const btck_WitnessStack* witness_stack)
     866                 :             : {
     867                 :           9 :     return btck_WitnessStack::get(witness_stack).size();
     868                 :             : }
     869                 :             : 
     870                 :          12 : int btck_witness_stack_get_item_at(const btck_WitnessStack* witness_stack, size_t index, btck_WriteBytes writer, void* user_data)
     871                 :             : {
     872                 :          12 :     const auto& stack{btck_WitnessStack::get(witness_stack)};
     873         [ -  + ]:          12 :     assert(index < stack.size());
     874                 :             :     // Look up the element once.
     875                 :          12 :     const auto element = stack[index];
     876                 :          12 :     return writer(element.data(), element.size(), user_data);
     877                 :             : }
     878                 :             : 
     879                 :           7 : btck_WitnessStack* btck_witness_stack_copy(const btck_WitnessStack* witness_stack)
     880                 :             : {
     881                 :           7 :     return btck_WitnessStack::copy(witness_stack);
     882                 :             : }
     883                 :             : 
     884                 :           9 : void btck_witness_stack_destroy(btck_WitnessStack* witness_stack)
     885                 :             : {
     886         [ +  + ]:           9 :     delete witness_stack;
     887                 :           9 : }
     888                 :             : 
     889                 :           7 : btck_TransactionOutPoint* btck_transaction_out_point_copy(const btck_TransactionOutPoint* out_point)
     890                 :             : {
     891                 :           7 :     return btck_TransactionOutPoint::copy(out_point);
     892                 :             : }
     893                 :             : 
     894                 :         325 : uint32_t btck_transaction_out_point_get_index(const btck_TransactionOutPoint* out_point)
     895                 :             : {
     896                 :         325 :     return btck_TransactionOutPoint::get(out_point).n;
     897                 :             : }
     898                 :             : 
     899                 :         177 : const btck_Txid* btck_transaction_out_point_get_txid(const btck_TransactionOutPoint* out_point)
     900                 :             : {
     901                 :         177 :     return btck_Txid::ref(&btck_TransactionOutPoint::get(out_point).hash);
     902                 :             : }
     903                 :             : 
     904                 :           9 : void btck_transaction_out_point_destroy(btck_TransactionOutPoint* out_point)
     905                 :             : {
     906         [ +  + ]:           9 :     delete out_point;
     907                 :           9 : }
     908                 :             : 
     909                 :          15 : btck_Txid* btck_txid_copy(const btck_Txid* txid)
     910                 :             : {
     911                 :          15 :     return btck_Txid::copy(txid);
     912                 :             : }
     913                 :             : 
     914                 :          29 : void btck_txid_to_bytes(const btck_Txid* txid, unsigned char output[32])
     915                 :             : {
     916                 :          29 :     std::memcpy(output, btck_Txid::get(txid).begin(), 32);
     917                 :          29 : }
     918                 :             : 
     919                 :        7637 : int btck_txid_equals(const btck_Txid* txid1, const btck_Txid* txid2)
     920                 :             : {
     921         [ +  + ]:        7637 :     return btck_Txid::get(txid1) == btck_Txid::get(txid2);
     922                 :             : }
     923                 :             : 
     924                 :          19 : void btck_txid_destroy(btck_Txid* txid)
     925                 :             : {
     926         [ +  + ]:          19 :     delete txid;
     927                 :          19 : }
     928                 :             : 
     929                 :           8 : btck_Wtxid* btck_wtxid_copy(const btck_Wtxid* wtxid)
     930                 :             : {
     931                 :           8 :     return btck_Wtxid::copy(wtxid);
     932                 :             : }
     933                 :             : 
     934                 :          15 : void btck_wtxid_to_bytes(const btck_Wtxid* wtxid, unsigned char output[32])
     935                 :             : {
     936                 :          15 :     std::memcpy(output, btck_Wtxid::get(wtxid).begin(), 32);
     937                 :          15 : }
     938                 :             : 
     939                 :           4 : int btck_wtxid_equals(const btck_Wtxid* wtxid1, const btck_Wtxid* wtxid2)
     940                 :             : {
     941         [ +  + ]:           4 :     return btck_Wtxid::get(wtxid1) == btck_Wtxid::get(wtxid2);
     942                 :             : }
     943                 :             : 
     944                 :          10 : void btck_wtxid_destroy(btck_Wtxid* wtxid)
     945                 :             : {
     946         [ +  + ]:          10 :     delete wtxid;
     947                 :          10 : }
     948                 :             : 
     949                 :             : namespace {
     950                 :             : //! The process-wide kernel logger. Intentionally leaked to avoid static destruction order issues,
     951                 :             : //! matching the node's LogInstance().
     952                 :        7172 : KernelLogger& GetKernelLogger()
     953                 :             : {
     954   [ +  +  +  -  :        7172 :     static KernelLogger* logger{new KernelLogger};
                   +  - ]
     955                 :        7172 :     return *logger;
     956                 :             : }
     957                 :             : } // namespace
     958                 :             : 
     959                 :             : namespace util::log {
     960                 :             : // Kernel filters on level only. The category is delivered as part of the entry, so consumers can
     961                 :             : // filter on it in their callback.
     962                 :        6009 : bool ShouldDebugLog(Category /*category*/)
     963                 :             : {
     964                 :        6009 :     return GetKernelLogger().ShouldLog(Level::Debug);
     965                 :             : }
     966                 :             : 
     967                 :           0 : bool ShouldTraceLog(Category /*category*/)
     968                 :             : {
     969                 :           0 :     return GetKernelLogger().ShouldLog(Level::Trace);
     970                 :             : }
     971                 :             : 
     972                 :        1151 : void Log(Entry entry)
     973                 :             : {
     974                 :             :     // Conditional logging, because the util::log framework doesn't allow us to check if the
     975                 :             :     // minimum level exceeds Info.
     976                 :        1151 :     GetKernelLogger().MaybeLog(entry);
     977                 :        1151 : }
     978                 :             : } // namespace util::log
     979                 :             : 
     980                 :             : 
     981                 :           3 : void btck_logging_set_min_level(btck_LogLevel level)
     982                 :             : {
     983                 :           3 :     GetKernelLogger().SetMinLevel(level);
     984                 :           3 : }
     985                 :             : 
     986                 :           9 : btck_LoggingConnection* btck_logging_connection_create(btck_LogCallback callback, void* user_data, btck_DestroyCallback user_data_destroy_callback)
     987                 :             : {
     988         [ -  + ]:           9 :     assert(callback);
     989                 :           9 :     try {
     990                 :             :         // Take ownership before anything can throw, so that user_data is always freed on error.
     991         [ +  - ]:           9 :         UserData data{user_data, {user_data_destroy_callback}};
     992   [ +  -  +  - ]:           9 :         auto handle{GetKernelLogger().RegisterCallback(callback, std::move(data))};
     993   [ +  -  +  +  :           9 :         LogDebug(BCLog::KERNEL, "Logger connected.");
                   +  - ]
     994         [ +  - ]:           9 :         return btck_LoggingConnection::create(std::move(handle));
     995                 :           9 :     } catch (...) {
     996                 :           0 :         return nullptr;
     997                 :           0 :     }
     998                 :             : }
     999                 :             : 
    1000                 :           9 : void btck_logging_connection_destroy(btck_LoggingConnection* connection)
    1001                 :             : {
    1002         [ +  - ]:           9 :     if (!connection) return;
    1003         [ +  + ]:           9 :     LogDebug(BCLog::KERNEL, "Logger disconnecting.");
    1004                 :           9 :     delete connection;
    1005                 :             : }
    1006                 :             : 
    1007                 :         378 : btck_StringView btck_log_entry_get_message(const btck_LogEntry* entry)
    1008                 :             : {
    1009                 :             :     // Some log statements are manually suffixed with a newline.
    1010         [ -  + ]:         378 :     return to_btck(util::RemoveSuffixView(btck_LogEntry::get(entry).message, "\n"));
    1011                 :             : }
    1012                 :             : 
    1013                 :           0 : btck_StringView btck_log_entry_get_thread_name(const btck_LogEntry* entry)
    1014                 :             : {
    1015         [ #  # ]:           0 :     return to_btck(btck_LogEntry::get(entry).thread_name);
    1016                 :             : }
    1017                 :             : 
    1018                 :         372 : int64_t btck_log_entry_get_timestamp_ns(const btck_LogEntry* entry)
    1019                 :             : {
    1020                 :         372 :     return TicksSinceEpoch<std::chrono::nanoseconds>(btck_LogEntry::get(entry).timestamp);
    1021                 :             : }
    1022                 :             : 
    1023                 :           0 : int64_t btck_log_entry_get_mocktime_s(const btck_LogEntry* entry)
    1024                 :             : {
    1025                 :           0 :     return btck_LogEntry::get(entry).mocktime.count();
    1026                 :             : }
    1027                 :             : 
    1028                 :           0 : btck_StringView btck_log_entry_get_file_name(const btck_LogEntry* entry)
    1029                 :             : {
    1030                 :           0 :     return to_btck(btck_LogEntry::get(entry).source_loc.file_name());
    1031                 :             : }
    1032                 :             : 
    1033                 :           0 : btck_StringView btck_log_entry_get_function_name(const btck_LogEntry* entry)
    1034                 :             : {
    1035                 :           0 :     return to_btck(btck_LogEntry::get(entry).source_loc.function_name_short());
    1036                 :             : }
    1037                 :             : 
    1038                 :           0 : uint32_t btck_log_entry_get_line(const btck_LogEntry* entry)
    1039                 :             : {
    1040         [ #  # ]:           0 :     return btck_LogEntry::get(entry).source_loc.line();
    1041                 :             : }
    1042                 :             : 
    1043                 :         372 : btck_LogLevel btck_log_entry_get_level(const btck_LogEntry* entry)
    1044                 :             : {
    1045                 :         372 :     return to_btck(btck_LogEntry::get(entry).level);
    1046                 :             : }
    1047                 :             : 
    1048                 :         372 : btck_LogCategory btck_log_entry_get_category(const btck_LogEntry* entry)
    1049                 :             : {
    1050                 :         372 :     return to_btck(static_cast<BCLog::LogFlags>(btck_LogEntry::get(entry).category));
    1051                 :             : }
    1052                 :             : 
    1053                 :          17 : btck_ChainParameters* btck_chain_parameters_create(const btck_ChainType chain_type)
    1054                 :             : {
    1055   [ +  -  -  +  :          17 :     switch (chain_type) {
                   +  - ]
    1056                 :           6 :     case btck_ChainType_MAINNET: {
    1057                 :           6 :         return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::Main().release()));
    1058                 :             :     }
    1059                 :           0 :     case btck_ChainType_TESTNET: {
    1060                 :           0 :         return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::TestNet().release()));
    1061                 :             :     }
    1062                 :           0 :     case btck_ChainType_TESTNET_4: {
    1063                 :           0 :         return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::TestNet4().release()));
    1064                 :             :     }
    1065                 :           1 :     case btck_ChainType_SIGNET: {
    1066                 :           1 :         return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::SigNet().release()));
    1067                 :             :     }
    1068                 :          10 :     case btck_ChainType_REGTEST: {
    1069                 :          10 :         return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::RegTest().release()));
    1070                 :             :     }
    1071                 :             :     }
    1072                 :           0 :     AssertUnreachable();
    1073                 :             : }
    1074                 :             : 
    1075                 :           1 : btck_ChainParameters* btck_chain_parameters_create_signet(const void* challenge, size_t challenge_len)
    1076                 :             : {
    1077         [ -  + ]:           1 :     assert(challenge != nullptr || challenge_len == 0);
    1078                 :           1 :     const uint8_t* p = static_cast<const uint8_t*>(challenge);
    1079                 :           1 :     CChainParams::SigNetOptions options{
    1080   [ +  -  +  - ]:           2 :         .challenge = std::vector<uint8_t>{p, p + challenge_len},
    1081         [ +  - ]:           1 :     };
    1082         [ +  - ]:           2 :     return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::SigNet(options).release()));
    1083                 :           1 : }
    1084                 :             : 
    1085                 :          10 : btck_ChainParameters* btck_chain_parameters_copy(const btck_ChainParameters* chain_parameters)
    1086                 :             : {
    1087                 :          10 :     return btck_ChainParameters::copy(chain_parameters);
    1088                 :             : }
    1089                 :             : 
    1090                 :           1 : const btck_ConsensusParams* btck_chain_parameters_get_consensus_params(const btck_ChainParameters* chain_parameters)
    1091                 :             : {
    1092                 :           1 :     return btck_ConsensusParams::ref(&btck_ChainParameters::get(chain_parameters).GetConsensus());
    1093                 :             : }
    1094                 :             : 
    1095                 :          32 : void btck_chain_parameters_destroy(btck_ChainParameters* chain_parameters)
    1096                 :             : {
    1097         [ +  + ]:          32 :     delete chain_parameters;
    1098                 :          32 : }
    1099                 :             : 
    1100                 :          20 : btck_ContextOptions* btck_context_options_create()
    1101                 :             : {
    1102                 :          20 :     return btck_ContextOptions::create();
    1103                 :             : }
    1104                 :             : 
    1105                 :          14 : void btck_context_options_set_chainparams(btck_ContextOptions* options, const btck_ChainParameters* chain_parameters)
    1106                 :             : {
    1107                 :             :     // Copy the chainparams, so the caller can free it again
    1108                 :          14 :     LOCK(btck_ContextOptions::get(options).m_mutex);
    1109   [ +  -  +  - ]:          14 :     btck_ContextOptions::get(options).m_chainparams = std::make_unique<const CChainParams>(btck_ChainParameters::get(chain_parameters));
    1110                 :          14 : }
    1111                 :             : 
    1112                 :          14 : void btck_context_options_set_notifications(btck_ContextOptions* options, btck_NotificationInterfaceCallbacks notifications)
    1113                 :             : {
    1114                 :             :     // The KernelNotifications are copy-initialized, so the caller can free them again.
    1115                 :          14 :     LOCK(btck_ContextOptions::get(options).m_mutex);
    1116   [ +  -  -  +  :          14 :     btck_ContextOptions::get(options).m_notifications = std::make_shared<KernelNotifications>(notifications);
                   +  - ]
    1117                 :          14 : }
    1118                 :             : 
    1119                 :           6 : void btck_context_options_set_validation_interface(btck_ContextOptions* options, btck_ValidationInterfaceCallbacks vi_cbs)
    1120                 :             : {
    1121                 :           6 :     LOCK(btck_ContextOptions::get(options).m_mutex);
    1122   [ +  -  -  +  :           6 :     btck_ContextOptions::get(options).m_validation_interface = std::make_shared<KernelValidationInterface>(vi_cbs);
                   +  - ]
    1123                 :           6 : }
    1124                 :             : 
    1125                 :          20 : void btck_context_options_destroy(btck_ContextOptions* options)
    1126                 :             : {
    1127         [ +  - ]:          20 :     delete options;
    1128                 :          20 : }
    1129                 :             : 
    1130                 :          20 : btck_Context* btck_context_create(const btck_ContextOptions* options)
    1131                 :             : {
    1132                 :          20 :     bool sane{true};
    1133                 :          20 :     const ContextOptions* opts = options ? &btck_ContextOptions::get(options) : nullptr;
    1134                 :          20 :     auto context{std::make_shared<const Context>(opts, sane)};
    1135         [ -  + ]:          20 :     if (!sane) {
    1136   [ -  -  +  - ]:          20 :         LogError("Kernel context sanity check failed.");
    1137                 :             :         return nullptr;
    1138                 :             :     }
    1139         [ +  - ]:          20 :     return btck_Context::create(context);
    1140                 :          20 : }
    1141                 :             : 
    1142                 :           5 : btck_Context* btck_context_copy(const btck_Context* context)
    1143                 :             : {
    1144                 :           5 :     return btck_Context::copy(context);
    1145                 :             : }
    1146                 :             : 
    1147                 :           1 : int btck_context_interrupt(btck_Context* context)
    1148                 :             : {
    1149         [ -  + ]:           1 :     return (*btck_Context::get(context)->m_interrupt)() ? 0 : -1;
    1150                 :             : }
    1151                 :             : 
    1152                 :          27 : void btck_context_destroy(btck_Context* context)
    1153                 :             : {
    1154         [ +  + ]:          27 :     delete context;
    1155                 :          27 : }
    1156                 :             : 
    1157                 :           6 : const btck_BlockTreeEntry* btck_block_tree_entry_get_previous(const btck_BlockTreeEntry* entry)
    1158                 :             : {
    1159         [ +  + ]:           6 :     if (!btck_BlockTreeEntry::get(entry).pprev) {
    1160                 :           2 :         LogInfo("Genesis block has no previous.");
    1161                 :           2 :         return nullptr;
    1162                 :             :     }
    1163                 :             : 
    1164                 :             :     return btck_BlockTreeEntry::ref(btck_BlockTreeEntry::get(entry).pprev);
    1165                 :             : }
    1166                 :             : 
    1167                 :           3 : const btck_BlockTreeEntry* btck_block_tree_entry_get_ancestor(const btck_BlockTreeEntry* block_tree_entry, int32_t height)
    1168                 :             : {
    1169                 :           3 :     const auto* ancestor{btck_BlockTreeEntry::get(block_tree_entry).GetAncestor(height)};
    1170         [ -  + ]:           3 :     assert(ancestor);
    1171                 :           3 :     return btck_BlockTreeEntry::ref(ancestor);
    1172                 :             : }
    1173                 :             : 
    1174                 :           1 : btck_BlockValidationState* btck_block_validation_state_create()
    1175                 :             : {
    1176                 :           1 :     return btck_BlockValidationState::create();
    1177                 :             : }
    1178                 :             : 
    1179                 :           0 : btck_BlockValidationState* btck_block_validation_state_copy(const btck_BlockValidationState* state)
    1180                 :             : {
    1181                 :           0 :     return btck_BlockValidationState::copy(state);
    1182                 :             : }
    1183                 :             : 
    1184                 :         209 : void btck_block_validation_state_destroy(btck_BlockValidationState* state)
    1185                 :             : {
    1186         [ +  - ]:         209 :     delete state;
    1187                 :         209 : }
    1188                 :             : 
    1189                 :         220 : btck_ValidationMode btck_block_validation_state_get_validation_mode(const btck_BlockValidationState* block_validation_state_)
    1190                 :             : {
    1191                 :         220 :     auto& block_validation_state = btck_BlockValidationState::get(block_validation_state_);
    1192         [ +  + ]:         220 :     if (block_validation_state.IsValid()) return btck_ValidationMode_VALID;
    1193         [ +  - ]:           5 :     if (block_validation_state.IsInvalid()) return btck_ValidationMode_INVALID;
    1194                 :             :     return btck_ValidationMode_INTERNAL_ERROR;
    1195                 :             : }
    1196                 :             : 
    1197                 :         212 : btck_BlockValidationResult btck_block_validation_state_get_block_validation_result(const btck_BlockValidationState* block_validation_state_)
    1198                 :             : {
    1199                 :         212 :     auto& block_validation_state = btck_BlockValidationState::get(block_validation_state_);
    1200   [ +  -  +  +  :         212 :     switch (block_validation_state.GetResult()) {
          -  -  +  -  -  
                      + ]
    1201                 :             :     case BlockValidationResult::BLOCK_RESULT_UNSET:
    1202                 :             :         return btck_BlockValidationResult_UNSET;
    1203                 :           1 :     case BlockValidationResult::BLOCK_CONSENSUS:
    1204                 :           1 :         return btck_BlockValidationResult_CONSENSUS;
    1205                 :           0 :     case BlockValidationResult::BLOCK_CACHED_INVALID:
    1206                 :           0 :         return btck_BlockValidationResult_CACHED_INVALID;
    1207                 :           2 :     case BlockValidationResult::BLOCK_INVALID_HEADER:
    1208                 :           2 :         return btck_BlockValidationResult_INVALID_HEADER;
    1209                 :           1 :     case BlockValidationResult::BLOCK_MUTATED:
    1210                 :           1 :         return btck_BlockValidationResult_MUTATED;
    1211                 :           0 :     case BlockValidationResult::BLOCK_MISSING_PREV:
    1212                 :           0 :         return btck_BlockValidationResult_MISSING_PREV;
    1213                 :           0 :     case BlockValidationResult::BLOCK_INVALID_PREV:
    1214                 :           0 :         return btck_BlockValidationResult_INVALID_PREV;
    1215                 :           1 :     case BlockValidationResult::BLOCK_TIME_FUTURE:
    1216                 :           1 :         return btck_BlockValidationResult_TIME_FUTURE;
    1217                 :           0 :     case BlockValidationResult::BLOCK_HEADER_LOW_WORK:
    1218                 :           0 :         return btck_BlockValidationResult_HEADER_LOW_WORK;
    1219                 :             :     } // no default case, so the compiler can warn about missing cases
    1220                 :           0 :     AssertUnreachable();
    1221                 :             : }
    1222                 :             : 
    1223                 :          21 : btck_ChainstateManagerOptions* btck_chainstate_manager_options_create(const btck_Context* context, const char* data_dir, size_t data_dir_len, const char* blocks_dir, size_t blocks_dir_len)
    1224                 :             : {
    1225         [ -  + ]:          21 :     assert(data_dir != nullptr || data_dir_len == 0);
    1226         [ -  + ]:          21 :     assert(blocks_dir != nullptr || blocks_dir_len == 0);
    1227         [ +  + ]:          21 :     if (data_dir_len == 0 || blocks_dir_len == 0) {
    1228                 :           4 :         LogError("Failed to create chainstate manager options: dir must be non-null and non-empty");
    1229                 :           4 :         return nullptr;
    1230                 :             :     }
    1231                 :          17 :     try {
    1232   [ +  -  +  -  :          34 :         fs::path abs_data_dir{fs::absolute(fs::PathFromString({data_dir, data_dir_len}))};
                   +  - ]
    1233         [ +  - ]:          17 :         fs::create_directories(abs_data_dir);
    1234   [ +  -  +  -  :          34 :         fs::path abs_blocks_dir{fs::absolute(fs::PathFromString({blocks_dir, blocks_dir_len}))};
                   +  - ]
    1235         [ +  - ]:          17 :         fs::create_directories(abs_blocks_dir);
    1236         [ +  - ]:          17 :         return btck_ChainstateManagerOptions::create(btck_Context::get(context), abs_data_dir, abs_blocks_dir);
    1237         [ -  - ]:          34 :     } catch (const std::exception& e) {
    1238         [ -  - ]:           0 :         LogError("Failed to create chainstate manager options: %s", e.what());
    1239                 :           0 :         return nullptr;
    1240                 :           0 :     }
    1241                 :             : }
    1242                 :             : 
    1243                 :           6 : void btck_chainstate_manager_options_set_worker_threads_num(btck_ChainstateManagerOptions* opts, int worker_threads)
    1244                 :             : {
    1245                 :           6 :     LOCK(btck_ChainstateManagerOptions::get(opts).m_mutex);
    1246         [ +  - ]:           6 :     btck_ChainstateManagerOptions::get(opts).m_chainman_options.worker_threads_num = worker_threads;
    1247                 :           6 : }
    1248                 :             : 
    1249                 :           2 : int btck_chainstate_manager_options_set_database_cache_bytes(btck_ChainstateManagerOptions* chainman_opts, uint64_t database_cache_bytes)
    1250                 :             : {
    1251         [ +  + ]:           2 :     if (database_cache_bytes < MIN_DBCACHE_BYTES || database_cache_bytes > MAX_DBCACHE_BYTES) {
    1252                 :           1 :         LogError("Failed to set database cache: size is outside the supported range.");
    1253                 :           1 :         return -1;
    1254                 :             :     }
    1255                 :             : 
    1256                 :           1 :     auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
    1257                 :           1 :     LOCK(opts.m_mutex);
    1258                 :           1 :     opts.m_db_cache_bytes = database_cache_bytes;
    1259                 :           1 :     opts.m_blockman_options.block_tree_db_params.cache_bytes = kernel::CacheSizes{database_cache_bytes}.block_tree_db;
    1260         [ +  - ]:           1 :     return 0;
    1261                 :           1 : }
    1262                 :             : 
    1263                 :          17 : void btck_chainstate_manager_options_destroy(btck_ChainstateManagerOptions* options)
    1264                 :             : {
    1265         [ +  - ]:          17 :     delete options;
    1266                 :          17 : }
    1267                 :             : 
    1268                 :           6 : int btck_chainstate_manager_options_set_wipe_dbs(btck_ChainstateManagerOptions* chainman_opts, int wipe_block_tree_db, int wipe_chainstate_db)
    1269                 :             : {
    1270         [ +  + ]:           6 :     if (wipe_block_tree_db == 1 && wipe_chainstate_db != 1) {
    1271                 :           1 :         LogError("Wiping the block tree db without also wiping the chainstate db is currently unsupported.");
    1272                 :           1 :         return -1;
    1273                 :             :     }
    1274                 :           5 :     auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
    1275                 :           5 :     LOCK(opts.m_mutex);
    1276                 :           5 :     opts.m_blockman_options.block_tree_db_params.wipe_data = wipe_block_tree_db == 1;
    1277                 :           5 :     opts.m_chainstate_load_options.wipe_chainstate_db = wipe_chainstate_db == 1;
    1278         [ +  - ]:           5 :     return 0;
    1279                 :           5 : }
    1280                 :             : 
    1281                 :           3 : void btck_chainstate_manager_options_update_block_tree_db_in_memory(
    1282                 :             :     btck_ChainstateManagerOptions* chainman_opts,
    1283                 :             :     int block_tree_db_in_memory)
    1284                 :             : {
    1285                 :           3 :     auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
    1286                 :           3 :     LOCK(opts.m_mutex);
    1287         [ +  - ]:           3 :     opts.m_blockman_options.block_tree_db_params.memory_only = block_tree_db_in_memory == 1;
    1288                 :           3 : }
    1289                 :             : 
    1290                 :           3 : void btck_chainstate_manager_options_update_chainstate_db_in_memory(
    1291                 :             :     btck_ChainstateManagerOptions* chainman_opts,
    1292                 :             :     int chainstate_db_in_memory)
    1293                 :             : {
    1294                 :           3 :     auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
    1295                 :           3 :     LOCK(opts.m_mutex);
    1296         [ +  - ]:           3 :     opts.m_chainstate_load_options.coins_db_in_memory = chainstate_db_in_memory == 1;
    1297                 :           3 : }
    1298                 :             : 
    1299                 :          17 : btck_ChainstateManager* btck_chainstate_manager_create(
    1300                 :             :     const btck_ChainstateManagerOptions* chainman_opts)
    1301                 :             : {
    1302                 :          17 :     auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
    1303                 :          17 :     std::unique_ptr<ChainstateManager> chainman;
    1304                 :          17 :     try {
    1305         [ +  - ]:          17 :         LOCK(opts.m_mutex);
    1306   [ +  -  +  - ]:          34 :         chainman = std::make_unique<ChainstateManager>(*opts.m_context->m_interrupt, opts.m_chainman_options, opts.m_blockman_options);
    1307         [ -  - ]:           0 :     } catch (const std::exception& e) {
    1308         [ -  - ]:           0 :         LogError("Failed to create chainstate manager: %s", e.what());
    1309                 :           0 :         return nullptr;
    1310                 :           0 :     }
    1311                 :             : 
    1312                 :          17 :     try {
    1313   [ +  -  +  - ]:          51 :         const auto chainstate_load_opts{WITH_LOCK(opts.m_mutex, return opts.m_chainstate_load_options)};
    1314                 :             : 
    1315   [ +  -  +  - ]:          34 :         const kernel::CacheSizes cache_sizes{WITH_LOCK(opts.m_mutex, return opts.m_db_cache_bytes)};
    1316   [ +  -  -  + ]:          17 :         auto [status, chainstate_err]{node::LoadChainstate(*chainman, cache_sizes, chainstate_load_opts)};
    1317         [ -  + ]:          17 :         if (status != node::ChainstateLoadStatus::SUCCESS) {
    1318         [ #  # ]:           0 :             LogError("Failed to load chain state from your data directory: %s", chainstate_err.original);
    1319                 :             :             return nullptr;
    1320                 :             :         }
    1321         [ +  - ]:          17 :         std::tie(status, chainstate_err) = node::VerifyLoadedChainstate(*chainman, chainstate_load_opts);
    1322         [ -  + ]:          17 :         if (status != node::ChainstateLoadStatus::SUCCESS) {
    1323         [ #  # ]:           0 :             LogError("Failed to verify loaded chain state from your datadir: %s", chainstate_err.original);
    1324                 :             :             return nullptr;
    1325                 :             :         }
    1326   [ +  -  -  + ]:          17 :         if (auto result = chainman->ActivateBestChains(); !result) {
    1327   [ #  #  #  # ]:           0 :             LogError("%s", util::ErrorString(result).original);
    1328                 :           0 :             return nullptr;
    1329                 :          17 :         }
    1330         [ -  - ]:          17 :     } catch (const std::exception& e) {
    1331         [ -  - ]:           0 :         LogError("Failed to load chainstate: %s", e.what());
    1332                 :           0 :         return nullptr;
    1333                 :           0 :     }
    1334                 :             : 
    1335         [ +  - ]:          17 :     return btck_ChainstateManager::create(std::move(chainman), opts.m_context);
    1336                 :          17 : }
    1337                 :             : 
    1338                 :         207 : const btck_BlockTreeEntry* btck_chainstate_manager_get_block_tree_entry_by_hash(const btck_ChainstateManager* chainman, const btck_BlockHash* block_hash)
    1339                 :             : {
    1340   [ +  -  +  - ]:         621 :     auto block_index = WITH_LOCK(btck_ChainstateManager::get(chainman).m_chainman->GetMutex(),
    1341                 :             :                                  return btck_ChainstateManager::get(chainman).m_chainman->m_blockman.LookupBlockIndex(btck_BlockHash::get(block_hash)));
    1342         [ -  + ]:         207 :     if (!block_index) {
    1343         [ #  # ]:           0 :         LogDebug(BCLog::KERNEL, "A block with the given hash is not indexed.");
    1344                 :           0 :         return nullptr;
    1345                 :             :     }
    1346                 :             :     return btck_BlockTreeEntry::ref(block_index);
    1347                 :             : }
    1348                 :             : 
    1349                 :         206 : const btck_BlockTreeEntry* btck_chainstate_manager_get_best_entry(const btck_ChainstateManager* chainstate_manager)
    1350                 :             : {
    1351                 :         206 :     auto& chainman = *btck_ChainstateManager::get(chainstate_manager).m_chainman;
    1352         [ +  - ]:         412 :     return btck_BlockTreeEntry::ref(WITH_LOCK(chainman.GetMutex(), return chainman.m_best_header));
    1353                 :             : }
    1354                 :             : 
    1355                 :          17 : void btck_chainstate_manager_destroy(btck_ChainstateManager* chainman)
    1356                 :             : {
    1357                 :          17 :     {
    1358                 :          17 :         LOCK(btck_ChainstateManager::get(chainman).m_chainman->GetMutex());
    1359         [ +  + ]:          35 :         for (const auto& chainstate : btck_ChainstateManager::get(chainman).m_chainman->m_chainstates) {
    1360         [ +  - ]:          36 :             if (chainstate->CanFlushToDisk()) {
    1361         [ +  - ]:          18 :                 chainstate->ForceFlushStateToDisk();
    1362                 :          18 :                 chainstate->ResetCoinsViews();
    1363                 :             :             }
    1364                 :             :         }
    1365                 :          17 :     }
    1366                 :             : 
    1367         [ +  - ]:          17 :     delete chainman;
    1368                 :          17 : }
    1369                 :             : 
    1370                 :           2 : int btck_chainstate_manager_import_blocks(btck_ChainstateManager* chainman, const char** block_file_paths_data, size_t* block_file_paths_lens, size_t block_file_paths_data_len)
    1371                 :             : {
    1372                 :           2 :     try {
    1373                 :           2 :         std::vector<fs::path> import_files;
    1374         [ +  - ]:           2 :         import_files.reserve(block_file_paths_data_len);
    1375         [ +  + ]:           3 :         for (uint32_t i = 0; i < block_file_paths_data_len; i++) {
    1376         [ +  - ]:           1 :             if (block_file_paths_data[i] != nullptr) {
    1377   [ +  -  +  - ]:           2 :                 import_files.emplace_back(std::string{block_file_paths_data[i], block_file_paths_lens[i]}.c_str());
    1378                 :             :             }
    1379                 :             :         }
    1380         [ -  + ]:           2 :         auto& chainman_ref{*btck_ChainstateManager::get(chainman).m_chainman};
    1381   [ -  +  +  - ]:           2 :         node::ImportBlocks(chainman_ref, import_files);
    1382   [ +  -  +  - ]:           6 :         WITH_LOCK(::cs_main, chainman_ref.UpdateIBDStatus());
    1383         [ -  - ]:           0 :     } catch (const std::exception& e) {
    1384         [ -  - ]:           0 :         LogError("Failed to import blocks: %s", e.what());
    1385                 :           0 :         return -1;
    1386                 :           0 :     }
    1387                 :           2 :     return 0;
    1388                 :             : }
    1389                 :             : 
    1390                 :         639 : btck_Block* btck_block_create(const void* raw_block, size_t raw_block_length)
    1391                 :             : {
    1392         [ -  + ]:         639 :     assert(raw_block != nullptr || raw_block_length == 0);
    1393                 :         639 :     auto block{std::make_shared<CBlock>()};
    1394                 :             : 
    1395         [ +  + ]:         639 :     SpanReader stream{std::span{reinterpret_cast<const std::byte*>(raw_block), raw_block_length}};
    1396                 :             : 
    1397                 :         639 :     try {
    1398         [ +  + ]:         639 :         stream >> TX_WITH_WITNESS(*block);
    1399                 :           4 :     } catch (...) {
    1400   [ +  -  -  +  :           4 :         LogDebug(BCLog::KERNEL, "Block decode failed.");
                   -  - ]
    1401                 :           4 :         return nullptr;
    1402         [ +  - ]:           4 :     }
    1403                 :             : 
    1404         [ +  - ]:         635 :     return btck_Block::create(block);
    1405                 :         639 : }
    1406                 :             : 
    1407                 :           5 : btck_Block* btck_block_copy(const btck_Block* block)
    1408                 :             : {
    1409                 :           5 :     return btck_Block::copy(block);
    1410                 :             : }
    1411                 :             : 
    1412                 :           7 : int btck_block_check(const btck_Block* block, const btck_ConsensusParams* consensus_params, btck_BlockCheckFlags flags, btck_BlockValidationState* validation_state)
    1413                 :             : {
    1414                 :           7 :     auto& state = btck_BlockValidationState::get(validation_state);
    1415                 :           7 :     state = BlockValidationState{};
    1416                 :             : 
    1417                 :           7 :     const bool check_pow    = (flags & btck_BlockCheckFlags_POW) != 0;
    1418                 :           7 :     const bool check_merkle = (flags & btck_BlockCheckFlags_MERKLE) != 0;
    1419                 :             : 
    1420                 :           7 :     const bool result = CheckBlock(*btck_Block::get(block), state, btck_ConsensusParams::get(consensus_params), /*fCheckPOW=*/check_pow, /*fCheckMerkleRoot=*/check_merkle);
    1421                 :             : 
    1422         [ +  + ]:           7 :     return result ? 1 : 0;
    1423                 :             : }
    1424                 :             : 
    1425                 :        6688 : size_t btck_block_count_transactions(const btck_Block* block)
    1426                 :             : {
    1427         [ -  + ]:        6688 :     return btck_Block::get(block)->vtx.size();
    1428                 :             : }
    1429                 :             : 
    1430                 :        8051 : const btck_Transaction* btck_block_get_transaction_at(const btck_Block* block, size_t index)
    1431                 :             : {
    1432   [ -  +  -  + ]:        8051 :     assert(index < btck_Block::get(block)->vtx.size());
    1433                 :        8051 :     return btck_Transaction::ref(&btck_Block::get(block)->vtx[index]);
    1434                 :             : }
    1435                 :             : 
    1436                 :         209 : btck_BlockHeader* btck_block_get_header(const btck_Block* block)
    1437                 :             : {
    1438                 :         209 :     const auto& block_ptr = btck_Block::get(block);
    1439                 :         209 :     return btck_BlockHeader::create(static_cast<const CBlockHeader&>(*block_ptr));
    1440                 :             : }
    1441                 :             : 
    1442                 :          22 : int btck_block_to_bytes(const btck_Block* block, btck_WriteBytes writer, void* user_data)
    1443                 :             : {
    1444                 :          22 :     try {
    1445                 :          22 :         WriterStream ws{writer, user_data};
    1446         [ +  - ]:          44 :         ws << TX_WITH_WITNESS(*btck_Block::get(block));
    1447                 :             :         return 0;
    1448                 :           0 :     } catch (...) {
    1449                 :           0 :         return -1;
    1450                 :           0 :     }
    1451                 :             : }
    1452                 :             : 
    1453                 :           1 : btck_BlockHash* btck_block_get_hash(const btck_Block* block)
    1454                 :             : {
    1455                 :           1 :     return btck_BlockHash::create(btck_Block::get(block)->GetHash());
    1456                 :             : }
    1457                 :             : 
    1458                 :        7330 : void btck_block_destroy(btck_Block* block)
    1459                 :             : {
    1460         [ +  + ]:        7330 :     delete block;
    1461                 :        7330 : }
    1462                 :             : 
    1463                 :        6676 : btck_Block* btck_block_read(const btck_ChainstateManager* chainman, const btck_BlockTreeEntry* entry)
    1464                 :             : {
    1465                 :        6676 :     auto block{std::make_shared<CBlock>()};
    1466   [ +  -  +  + ]:        6676 :     if (!btck_ChainstateManager::get(chainman).m_chainman->m_blockman.ReadBlock(*block, btck_BlockTreeEntry::get(entry))) {
    1467   [ +  -  +  - ]:        6676 :         LogError("Failed to read block.");
    1468                 :             :         return nullptr;
    1469                 :             :     }
    1470         [ +  - ]:        6675 :     return btck_Block::create(block);
    1471                 :        6676 : }
    1472                 :             : 
    1473                 :         206 : btck_BlockHeader* btck_block_tree_entry_get_block_header(const btck_BlockTreeEntry* entry)
    1474                 :             : {
    1475                 :         206 :     return btck_BlockHeader::create(btck_BlockTreeEntry::get(entry).GetBlockHeader());
    1476                 :             : }
    1477                 :             : 
    1478                 :         211 : int32_t btck_block_tree_entry_get_height(const btck_BlockTreeEntry* entry)
    1479                 :             : {
    1480                 :         211 :     return btck_BlockTreeEntry::get(entry).nHeight;
    1481                 :             : }
    1482                 :             : 
    1483                 :         207 : const btck_BlockHash* btck_block_tree_entry_get_block_hash(const btck_BlockTreeEntry* entry)
    1484                 :             : {
    1485                 :         207 :     return btck_BlockHash::ref(btck_BlockTreeEntry::get(entry).phashBlock);
    1486                 :             : }
    1487                 :             : 
    1488                 :          10 : int btck_block_tree_entry_equals(const btck_BlockTreeEntry* entry1, const btck_BlockTreeEntry* entry2)
    1489                 :             : {
    1490                 :          10 :     return &btck_BlockTreeEntry::get(entry1) == &btck_BlockTreeEntry::get(entry2);
    1491                 :             : }
    1492                 :             : 
    1493                 :           2 : btck_BlockHash* btck_block_hash_create(const unsigned char block_hash[32])
    1494                 :             : {
    1495                 :           2 :     return btck_BlockHash::create(std::span<const unsigned char>{block_hash, 32});
    1496                 :             : }
    1497                 :             : 
    1498                 :         212 : btck_BlockHash* btck_block_hash_copy(const btck_BlockHash* block_hash)
    1499                 :             : {
    1500                 :         212 :     return btck_BlockHash::copy(block_hash);
    1501                 :             : }
    1502                 :             : 
    1503                 :          18 : void btck_block_hash_to_bytes(const btck_BlockHash* block_hash, unsigned char output[32])
    1504                 :             : {
    1505                 :          18 :     std::memcpy(output, btck_BlockHash::get(block_hash).begin(), 32);
    1506                 :          18 : }
    1507                 :             : 
    1508                 :         208 : int btck_block_hash_equals(const btck_BlockHash* hash1, const btck_BlockHash* hash2)
    1509                 :             : {
    1510                 :         208 :     return btck_BlockHash::get(hash1) == btck_BlockHash::get(hash2);
    1511                 :             : }
    1512                 :             : 
    1513                 :         632 : void btck_block_hash_destroy(btck_BlockHash* hash)
    1514                 :             : {
    1515         [ +  + ]:         632 :     delete hash;
    1516                 :         632 : }
    1517                 :             : 
    1518                 :           5 : btck_BlockSpentOutputs* btck_block_spent_outputs_read(const btck_ChainstateManager* chainman, const btck_BlockTreeEntry* entry)
    1519                 :             : {
    1520                 :           5 :     auto block_undo{std::make_shared<CBlockUndo>()};
    1521         [ +  + ]:           5 :     if (btck_BlockTreeEntry::get(entry).nHeight < 1) {
    1522   [ +  -  -  +  :           1 :         LogDebug(BCLog::KERNEL, "The genesis block does not have any spent outputs.");
                   -  - ]
    1523         [ +  - ]:           1 :         return btck_BlockSpentOutputs::create(block_undo);
    1524                 :             :     }
    1525   [ +  -  +  + ]:           4 :     if (!btck_ChainstateManager::get(chainman).m_chainman->m_blockman.ReadBlockUndo(*block_undo, btck_BlockTreeEntry::get(entry))) {
    1526   [ +  -  +  - ]:           5 :         LogError("Failed to read block spent outputs data.");
    1527                 :             :         return nullptr;
    1528                 :             :     }
    1529         [ +  - ]:           3 :     return btck_BlockSpentOutputs::create(block_undo);
    1530                 :           5 : }
    1531                 :             : 
    1532                 :           5 : btck_BlockSpentOutputs* btck_block_spent_outputs_copy(const btck_BlockSpentOutputs* block_spent_outputs)
    1533                 :             : {
    1534                 :           5 :     return btck_BlockSpentOutputs::copy(block_spent_outputs);
    1535                 :             : }
    1536                 :             : 
    1537                 :          25 : size_t btck_block_spent_outputs_count(const btck_BlockSpentOutputs* block_spent_outputs)
    1538                 :             : {
    1539         [ -  + ]:          25 :     return btck_BlockSpentOutputs::get(block_spent_outputs)->vtxundo.size();
    1540                 :             : }
    1541                 :             : 
    1542                 :          12 : const btck_TransactionSpentOutputs* btck_block_spent_outputs_get_transaction_spent_outputs_at(const btck_BlockSpentOutputs* block_spent_outputs, size_t transaction_index)
    1543                 :             : {
    1544   [ -  +  -  + ]:          12 :     assert(transaction_index < btck_BlockSpentOutputs::get(block_spent_outputs)->vtxundo.size());
    1545                 :          12 :     const auto* tx_undo{&btck_BlockSpentOutputs::get(block_spent_outputs)->vtxundo.at(transaction_index)};
    1546                 :          12 :     return btck_TransactionSpentOutputs::ref(tx_undo);
    1547                 :             : }
    1548                 :             : 
    1549                 :          11 : void btck_block_spent_outputs_destroy(btck_BlockSpentOutputs* block_spent_outputs)
    1550                 :             : {
    1551         [ +  + ]:          11 :     delete block_spent_outputs;
    1552                 :          11 : }
    1553                 :             : 
    1554                 :           7 : btck_TransactionSpentOutputs* btck_transaction_spent_outputs_copy(const btck_TransactionSpentOutputs* transaction_spent_outputs)
    1555                 :             : {
    1556                 :           7 :     return btck_TransactionSpentOutputs::copy(transaction_spent_outputs);
    1557                 :             : }
    1558                 :             : 
    1559                 :          22 : size_t btck_transaction_spent_outputs_count(const btck_TransactionSpentOutputs* transaction_spent_outputs)
    1560                 :             : {
    1561         [ -  + ]:          22 :     return btck_TransactionSpentOutputs::get(transaction_spent_outputs).vprevout.size();
    1562                 :             : }
    1563                 :             : 
    1564                 :           9 : void btck_transaction_spent_outputs_destroy(btck_TransactionSpentOutputs* transaction_spent_outputs)
    1565                 :             : {
    1566         [ +  + ]:           9 :     delete transaction_spent_outputs;
    1567                 :           9 : }
    1568                 :             : 
    1569                 :          12 : const btck_Coin* btck_transaction_spent_outputs_get_coin_at(const btck_TransactionSpentOutputs* transaction_spent_outputs, size_t coin_index)
    1570                 :             : {
    1571   [ -  +  -  + ]:          12 :     assert(coin_index < btck_TransactionSpentOutputs::get(transaction_spent_outputs).vprevout.size());
    1572                 :          12 :     const Coin* coin{&btck_TransactionSpentOutputs::get(transaction_spent_outputs).vprevout.at(coin_index)};
    1573                 :          12 :     return btck_Coin::ref(coin);
    1574                 :             : }
    1575                 :             : 
    1576                 :           7 : btck_Coin* btck_coin_copy(const btck_Coin* coin)
    1577                 :             : {
    1578                 :           7 :     return btck_Coin::copy(coin);
    1579                 :             : }
    1580                 :             : 
    1581                 :           1 : uint32_t btck_coin_confirmation_height(const btck_Coin* coin)
    1582                 :             : {
    1583                 :           1 :     return btck_Coin::get(coin).nHeight;
    1584                 :             : }
    1585                 :             : 
    1586                 :           1 : int btck_coin_is_coinbase(const btck_Coin* coin)
    1587                 :             : {
    1588         [ +  - ]:           1 :     return btck_Coin::get(coin).IsCoinBase() ? 1 : 0;
    1589                 :             : }
    1590                 :             : 
    1591                 :           2 : const btck_TransactionOutput* btck_coin_get_output(const btck_Coin* coin)
    1592                 :             : {
    1593                 :           2 :     return btck_TransactionOutput::ref(&btck_Coin::get(coin).out);
    1594                 :             : }
    1595                 :             : 
    1596                 :           9 : void btck_coin_destroy(btck_Coin* coin)
    1597                 :             : {
    1598         [ +  + ]:           9 :     delete coin;
    1599                 :           9 : }
    1600                 :             : 
    1601                 :         421 : int btck_chainstate_manager_process_block(
    1602                 :             :     btck_ChainstateManager* chainman,
    1603                 :             :     const btck_Block* block,
    1604                 :             :     int* _new_block)
    1605                 :             : {
    1606                 :         421 :     bool new_block;
    1607                 :         421 :     auto result = btck_ChainstateManager::get(chainman).m_chainman->ProcessNewBlock(btck_Block::get(block), /*force_processing=*/true, /*min_pow_checked=*/true, /*new_block=*/&new_block);
    1608         [ +  - ]:         421 :     if (_new_block) {
    1609         [ +  + ]:         424 :         *_new_block = new_block ? 1 : 0;
    1610                 :             :     }
    1611         [ +  + ]:         421 :     return result ? 0 : -1;
    1612                 :             : }
    1613                 :             : 
    1614                 :         208 : btck_BlockValidationState* btck_chainstate_manager_process_block_header(
    1615                 :             :     btck_ChainstateManager* chainstate_manager,
    1616                 :             :     const btck_BlockHeader* header)
    1617                 :             : {
    1618                 :         208 :     try {
    1619                 :         208 :         auto& chainman = btck_ChainstateManager::get(chainstate_manager).m_chainman;
    1620                 :             : 
    1621         [ +  - ]:         208 :         auto state = btck_BlockValidationState::create();
    1622         [ +  - ]:         208 :         bool result{chainman->ProcessNewBlockHeaders({&btck_BlockHeader::get(header), 1}, /*min_pow_checked=*/true, btck_BlockValidationState::get(state))};
    1623         [ -  + ]:         208 :         assert(result == btck_BlockValidationState::get(state).IsValid());
    1624                 :             :         return state;
    1625         [ -  - ]:           0 :     } catch (const std::exception& e) {
    1626         [ -  - ]:           0 :         LogError("Failed to process block header: %s", e.what());
    1627                 :           0 :         return nullptr;
    1628                 :           0 :     }
    1629                 :             : }
    1630                 :             : 
    1631                 :         269 : const btck_Chain* btck_chainstate_manager_get_active_chain(const btck_ChainstateManager* chainman)
    1632                 :             : {
    1633   [ +  -  +  - ]:         807 :     return btck_Chain::ref(&WITH_LOCK(btck_ChainstateManager::get(chainman).m_chainman->GetMutex(), return btck_ChainstateManager::get(chainman).m_chainman->ActiveChain()));
    1634                 :             : }
    1635                 :             : 
    1636                 :         292 : int32_t btck_chain_get_height(const btck_Chain* chain)
    1637                 :             : {
    1638                 :         292 :     LOCK(::cs_main);
    1639   [ -  +  +  - ]:         292 :     return btck_Chain::get(chain).Height();
    1640                 :         292 : }
    1641                 :             : 
    1642                 :        7512 : const btck_BlockTreeEntry* btck_chain_get_by_height(const btck_Chain* chain, int32_t height)
    1643                 :             : {
    1644                 :        7512 :     LOCK(::cs_main);
    1645   [ +  -  +  - ]:       15024 :     return btck_BlockTreeEntry::ref(btck_Chain::get(chain)[height]);
    1646                 :        7512 : }
    1647                 :             : 
    1648                 :         207 : int btck_chain_contains(const btck_Chain* chain, const btck_BlockTreeEntry* entry)
    1649                 :             : {
    1650                 :         207 :     LOCK(::cs_main);
    1651         [ +  + ]:         207 :     return btck_Chain::get(chain).Contains(btck_BlockTreeEntry::get(entry)) ? 1 : 0;
    1652                 :         207 : }
    1653                 :             : 
    1654                 :           4 : btck_BlockHeader* btck_block_header_create(const void* raw_block_header, size_t raw_block_header_len)
    1655                 :             : {
    1656         [ -  + ]:           4 :     assert(raw_block_header != nullptr && raw_block_header_len == 80);
    1657                 :           4 :     auto header{std::make_unique<CBlockHeader>()};
    1658         [ +  - ]:           4 :     SpanReader stream{std::span{reinterpret_cast<const std::byte*>(raw_block_header), raw_block_header_len}};
    1659                 :             : 
    1660                 :           4 :     try {
    1661         [ +  - ]:           4 :         stream >> *header;
    1662                 :           0 :     } catch (...) {
    1663         [ -  - ]:           0 :         LogError("Block header decode failed.");
    1664                 :           0 :         return nullptr;
    1665         [ -  - ]:           0 :     }
    1666                 :             : 
    1667                 :           4 :     return btck_BlockHeader::ref(header.release());
    1668                 :           4 : }
    1669                 :             : 
    1670                 :           5 : btck_BlockHeader* btck_block_header_copy(const btck_BlockHeader* header)
    1671                 :             : {
    1672                 :           5 :     return btck_BlockHeader::copy(header);
    1673                 :             : }
    1674                 :             : 
    1675                 :         415 : btck_BlockHash* btck_block_header_get_hash(const btck_BlockHeader* header)
    1676                 :             : {
    1677                 :         415 :     return btck_BlockHash::create(btck_BlockHeader::get(header).GetHash());
    1678                 :             : }
    1679                 :             : 
    1680                 :           1 : const btck_BlockHash* btck_block_header_get_prev_hash(const btck_BlockHeader* header)
    1681                 :             : {
    1682                 :           1 :     return btck_BlockHash::ref(&btck_BlockHeader::get(header).hashPrevBlock);
    1683                 :             : }
    1684                 :             : 
    1685                 :           2 : void btck_block_header_get_merkle_root(const btck_BlockHeader* header, unsigned char output[32])
    1686                 :             : {
    1687                 :           2 :     std::memcpy(output, btck_BlockHeader::get(header).hashMerkleRoot.begin(), 32);
    1688                 :           2 : }
    1689                 :             : 
    1690                 :           4 : uint32_t btck_block_header_get_timestamp(const btck_BlockHeader* header)
    1691                 :             : {
    1692                 :           4 :     return btck_BlockHeader::get(header).nTime;
    1693                 :             : }
    1694                 :             : 
    1695                 :           3 : uint32_t btck_block_header_get_bits(const btck_BlockHeader* header)
    1696                 :             : {
    1697                 :           3 :     return btck_BlockHeader::get(header).nBits;
    1698                 :             : }
    1699                 :             : 
    1700                 :           3 : int32_t btck_block_header_get_version(const btck_BlockHeader* header)
    1701                 :             : {
    1702                 :           3 :     return btck_BlockHeader::get(header).nVersion;
    1703                 :             : }
    1704                 :             : 
    1705                 :           3 : uint32_t btck_block_header_get_nonce(const btck_BlockHeader* header)
    1706                 :             : {
    1707                 :           3 :     return btck_BlockHeader::get(header).nNonce;
    1708                 :             : }
    1709                 :             : 
    1710                 :          15 : int btck_block_header_to_bytes(const btck_BlockHeader* header, unsigned char output[80])
    1711                 :             : {
    1712                 :          15 :     try {
    1713         [ +  - ]:          30 :         SpanWriter{std::as_writable_bytes(std::span{output, 80})} << btck_BlockHeader::get(header);
    1714                 :             :         return 0;
    1715                 :           0 :     } catch (...) {
    1716                 :           0 :         return -1;
    1717                 :           0 :     }
    1718                 :             : }
    1719                 :             : 
    1720                 :         426 : void btck_block_header_destroy(btck_BlockHeader* header)
    1721                 :             : {
    1722         [ +  + ]:         426 :     delete header;
    1723                 :         426 : }
    1724                 :             : 
    1725                 :          12 : btck_ValidationMode btck_tx_validation_state_get_validation_mode(const btck_TxValidationState* state_)
    1726                 :             : {
    1727                 :          12 :     const auto& state = btck_TxValidationState::get(state_);
    1728         [ +  + ]:          12 :     if (state.IsValid()) return btck_ValidationMode_VALID;
    1729         [ +  - ]:           9 :     if (state.IsInvalid()) return btck_ValidationMode_INVALID;
    1730                 :             :     return btck_ValidationMode_INTERNAL_ERROR;
    1731                 :             : }
    1732                 :             : 
    1733                 :          11 : btck_TxValidationState* btck_tx_validation_state_create()
    1734                 :             : {
    1735                 :          11 :     return btck_TxValidationState::create();
    1736                 :             : }
    1737                 :             : 
    1738                 :          12 : btck_TxValidationResult btck_tx_validation_state_get_tx_validation_result(const btck_TxValidationState* state_)
    1739                 :             : {
    1740   [ +  -  -  -  :          12 :     switch (btck_TxValidationState::get(state_).GetResult()) {
          -  -  -  -  -  
             -  -  -  -  
                      + ]
    1741                 :             :     case TxValidationResult::TX_RESULT_UNSET:        return btck_TxValidationResult_UNSET;
    1742                 :           9 :     case TxValidationResult::TX_CONSENSUS:           return btck_TxValidationResult_CONSENSUS;
    1743                 :           0 :     case TxValidationResult::TX_INPUTS_NOT_STANDARD: return btck_TxValidationResult_INPUTS_NOT_STANDARD;
    1744                 :           0 :     case TxValidationResult::TX_NOT_STANDARD:        return btck_TxValidationResult_NOT_STANDARD;
    1745                 :           0 :     case TxValidationResult::TX_MISSING_INPUTS:      return btck_TxValidationResult_MISSING_INPUTS;
    1746                 :           0 :     case TxValidationResult::TX_PREMATURE_SPEND:     return btck_TxValidationResult_PREMATURE_SPEND;
    1747                 :           0 :     case TxValidationResult::TX_WITNESS_MUTATED:     return btck_TxValidationResult_WITNESS_MUTATED;
    1748                 :           0 :     case TxValidationResult::TX_WITNESS_STRIPPED:    return btck_TxValidationResult_WITNESS_STRIPPED;
    1749                 :           0 :     case TxValidationResult::TX_CONFLICT:            return btck_TxValidationResult_CONFLICT;
    1750                 :           0 :     case TxValidationResult::TX_MEMPOOL_POLICY:      return btck_TxValidationResult_MEMPOOL_POLICY;
    1751                 :           0 :     case TxValidationResult::TX_NO_MEMPOOL:          return btck_TxValidationResult_NO_MEMPOOL;
    1752                 :           0 :     case TxValidationResult::TX_RECONSIDERABLE:      return btck_TxValidationResult_RECONSIDERABLE;
    1753                 :           0 :     case TxValidationResult::TX_UNKNOWN:             return btck_TxValidationResult_UNKNOWN;
    1754                 :             :     } // no default case, so the compiler can warn about missing cases
    1755                 :           0 :     AssertUnreachable();
    1756                 :             : }
    1757                 :             : 
    1758                 :          11 : void btck_tx_validation_state_destroy(btck_TxValidationState* state)
    1759                 :             : {
    1760         [ +  - ]:          11 :     delete state;
    1761                 :          11 : }
    1762                 :             : 
    1763                 :          12 : int btck_transaction_check(const btck_Transaction* tx, btck_TxValidationState* validation_state)
    1764                 :             : {
    1765                 :          12 :     auto& state = btck_TxValidationState::get(validation_state);
    1766                 :          12 :     state = TxValidationState{};
    1767                 :          12 :     const bool ok = CheckTransaction(*btck_Transaction::get(tx), state);
    1768         [ +  + ]:          12 :     return ok ? 1 : 0;
    1769                 :             : }
    1770                 :             : 
    1771                 :           5 : int btck_set_mock_time(int64_t timestamp)
    1772                 :             : {
    1773                 :           5 :     constexpr int64_t max_time{std::numeric_limits<uint32_t>::max()};
    1774         [ +  + ]:           5 :     if (timestamp < 0 || timestamp > max_time) {
    1775                 :             :         return -1;
    1776                 :             :     }
    1777                 :           3 :     SetMockTime(std::chrono::seconds{timestamp});
    1778                 :           3 :     return 0;
    1779                 :             : }
        

Generated by: LCOV version 2.0-1