/ src / kernel / bitcoinkernel.h
bitcoinkernel.h
   1  // Copyright (c) 2024-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  #ifndef BITCOIN_KERNEL_BITCOINKERNEL_H
   6  #define BITCOIN_KERNEL_BITCOINKERNEL_H
   7  
   8  #ifndef __cplusplus
   9  #include <stddef.h>
  10  #include <stdint.h>
  11  #else
  12  #include <cstddef>
  13  #include <cstdint>
  14  #endif // __cplusplus
  15  
  16  #ifndef BITCOINKERNEL_API
  17      #ifdef BITCOINKERNEL_BUILD
  18          #if defined(_WIN32)
  19              #define BITCOINKERNEL_API __declspec(dllexport)
  20          #else
  21              #define BITCOINKERNEL_API __attribute__((visibility("default")))
  22          #endif
  23      #else
  24          #if defined(_WIN32) && !defined(BITCOINKERNEL_STATIC)
  25              #define BITCOINKERNEL_API __declspec(dllimport)
  26          #else
  27              #define BITCOINKERNEL_API
  28          #endif
  29      #endif
  30  #endif
  31  
  32  /* Warning attributes */
  33  #if defined(__GNUC__)
  34      #define BITCOINKERNEL_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__))
  35  #else
  36      #define BITCOINKERNEL_WARN_UNUSED_RESULT
  37  #endif
  38  
  39  /**
  40   * BITCOINKERNEL_ARG_NONNULL is a compiler attribute used to indicate that
  41   * certain pointer arguments to a function are not expected to be null.
  42   *
  43   * Callers must not pass a null pointer for arguments marked with this attribute,
  44   * as doing so may result in undefined behavior. This attribute should only be
  45   * used for arguments where a null pointer is unambiguously a programmer error,
  46   * such as for opaque handles, and not for pointers to raw input data that might
  47   * validly be null (e.g., from an empty std::span or std::string).
  48   */
  49  #if !defined(BITCOINKERNEL_BUILD) && defined(__GNUC__)
  50      #define BITCOINKERNEL_ARG_NONNULL(...) __attribute__((__nonnull__(__VA_ARGS__)))
  51  #else
  52      #define BITCOINKERNEL_ARG_NONNULL(...)
  53  #endif
  54  
  55  #ifdef __cplusplus
  56  extern "C" {
  57  #endif // __cplusplus
  58  
  59  /**
  60   * @page remarks Remarks
  61   *
  62   * @section purpose Purpose
  63   *
  64   * This header currently exposes an API for interacting with parts of Bitcoin
  65   * Core's consensus code. Users can validate blocks, iterate the block index,
  66   * read block and undo data from disk, and validate scripts. The header is
  67   * unversioned and not stable yet. Users should expect breaking changes. It is
  68   * also not yet included in releases of Bitcoin Core.
  69   *
  70   * @section context Context
  71   *
  72   * The library provides a built-in static constant kernel context. This static
  73   * context offers only limited functionality. It detects and self-checks the
  74   * correct sha256 implementation, initializes the random number generator and
  75   * self-checks the secp256k1 static context. It is used internally for
  76   * otherwise "context-free" operations. This means that the user is not
  77   * required to initialize their own context before using the library.
  78   *
  79   * The user should create their own context for passing it to state-rich validation
  80   * functions and holding callbacks for kernel events.
  81   *
  82   * @section error Error handling
  83   *
  84   * Functions communicate an error through their return types, usually returning
  85   * a nullptr or a status code as documented by the returning function.
  86   * Additionally, verification functions, e.g. for scripts, may communicate more
  87   * detailed error information through status code out parameters.
  88   *
  89   * Fine-grained validation information is communicated through the validation
  90   * interface.
  91   *
  92   * The kernel notifications issue callbacks for errors. These are usually
  93   * indicative of a system error. If such an error is issued, it is recommended
  94   * to halt and tear down the existing kernel objects. Remediating the error may
  95   * require system intervention by the user.
  96   *
  97   * @section pointer Pointer and argument conventions
  98   *
  99   * The user is responsible for de-allocating the memory owned by pointers
 100   * returned by functions. Typically pointers returned by *_create(...) functions
 101   * can be de-allocated by corresponding *_destroy(...) functions.
 102   *
 103   * A function that takes pointer arguments makes no assumptions on their
 104   * lifetime. Once the function returns the user can safely de-allocate the
 105   * passed in arguments.
 106   *
 107   * Const pointers represent views, and do not transfer ownership. Lifetime
 108   * guarantees of these objects are described in the respective documentation.
 109   * Ownership of these resources may be taken by copying. They are typically
 110   * used for iteration with minimal overhead and require some care by the
 111   * programmer that their lifetime is not extended beyond that of the original
 112   * object.
 113   *
 114   * Array lengths follow the pointer argument they describe.
 115   *
 116   * @section types Type conventions
 117   *
 118   * Fixed-width integer types (e.g. int32_t, uint32_t) are used for data values
 119   * such as heights. Plain int and unsigned int are used for boolean-like values
 120   * and flags.
 121   */
 122  
 123  /**
 124   * Opaque data structure for holding a transaction.
 125   */
 126  typedef struct btck_Transaction btck_Transaction;
 127  
 128  /**
 129   * Opaque data structure for holding a script pubkey.
 130   */
 131  typedef struct btck_ScriptPubkey btck_ScriptPubkey;
 132  
 133  /**
 134   * Opaque data structure for holding a transaction output.
 135   */
 136  typedef struct btck_TransactionOutput btck_TransactionOutput;
 137  
 138  /**
 139   * Opaque data structure for holding a logging connection.
 140   *
 141   * The logging connection can be used to manually stop logging.
 142   *
 143   * Messages that were logged before a connection is created are buffered in a
 144   * 1MB buffer. Logging can alternatively be permanently disabled by calling
 145   * @ref btck_logging_disable. Functions changing the logging settings are
 146   * global and change the settings for all existing btck_LoggingConnection
 147   * instances.
 148   */
 149  typedef struct btck_LoggingConnection btck_LoggingConnection;
 150  
 151  /**
 152   * Opaque data structure for holding the chain parameters.
 153   *
 154   * These are eventually placed into a kernel context through the kernel context
 155   * options. The parameters describe the properties of a chain, and may be
 156   * instantiated for either mainnet, testnet, signet, or regtest.
 157   */
 158  typedef struct btck_ChainParameters btck_ChainParameters;
 159  
 160  /**
 161   * Opaque data structure for holding options for creating a new kernel context.
 162   *
 163   * Once a kernel context has been created from these options, they may be
 164   * destroyed. The options hold the notification and validation interface
 165   * callbacks as well as the selected chain type until they are passed to the
 166   * context. If no options are configured, the context will be instantiated with
 167   * no callbacks and for mainnet. Their content and scope can be expanded over
 168   * time.
 169   */
 170  typedef struct btck_ContextOptions btck_ContextOptions;
 171  
 172  /**
 173   * Opaque data structure for holding a kernel context.
 174   *
 175   * The kernel context is used to initialize internal state and hold the chain
 176   * parameters and callbacks for handling error and validation events. Once
 177   * other validation objects are instantiated from it, the context is kept in
 178   * memory for the duration of their lifetimes.
 179   *
 180   * The processing of validation events is done through an internal task runner
 181   * owned by the context. It passes events through the registered validation
 182   * interface callbacks.
 183   *
 184   * A constructed context can be safely used from multiple threads.
 185   */
 186  typedef struct btck_Context btck_Context;
 187  
 188  /**
 189   * Opaque data structure for holding a block tree entry.
 190   *
 191   * This is a pointer to an element in the block index currently in memory of
 192   * the chainstate manager. It is valid for the lifetime of the chainstate
 193   * manager it was retrieved from. The entry is part of a tree-like structure
 194   * that is maintained internally. Every entry, besides the genesis, points to a
 195   * single parent. Multiple entries may share a parent, thus forming a tree.
 196   * Each entry corresponds to a single block and may be used to retrieve its
 197   * data and validation status.
 198   */
 199  typedef struct btck_BlockTreeEntry btck_BlockTreeEntry;
 200  
 201  /**
 202   * Opaque data structure for holding options for creating a new chainstate
 203   * manager.
 204   *
 205   * The chainstate manager options are used to set some parameters for the
 206   * chainstate manager.
 207   */
 208  typedef struct btck_ChainstateManagerOptions btck_ChainstateManagerOptions;
 209  
 210  /**
 211   * Opaque data structure for holding a chainstate manager.
 212   *
 213   * The chainstate manager is the central object for doing validation tasks as
 214   * well as retrieving data from the chain. Internally it is a complex data
 215   * structure with diverse functionality.
 216   *
 217   * Its functionality will be more and more exposed in the future.
 218   */
 219  typedef struct btck_ChainstateManager btck_ChainstateManager;
 220  
 221  /**
 222   * Opaque data structure for holding a block.
 223   */
 224  typedef struct btck_Block btck_Block;
 225  
 226  /**
 227   * Opaque data structure for holding the state of a block during validation.
 228   *
 229   * Contains information indicating whether validation was successful, and if not
 230   * which step during block validation failed.
 231   */
 232  typedef struct btck_BlockValidationState btck_BlockValidationState;
 233  
 234  /**
 235   * Opaque data structure for holding the Consensus Params.
 236   */
 237  typedef struct btck_ConsensusParams btck_ConsensusParams;
 238  
 239  /**
 240   * Opaque data structure for holding the currently known best-chain associated
 241   * with a chainstate.
 242   */
 243  typedef struct btck_Chain btck_Chain;
 244  
 245  /**
 246   * Opaque data structure for holding a block's spent outputs.
 247   *
 248   * Contains all the previous outputs consumed by all transactions in a specific
 249   * block. Internally it holds a nested vector. The top level vector has an
 250   * entry for each transaction in a block (in order of the actual transactions
 251   * of the block and without the coinbase transaction). This is exposed through
 252   * @ref btck_TransactionSpentOutputs. Each btck_TransactionSpentOutputs is in
 253   * turn a vector of all the previous outputs of a transaction (in order of
 254   * their corresponding inputs).
 255   */
 256  typedef struct btck_BlockSpentOutputs btck_BlockSpentOutputs;
 257  
 258  /**
 259   * Opaque data structure for holding a transaction's spent outputs.
 260   *
 261   * Holds the coins consumed by a certain transaction. Retrieved through the
 262   * @ref btck_BlockSpentOutputs. The coins are in the same order as the
 263   * transaction's inputs consuming them.
 264   */
 265  typedef struct btck_TransactionSpentOutputs btck_TransactionSpentOutputs;
 266  
 267  /**
 268   * Opaque data structure for holding a coin.
 269   *
 270   * Holds information on the @ref btck_TransactionOutput held within,
 271   * including the height it was spent at and whether it is a coinbase output.
 272   */
 273  typedef struct btck_Coin btck_Coin;
 274  
 275  /**
 276   * Opaque data structure for holding a block hash.
 277   *
 278   * This is a type-safe identifier for a block.
 279   */
 280  typedef struct btck_BlockHash btck_BlockHash;
 281  
 282  /**
 283   * Opaque data structure for holding a transaction input.
 284   *
 285   * Holds information on the @ref btck_TransactionOutPoint held within.
 286   */
 287  typedef struct btck_TransactionInput btck_TransactionInput;
 288  
 289  /**
 290   * Opaque data structure for holding a transaction out point.
 291   *
 292   * Holds the txid and output index it is pointing to.
 293   */
 294  typedef struct btck_TransactionOutPoint btck_TransactionOutPoint;
 295  
 296  /**
 297   * Opaque data structure for holding precomputed transaction data.
 298   *
 299   * Reusable when verifying multiple inputs of the same transaction.
 300   * This avoids recomputing transaction hashes for each input.
 301   *
 302   * Required when verifying a taproot input.
 303   */
 304  typedef struct btck_PrecomputedTransactionData btck_PrecomputedTransactionData;
 305  
 306  /**
 307   * Opaque data structure for holding a btck_Txid.
 308   *
 309   * This is a type-safe identifier for a transaction.
 310   */
 311  typedef struct btck_Txid btck_Txid;
 312  
 313  /**
 314   * Opaque data structure for holding a btck_BlockHeader.
 315   */
 316  typedef struct btck_BlockHeader btck_BlockHeader;
 317  
 318  /** Current sync state passed to tip changed callbacks. */
 319  typedef uint8_t btck_SynchronizationState;
 320  #define btck_SynchronizationState_INIT_REINDEX ((btck_SynchronizationState)(0))
 321  #define btck_SynchronizationState_INIT_DOWNLOAD ((btck_SynchronizationState)(1))
 322  #define btck_SynchronizationState_POST_INIT ((btck_SynchronizationState)(2))
 323  
 324  /** Possible warning types issued by validation. */
 325  typedef uint8_t btck_Warning;
 326  #define btck_Warning_UNKNOWN_NEW_RULES_ACTIVATED ((btck_Warning)(0))
 327  #define btck_Warning_LARGE_WORK_INVALID_CHAIN ((btck_Warning)(1))
 328  
 329  /** Callback function types */
 330  
 331  /**
 332   * Function signature for the global logging callback. All bitcoin kernel
 333   * internal logs will pass through this callback.
 334   */
 335  typedef void (*btck_LogCallback)(void* user_data, const char* message, size_t message_len);
 336  
 337  /**
 338   * Function signature for freeing user data.
 339   */
 340  typedef void (*btck_DestroyCallback)(void* user_data);
 341  
 342  /**
 343   * Function signatures for the kernel notifications.
 344   */
 345  typedef void (*btck_NotifyBlockTip)(void* user_data, btck_SynchronizationState state, const btck_BlockTreeEntry* entry, double verification_progress);
 346  typedef void (*btck_NotifyHeaderTip)(void* user_data, btck_SynchronizationState state, int64_t height, int64_t timestamp, int presync);
 347  typedef void (*btck_NotifyProgress)(void* user_data, const char* title, size_t title_len, int progress_percent, int resume_possible);
 348  typedef void (*btck_NotifyWarningSet)(void* user_data, btck_Warning warning, const char* message, size_t message_len);
 349  typedef void (*btck_NotifyWarningUnset)(void* user_data, btck_Warning warning);
 350  typedef void (*btck_NotifyFlushError)(void* user_data, const char* message, size_t message_len);
 351  typedef void (*btck_NotifyFatalError)(void* user_data, const char* message, size_t message_len);
 352  
 353  /**
 354   * Function signatures for the validation interface.
 355   */
 356  typedef void (*btck_ValidationInterfaceBlockChecked)(void* user_data, btck_Block* block, const btck_BlockValidationState* state);
 357  typedef void (*btck_ValidationInterfacePoWValidBlock)(void* user_data, btck_Block* block, const btck_BlockTreeEntry* entry);
 358  typedef void (*btck_ValidationInterfaceBlockConnected)(void* user_data, btck_Block* block, const btck_BlockTreeEntry* entry);
 359  typedef void (*btck_ValidationInterfaceBlockDisconnected)(void* user_data, btck_Block* block, const btck_BlockTreeEntry* entry);
 360  
 361  /**
 362   * Function signature for serializing data.
 363   *
 364   * Returns 0 to indicate success.
 365   */
 366  typedef int (*btck_WriteBytes)(const void* bytes, size_t size, void* userdata);
 367  
 368  /**
 369   * Whether a validated data structure is valid, invalid, or an error was
 370   * encountered during processing.
 371   */
 372  typedef uint8_t btck_ValidationMode;
 373  #define btck_ValidationMode_VALID ((btck_ValidationMode)(0))
 374  #define btck_ValidationMode_INVALID ((btck_ValidationMode)(1))
 375  #define btck_ValidationMode_INTERNAL_ERROR ((btck_ValidationMode)(2))
 376  
 377  /**
 378   * A granular "reason" why a block was invalid.
 379   */
 380  typedef uint32_t btck_BlockValidationResult;
 381  #define btck_BlockValidationResult_UNSET ((btck_BlockValidationResult)(0))           //!< initial value. Block has not yet been rejected
 382  #define btck_BlockValidationResult_CONSENSUS ((btck_BlockValidationResult)(1))       //!< invalid by consensus rules (excluding any below reasons)
 383  #define btck_BlockValidationResult_CACHED_INVALID ((btck_BlockValidationResult)(2))  //!< this block was cached as being invalid and we didn't store the reason why
 384  #define btck_BlockValidationResult_INVALID_HEADER ((btck_BlockValidationResult)(3))  //!< invalid proof of work or time too old
 385  #define btck_BlockValidationResult_MUTATED ((btck_BlockValidationResult)(4))         //!< the block's data didn't match the data committed to by the PoW
 386  #define btck_BlockValidationResult_MISSING_PREV ((btck_BlockValidationResult)(5))    //!< We don't have the previous block the checked one is built on
 387  #define btck_BlockValidationResult_INVALID_PREV ((btck_BlockValidationResult)(6))    //!< A block this one builds on is invalid
 388  #define btck_BlockValidationResult_TIME_FUTURE ((btck_BlockValidationResult)(7))     //!< block timestamp was > 2 hours in the future (or our clock is bad)
 389  #define btck_BlockValidationResult_HEADER_LOW_WORK ((btck_BlockValidationResult)(8)) //!< the block header may be on a too-little-work chain
 390  
 391  /**
 392   * Holds the validation interface callbacks. The user data pointer may be used
 393   * to point to user-defined structures to make processing the validation
 394   * callbacks easier. Note that these callbacks block any further validation
 395   * execution when they are called.
 396   */
 397  typedef struct {
 398      void* user_data;                                              //!< Holds a user-defined opaque structure that is passed to the validation
 399                                                                    //!< interface callbacks. If user_data_destroy is also defined ownership of the
 400                                                                    //!< user_data is passed to the created context options and subsequently context.
 401      btck_DestroyCallback user_data_destroy;                       //!< Frees the provided user data structure.
 402      btck_ValidationInterfaceBlockChecked block_checked;           //!< Called when a new block has been fully validated. Contains the
 403                                                                    //!< result of its validation.
 404      btck_ValidationInterfacePoWValidBlock pow_valid_block;        //!< Called when a new block extends the header chain and has a valid transaction
 405                                                                    //!< and segwit merkle root.
 406      btck_ValidationInterfaceBlockConnected block_connected;       //!< Called when a block is valid and has now been connected to the best chain.
 407      btck_ValidationInterfaceBlockDisconnected block_disconnected; //!< Called during a re-org when a block has been removed from the best chain.
 408  } btck_ValidationInterfaceCallbacks;
 409  
 410  /**
 411   * A struct for holding the kernel notification callbacks. The user data
 412   * pointer may be used to point to user-defined structures to make processing
 413   * the notifications easier.
 414   *
 415   * If user_data_destroy is provided, the kernel will automatically call this
 416   * callback to clean up user_data when the notification interface object is destroyed.
 417   * If user_data_destroy is NULL, it is the user's responsibility to ensure that
 418   * the user_data outlives the kernel objects. Notifications can
 419   * occur even as kernel objects are deleted, so care has to be taken to ensure
 420   * safe unwinding.
 421   */
 422  typedef struct {
 423      void* user_data;                        //!< Holds a user-defined opaque structure that is passed to the notification callbacks.
 424                                              //!< If user_data_destroy is also defined ownership of the user_data is passed to the
 425                                              //!< created context options and subsequently context.
 426      btck_DestroyCallback user_data_destroy; //!< Frees the provided user data structure.
 427      btck_NotifyBlockTip block_tip;          //!< The chain's tip was updated to the provided block entry.
 428      btck_NotifyHeaderTip header_tip;        //!< A new best block header was added.
 429      btck_NotifyProgress progress;           //!< Reports on current block synchronization progress.
 430      btck_NotifyWarningSet warning_set;      //!< A warning issued by the kernel library during validation.
 431      btck_NotifyWarningUnset warning_unset;  //!< A previous condition leading to the issuance of a warning is no longer given.
 432      btck_NotifyFlushError flush_error;      //!< An error encountered when flushing data to disk.
 433      btck_NotifyFatalError fatal_error;      //!< An unrecoverable system error encountered by the library.
 434  } btck_NotificationInterfaceCallbacks;
 435  
 436  /**
 437   * A collection of logging categories that may be encountered by kernel code.
 438   */
 439  typedef uint8_t btck_LogCategory;
 440  #define btck_LogCategory_ALL ((btck_LogCategory)(0))
 441  #define btck_LogCategory_BENCH ((btck_LogCategory)(1))
 442  #define btck_LogCategory_BLOCKSTORAGE ((btck_LogCategory)(2))
 443  #define btck_LogCategory_COINDB ((btck_LogCategory)(3))
 444  #define btck_LogCategory_LEVELDB ((btck_LogCategory)(4))
 445  #define btck_LogCategory_MEMPOOL ((btck_LogCategory)(5))
 446  #define btck_LogCategory_PRUNE ((btck_LogCategory)(6))
 447  #define btck_LogCategory_RAND ((btck_LogCategory)(7))
 448  #define btck_LogCategory_REINDEX ((btck_LogCategory)(8))
 449  #define btck_LogCategory_VALIDATION ((btck_LogCategory)(9))
 450  #define btck_LogCategory_KERNEL ((btck_LogCategory)(10))
 451  
 452  /**
 453   * The level at which logs should be produced.
 454   */
 455  typedef uint8_t btck_LogLevel;
 456  #define btck_LogLevel_TRACE ((btck_LogLevel)(0))
 457  #define btck_LogLevel_DEBUG ((btck_LogLevel)(1))
 458  #define btck_LogLevel_INFO ((btck_LogLevel)(2))
 459  
 460  /**
 461   * Options controlling the format of log messages.
 462   *
 463   * Set fields as non-zero to indicate true.
 464   */
 465  typedef struct {
 466      int log_timestamps;               //!< Prepend a timestamp to log messages.
 467      int log_time_micros;              //!< Log timestamps in microsecond precision.
 468      int log_threadnames;              //!< Prepend the name of the thread to log messages.
 469      int log_sourcelocations;          //!< Prepend the source location to log messages.
 470      int always_print_category_levels; //!< Prepend the log category and level to log messages.
 471  } btck_LoggingOptions;
 472  
 473  /**
 474   * A collection of status codes that may be issued by the script verify function.
 475   */
 476  typedef uint8_t btck_ScriptVerifyStatus;
 477  #define btck_ScriptVerifyStatus_OK ((btck_ScriptVerifyStatus)(0))
 478  #define btck_ScriptVerifyStatus_ERROR_INVALID_FLAGS_COMBINATION ((btck_ScriptVerifyStatus)(1)) //!< The flags were combined in an invalid way.
 479  #define btck_ScriptVerifyStatus_ERROR_SPENT_OUTPUTS_REQUIRED ((btck_ScriptVerifyStatus)(2))    //!< The taproot flag was set, so valid spent_outputs have to be provided.
 480  
 481  /**
 482   * Script verification flags that may be composed with each other.
 483   */
 484  typedef uint32_t btck_ScriptVerificationFlags;
 485  #define btck_ScriptVerificationFlags_NONE ((btck_ScriptVerificationFlags)(0))
 486  #define btck_ScriptVerificationFlags_P2SH ((btck_ScriptVerificationFlags)(1U << 0))                 //!< evaluate P2SH (BIP16) subscripts
 487  #define btck_ScriptVerificationFlags_DERSIG ((btck_ScriptVerificationFlags)(1U << 2))               //!< enforce strict DER (BIP66) compliance
 488  #define btck_ScriptVerificationFlags_NULLDUMMY ((btck_ScriptVerificationFlags)(1U << 4))            //!< enforce NULLDUMMY (BIP147)
 489  #define btck_ScriptVerificationFlags_CHECKLOCKTIMEVERIFY ((btck_ScriptVerificationFlags)(1U << 9))  //!< enable CHECKLOCKTIMEVERIFY (BIP65)
 490  #define btck_ScriptVerificationFlags_CHECKSEQUENCEVERIFY ((btck_ScriptVerificationFlags)(1U << 10)) //!< enable CHECKSEQUENCEVERIFY (BIP112)
 491  #define btck_ScriptVerificationFlags_WITNESS ((btck_ScriptVerificationFlags)(1U << 11))             //!< enable WITNESS (BIP141)
 492  #define btck_ScriptVerificationFlags_TAPROOT ((btck_ScriptVerificationFlags)(1U << 17))             //!< enable TAPROOT (BIPs 341 & 342)
 493  #define btck_ScriptVerificationFlags_ALL ((btck_ScriptVerificationFlags)(btck_ScriptVerificationFlags_P2SH |                \
 494                                                                           btck_ScriptVerificationFlags_DERSIG |              \
 495                                                                           btck_ScriptVerificationFlags_NULLDUMMY |           \
 496                                                                           btck_ScriptVerificationFlags_CHECKLOCKTIMEVERIFY | \
 497                                                                           btck_ScriptVerificationFlags_CHECKSEQUENCEVERIFY | \
 498                                                                           btck_ScriptVerificationFlags_WITNESS |             \
 499                                                                           btck_ScriptVerificationFlags_TAPROOT))
 500  
 501  typedef uint8_t btck_ChainType;
 502  #define btck_ChainType_MAINNET ((btck_ChainType)(0))
 503  #define btck_ChainType_TESTNET ((btck_ChainType)(1))
 504  #define btck_ChainType_TESTNET_4 ((btck_ChainType)(2))
 505  #define btck_ChainType_SIGNET ((btck_ChainType)(3))
 506  #define btck_ChainType_REGTEST ((btck_ChainType)(4))
 507  
 508  /** @name Transaction
 509   * Functions for working with transactions.
 510   */
 511  ///@{
 512  
 513  /**
 514   * @brief Create a new transaction from the serialized data.
 515   *
 516   * @param[in] raw_transaction     Serialized transaction.
 517   * @param[in] raw_transaction_len Length of the serialized transaction.
 518   * @return                        The transaction, or null on error.
 519   */
 520  BITCOINKERNEL_API btck_Transaction* BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_create(
 521      const void* raw_transaction, size_t raw_transaction_len);
 522  
 523  /**
 524   * @brief Copy a transaction. Transactions are reference counted, so this just
 525   * increments the reference count.
 526   *
 527   * @param[in] transaction Non-null.
 528   * @return                The copied transaction.
 529   */
 530  BITCOINKERNEL_API btck_Transaction* BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_copy(
 531      const btck_Transaction* transaction) BITCOINKERNEL_ARG_NONNULL(1);
 532  
 533  /**
 534   * @brief Serializes the transaction through the passed in callback to bytes.
 535   * This is consensus serialization that is also used for the P2P network.
 536   *
 537   * @param[in] transaction Non-null.
 538   * @param[in] writer      Non-null, callback to a write bytes function.
 539   * @param[in] user_data   Holds a user-defined opaque structure that will be
 540   *                        passed back through the writer callback.
 541   * @return                0 on success.
 542   */
 543  BITCOINKERNEL_API int btck_transaction_to_bytes(
 544      const btck_Transaction* transaction,
 545      btck_WriteBytes writer,
 546      void* user_data) BITCOINKERNEL_ARG_NONNULL(1, 2);
 547  
 548  /**
 549   * @brief Get the number of outputs of a transaction.
 550   *
 551   * @param[in] transaction Non-null.
 552   * @return                The number of outputs.
 553   */
 554  BITCOINKERNEL_API size_t BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_count_outputs(
 555      const btck_Transaction* transaction) BITCOINKERNEL_ARG_NONNULL(1);
 556  
 557  /**
 558   * @brief Get the transaction outputs at the provided index. The returned
 559   * transaction output is not owned and depends on the lifetime of the
 560   * transaction.
 561   *
 562   * @param[in] transaction  Non-null.
 563   * @param[in] output_index The index of the transaction output to be retrieved.
 564   * @return                 The transaction output
 565   */
 566  BITCOINKERNEL_API const btck_TransactionOutput* BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_get_output_at(
 567      const btck_Transaction* transaction, size_t output_index) BITCOINKERNEL_ARG_NONNULL(1);
 568  
 569  /**
 570   * @brief Get the transaction input at the provided index. The returned
 571   * transaction input is not owned and depends on the lifetime of the
 572   * transaction.
 573   *
 574   * @param[in] transaction Non-null.
 575   * @param[in] input_index The index of the transaction input to be retrieved.
 576   * @return                 The transaction input
 577   */
 578  BITCOINKERNEL_API const btck_TransactionInput* BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_get_input_at(
 579      const btck_Transaction* transaction, size_t input_index) BITCOINKERNEL_ARG_NONNULL(1);
 580  
 581  /**
 582   * @brief Get the number of inputs of a transaction.
 583   *
 584   * @param[in] transaction Non-null.
 585   * @return                The number of inputs.
 586   */
 587  BITCOINKERNEL_API size_t BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_count_inputs(
 588      const btck_Transaction* transaction) BITCOINKERNEL_ARG_NONNULL(1);
 589  
 590  /**
 591   * @brief Get a transaction's nLockTime value.
 592   *
 593   * @param[in] transaction Non-null.
 594   * @return                The nLockTime value.
 595   */
 596  BITCOINKERNEL_API uint32_t BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_get_locktime(
 597      const btck_Transaction* transaction) BITCOINKERNEL_ARG_NONNULL(1);
 598  
 599  /**
 600   * @brief Get the txid of a transaction. The returned txid is not owned and
 601   * depends on the lifetime of the transaction.
 602   *
 603   * @param[in] transaction Non-null.
 604   * @return                The txid.
 605   */
 606  BITCOINKERNEL_API const btck_Txid* BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_get_txid(
 607      const btck_Transaction* transaction) BITCOINKERNEL_ARG_NONNULL(1);
 608  
 609  /**
 610   * Destroy the transaction.
 611   */
 612  BITCOINKERNEL_API void btck_transaction_destroy(btck_Transaction* transaction);
 613  
 614  ///@}
 615  
 616  /** @name PrecomputedTransactionData
 617   * Functions for working with precomputed transaction data.
 618   */
 619  ///@{
 620  
 621  /**
 622   * @brief Create precomputed transaction data for script verification.
 623   *
 624   * @param[in] tx_to             Non-null.
 625   * @param[in] spent_outputs     Nullable for non-taproot verification. Points to an array of
 626   *                              outputs spent by the transaction.
 627   * @param[in] spent_outputs_len Length of the spent_outputs array.
 628   * @return                      The precomputed data, or null on error.
 629   */
 630  BITCOINKERNEL_API btck_PrecomputedTransactionData* BITCOINKERNEL_WARN_UNUSED_RESULT btck_precomputed_transaction_data_create(
 631      const btck_Transaction* tx_to,
 632      const btck_TransactionOutput** spent_outputs, size_t spent_outputs_len) BITCOINKERNEL_ARG_NONNULL(1);
 633  
 634  /**
 635   * @brief Copy precomputed transaction data.
 636   *
 637   * @param[in] precomputed_txdata Non-null.
 638   * @return                       The copied precomputed transaction data.
 639   */
 640  BITCOINKERNEL_API btck_PrecomputedTransactionData* BITCOINKERNEL_WARN_UNUSED_RESULT btck_precomputed_transaction_data_copy(
 641      const btck_PrecomputedTransactionData* precomputed_txdata) BITCOINKERNEL_ARG_NONNULL(1);
 642  
 643  /**
 644   * Destroy the precomputed transaction data.
 645   */
 646  BITCOINKERNEL_API void btck_precomputed_transaction_data_destroy(btck_PrecomputedTransactionData* precomputed_txdata);
 647  
 648  ///@}
 649  
 650  /** @name ScriptPubkey
 651   * Functions for working with script pubkeys.
 652   */
 653  ///@{
 654  
 655  /**
 656   * @brief Create a script pubkey from serialized data.
 657   * @param[in] script_pubkey     Serialized script pubkey.
 658   * @param[in] script_pubkey_len Length of the script pubkey data.
 659   * @return                      The script pubkey.
 660   */
 661  BITCOINKERNEL_API btck_ScriptPubkey* BITCOINKERNEL_WARN_UNUSED_RESULT btck_script_pubkey_create(
 662      const void* script_pubkey, size_t script_pubkey_len);
 663  
 664  /**
 665   * @brief Copy a script pubkey.
 666   *
 667   * @param[in] script_pubkey Non-null.
 668   * @return                  The copied script pubkey.
 669   */
 670  BITCOINKERNEL_API btck_ScriptPubkey* BITCOINKERNEL_WARN_UNUSED_RESULT btck_script_pubkey_copy(
 671      const btck_ScriptPubkey* script_pubkey) BITCOINKERNEL_ARG_NONNULL(1);
 672  
 673  /**
 674   * @brief Verify if the input at input_index of tx_to spends the script pubkey
 675   * under the constraints specified by flags. If the
 676   * `btck_ScriptVerificationFlags_WITNESS` flag is set in the flags bitfield, the
 677   * amount parameter is used. If the taproot flag is set, the precomputed data
 678   * must contain the spent outputs.
 679   *
 680   * @param[in] script_pubkey      Non-null, script pubkey to be spent.
 681   * @param[in] amount             Amount of the script pubkey's associated output. May be zero if
 682   *                               the witness flag is not set.
 683   * @param[in] tx_to              Non-null, transaction spending the script_pubkey.
 684   * @param[in] precomputed_txdata Nullable if the taproot flag is not set. Otherwise, precomputed data
 685   *                               for tx_to with the spent outputs must be provided.
 686   * @param[in] input_index        Index of the input in tx_to spending the script_pubkey.
 687   * @param[in] flags              Bitfield of btck_ScriptVerificationFlags controlling validation constraints.
 688   * @param[out] status            Nullable, will be set to an error code if the operation fails, or OK otherwise.
 689   * @return                       1 if the script is valid, 0 otherwise.
 690   */
 691  BITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_script_pubkey_verify(
 692      const btck_ScriptPubkey* script_pubkey,
 693      int64_t amount,
 694      const btck_Transaction* tx_to,
 695      const btck_PrecomputedTransactionData* precomputed_txdata,
 696      unsigned int input_index,
 697      btck_ScriptVerificationFlags flags,
 698      btck_ScriptVerifyStatus* status) BITCOINKERNEL_ARG_NONNULL(1, 3);
 699  
 700  /**
 701   * @brief Serializes the script pubkey through the passed in callback to bytes.
 702   *
 703   * @param[in] script_pubkey Non-null.
 704   * @param[in] writer        Non-null, callback to a write bytes function.
 705   * @param[in] user_data     Holds a user-defined opaque structure that will be
 706   *                          passed back through the writer callback.
 707   * @return                  0 on success.
 708   */
 709  BITCOINKERNEL_API int btck_script_pubkey_to_bytes(
 710      const btck_ScriptPubkey* script_pubkey,
 711      btck_WriteBytes writer,
 712      void* user_data) BITCOINKERNEL_ARG_NONNULL(1, 2);
 713  
 714  /**
 715   * Destroy the script pubkey.
 716   */
 717  BITCOINKERNEL_API void btck_script_pubkey_destroy(btck_ScriptPubkey* script_pubkey);
 718  
 719  ///@}
 720  
 721  /** @name TransactionOutput
 722   * Functions for working with transaction outputs.
 723   */
 724  ///@{
 725  
 726  /**
 727   * @brief Create a transaction output from a script pubkey and an amount.
 728   *
 729   * @param[in] script_pubkey Non-null.
 730   * @param[in] amount        The amount associated with the script pubkey for this output.
 731   * @return                  The transaction output.
 732   */
 733  BITCOINKERNEL_API btck_TransactionOutput* BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_output_create(
 734      const btck_ScriptPubkey* script_pubkey,
 735      int64_t amount) BITCOINKERNEL_ARG_NONNULL(1);
 736  
 737  /**
 738   * @brief Get the script pubkey of the output. The returned
 739   * script pubkey is not owned and depends on the lifetime of the
 740   * transaction output.
 741   *
 742   * @param[in] transaction_output Non-null.
 743   * @return                       The script pubkey.
 744   */
 745  BITCOINKERNEL_API const btck_ScriptPubkey* BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_output_get_script_pubkey(
 746      const btck_TransactionOutput* transaction_output) BITCOINKERNEL_ARG_NONNULL(1);
 747  
 748  /**
 749   * @brief Get the amount in the output.
 750   *
 751   * @param[in] transaction_output Non-null.
 752   * @return                       The amount.
 753   */
 754  BITCOINKERNEL_API int64_t BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_output_get_amount(
 755      const btck_TransactionOutput* transaction_output) BITCOINKERNEL_ARG_NONNULL(1);
 756  
 757  /**
 758   *  @brief Copy a transaction output.
 759   *
 760   *  @param[in] transaction_output Non-null.
 761   *  @return                       The copied transaction output.
 762   */
 763  BITCOINKERNEL_API btck_TransactionOutput* BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_output_copy(
 764      const btck_TransactionOutput* transaction_output) BITCOINKERNEL_ARG_NONNULL(1);
 765  
 766  /**
 767   * Destroy the transaction output.
 768   */
 769  BITCOINKERNEL_API void btck_transaction_output_destroy(btck_TransactionOutput* transaction_output);
 770  
 771  ///@}
 772  
 773  /** @name Logging
 774   * Logging-related functions.
 775   */
 776  ///@{
 777  
 778  /**
 779   * @brief This disables the global internal logger. No log messages will be
 780   * buffered internally anymore once this is called and the buffer is cleared.
 781   * This function should only be called once and is not thread or re-entry safe.
 782   * Log messages will be buffered until this function is called, or a logging
 783   * connection is created. This must not be called while a logging connection
 784   * already exists.
 785   */
 786  BITCOINKERNEL_API void btck_logging_disable();
 787  
 788  /**
 789   * @brief Set some options for the global internal logger. This changes global
 790   * settings and will override settings for all existing @ref
 791   * btck_LoggingConnection instances.
 792   *
 793   * @param[in] options Sets formatting options of the log messages.
 794   */
 795  BITCOINKERNEL_API void btck_logging_set_options(btck_LoggingOptions options);
 796  
 797  /**
 798   * @brief Set the log level of the global internal logger. This does not
 799   * enable the selected categories. Use @ref btck_logging_enable_category to
 800   * start logging from a specific, or all categories. This changes a global
 801   * setting and will override settings for all existing
 802   * @ref btck_LoggingConnection instances.
 803   *
 804   * @param[in] category If btck_LogCategory_ALL is chosen, sets both the global fallback log level
 805   *                     used by all categories that don't have a specific level set, and also
 806   *                     sets the log level for messages logged with the btck_LogCategory_ALL category itself.
 807   *                     For any other category, sets a category-specific log level that overrides
 808   *                     the global fallback for that category only.
 809  
 810   * @param[in] level    Log level at which the log category is set.
 811   */
 812  BITCOINKERNEL_API void btck_logging_set_level_category(btck_LogCategory category, btck_LogLevel level);
 813  
 814  /**
 815   * @brief Enable a specific log category for the global internal logger. This
 816   * changes a global setting and will override settings for all existing @ref
 817   * btck_LoggingConnection instances.
 818   *
 819   * @param[in] category If btck_LogCategory_ALL is chosen, all categories will be enabled.
 820   */
 821  BITCOINKERNEL_API void btck_logging_enable_category(btck_LogCategory category);
 822  
 823  /**
 824   * @brief Disable a specific log category for the global internal logger. This
 825   * changes a global setting and will override settings for all existing @ref
 826   * btck_LoggingConnection instances.
 827   *
 828   * @param[in] category If btck_LogCategory_ALL is chosen, all categories will be disabled.
 829   */
 830  BITCOINKERNEL_API void btck_logging_disable_category(btck_LogCategory category);
 831  
 832  /**
 833   * @brief Start logging messages through the provided callback. Log messages
 834   * produced before this function is first called are buffered and on calling this
 835   * function are logged immediately.
 836   *
 837   * @param[in] log_callback               Non-null, function through which messages will be logged.
 838   * @param[in] user_data                  Nullable, holds a user-defined opaque structure. Is passed back
 839   *                                       to the user through the callback. If the user_data_destroy_callback
 840   *                                       is also defined it is assumed that ownership of the user_data is passed
 841   *                                       to the created logging connection.
 842   * @param[in] user_data_destroy_callback Nullable, function for freeing the user data.
 843   * @return                               A new kernel logging connection, or null on error.
 844   */
 845  BITCOINKERNEL_API btck_LoggingConnection* BITCOINKERNEL_WARN_UNUSED_RESULT btck_logging_connection_create(
 846      btck_LogCallback log_callback,
 847      void* user_data,
 848      btck_DestroyCallback user_data_destroy_callback) BITCOINKERNEL_ARG_NONNULL(1);
 849  
 850  /**
 851   * Stop logging and destroy the logging connection.
 852   */
 853  BITCOINKERNEL_API void btck_logging_connection_destroy(btck_LoggingConnection* logging_connection);
 854  
 855  ///@}
 856  
 857  /** @name ChainParameters
 858   * Functions for working with chain parameters.
 859   */
 860  ///@{
 861  
 862  /**
 863   * @brief Creates a chain parameters struct with default parameters based on the
 864   * passed in chain type.
 865   *
 866   * @param[in] chain_type Controls the chain parameters type created.
 867   * @return               An allocated chain parameters opaque struct.
 868   */
 869  BITCOINKERNEL_API btck_ChainParameters* BITCOINKERNEL_WARN_UNUSED_RESULT btck_chain_parameters_create(
 870      btck_ChainType chain_type);
 871  
 872  /**
 873   * Copy the chain parameters.
 874   */
 875  BITCOINKERNEL_API btck_ChainParameters* BITCOINKERNEL_WARN_UNUSED_RESULT btck_chain_parameters_copy(
 876      const btck_ChainParameters* chain_parameters) BITCOINKERNEL_ARG_NONNULL(1);
 877  
 878  /**
 879   * @brief Get btck_ConsensusParams from btck_ChainParameters. The returned
 880   * btck_ConsensusParams pointer is valid only for the lifetime of the
 881   * btck_ChainParameters object and must not be destroyed by the caller.
 882   *
 883   * @param[in] chain_parameters  Non-null.
 884   * @return                      The btck_ConsensusParams.
 885   */
 886  BITCOINKERNEL_API const btck_ConsensusParams* BITCOINKERNEL_WARN_UNUSED_RESULT btck_chain_parameters_get_consensus_params(
 887      const btck_ChainParameters* chain_parameters) BITCOINKERNEL_ARG_NONNULL(1);
 888  
 889  /**
 890   * Destroy the chain parameters.
 891   */
 892  BITCOINKERNEL_API void btck_chain_parameters_destroy(btck_ChainParameters* chain_parameters);
 893  
 894  ///@}
 895  
 896  /** @name ContextOptions
 897   * Functions for working with context options.
 898   */
 899  ///@{
 900  
 901  /**
 902   * Creates an empty context options.
 903   */
 904  BITCOINKERNEL_API btck_ContextOptions* BITCOINKERNEL_WARN_UNUSED_RESULT btck_context_options_create();
 905  
 906  /**
 907   * @brief Sets the chain params for the context options. The context created
 908   * with the options will be configured for these chain parameters.
 909   *
 910   * @param[in] context_options  Non-null, previously created by @ref btck_context_options_create.
 911   * @param[in] chain_parameters Is set to the context options.
 912   */
 913  BITCOINKERNEL_API void btck_context_options_set_chainparams(
 914      btck_ContextOptions* context_options,
 915      const btck_ChainParameters* chain_parameters) BITCOINKERNEL_ARG_NONNULL(1, 2);
 916  
 917  /**
 918   * @brief Set the kernel notifications for the context options. The context
 919   * created with the options will be configured with these notifications.
 920   *
 921   * @param[in] context_options Non-null, previously created by @ref btck_context_options_create.
 922   * @param[in] notifications   Is set to the context options.
 923   */
 924  BITCOINKERNEL_API void btck_context_options_set_notifications(
 925      btck_ContextOptions* context_options,
 926      btck_NotificationInterfaceCallbacks notifications) BITCOINKERNEL_ARG_NONNULL(1);
 927  
 928  /**
 929   * @brief Set the validation interface callbacks for the context options. The
 930   * context created with the options will be configured for these validation
 931   * interface callbacks. The callbacks will then be triggered from validation
 932   * events issued by the chainstate manager created from the same context.
 933   *
 934   * @param[in] context_options                Non-null, previously created with btck_context_options_create.
 935   * @param[in] validation_interface_callbacks The callbacks used for passing validation information to the
 936   *                                           user.
 937   */
 938  BITCOINKERNEL_API void btck_context_options_set_validation_interface(
 939      btck_ContextOptions* context_options,
 940      btck_ValidationInterfaceCallbacks validation_interface_callbacks) BITCOINKERNEL_ARG_NONNULL(1);
 941  
 942  /**
 943   * Destroy the context options.
 944   */
 945  BITCOINKERNEL_API void btck_context_options_destroy(btck_ContextOptions* context_options);
 946  
 947  ///@}
 948  
 949  /** @name Context
 950   * Functions for working with contexts.
 951   */
 952  ///@{
 953  
 954  /**
 955   * @brief Create a new kernel context. If the options have not been previously
 956   * set, their corresponding fields will be initialized to default values; the
 957   * context will assume mainnet chain parameters and won't attempt to call the
 958   * kernel notification callbacks.
 959   *
 960   * @param[in] context_options Nullable, created by @ref btck_context_options_create.
 961   * @return                    The allocated context, or null on error.
 962   */
 963  BITCOINKERNEL_API btck_Context* BITCOINKERNEL_WARN_UNUSED_RESULT btck_context_create(
 964      const btck_ContextOptions* context_options);
 965  
 966  /**
 967   * Copy the context.
 968   */
 969  BITCOINKERNEL_API btck_Context* BITCOINKERNEL_WARN_UNUSED_RESULT btck_context_copy(
 970      const btck_Context* context) BITCOINKERNEL_ARG_NONNULL(1);
 971  
 972  /**
 973   * @brief Interrupt can be used to halt long-running validation functions like
 974   * when reindexing, importing or processing blocks.
 975   *
 976   * @param[in] context  Non-null.
 977   * @return             0 if the interrupt was successful, non-zero otherwise.
 978   */
 979  BITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_context_interrupt(
 980      btck_Context* context) BITCOINKERNEL_ARG_NONNULL(1);
 981  
 982  /**
 983   * Destroy the context.
 984   */
 985  BITCOINKERNEL_API void btck_context_destroy(btck_Context* context);
 986  
 987  ///@}
 988  
 989  /** @name BlockTreeEntry
 990   * Functions for working with block tree entries.
 991   */
 992  ///@{
 993  
 994  /**
 995   * @brief Returns the previous block tree entry in the tree, or null if the current
 996   * block tree entry is the genesis block.
 997   *
 998   * @param[in] block_tree_entry Non-null.
 999   * @return                     The previous block tree entry, or null on error or if the current block tree entry is the genesis block.
1000   */
1001  BITCOINKERNEL_API const btck_BlockTreeEntry* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_tree_entry_get_previous(
1002      const btck_BlockTreeEntry* block_tree_entry) BITCOINKERNEL_ARG_NONNULL(1);
1003  
1004  /**
1005   * @brief Return the btck_BlockHeader associated with this entry.
1006   *
1007   * @param[in] block_tree_entry Non-null.
1008   * @return                     btck_BlockHeader.
1009   */
1010  BITCOINKERNEL_API btck_BlockHeader* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_tree_entry_get_block_header(
1011      const btck_BlockTreeEntry* block_tree_entry) BITCOINKERNEL_ARG_NONNULL(1);
1012  
1013  /**
1014   * @brief Return the height of a certain block tree entry.
1015   *
1016   * @param[in] block_tree_entry Non-null.
1017   * @return                     The block height.
1018   */
1019  BITCOINKERNEL_API int32_t BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_tree_entry_get_height(
1020      const btck_BlockTreeEntry* block_tree_entry) BITCOINKERNEL_ARG_NONNULL(1);
1021  
1022  /**
1023   * @brief Return the block hash associated with a block tree entry.
1024   *
1025   * @param[in] block_tree_entry Non-null.
1026   * @return                     The block hash.
1027   */
1028  BITCOINKERNEL_API const btck_BlockHash* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_tree_entry_get_block_hash(
1029      const btck_BlockTreeEntry* block_tree_entry) BITCOINKERNEL_ARG_NONNULL(1);
1030  
1031  /**
1032   * @brief Check if two block tree entries are equal. Two block tree entries are equal when they
1033   * point to the same block.
1034   *
1035   * @param[in] entry1 Non-null.
1036   * @param[in] entry2 Non-null.
1037   * @return           1 if the block tree entries are equal, 0 otherwise.
1038   */
1039  BITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_tree_entry_equals(
1040      const btck_BlockTreeEntry* entry1, const btck_BlockTreeEntry* entry2) BITCOINKERNEL_ARG_NONNULL(1, 2);
1041  
1042  /**
1043   * @brief Return the ancestor of a btck_BlockTreeEntry at the given height.
1044   *
1045   * @param[in] block_tree_entry Non-null.
1046   * @param[in] height           The height of the requested ancestor.
1047   * @return                     The ancestor at the given height.
1048   */
1049  BITCOINKERNEL_API const btck_BlockTreeEntry* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_tree_entry_get_ancestor(
1050      const btck_BlockTreeEntry* block_tree_entry,
1051      int32_t height) BITCOINKERNEL_ARG_NONNULL(1);
1052  
1053  ///@}
1054  
1055  /** @name ChainstateManagerOptions
1056   * Functions for working with chainstate manager options.
1057   */
1058  ///@{
1059  
1060  /**
1061   * @brief Create options for the chainstate manager.
1062   *
1063   * @param[in] context          Non-null, the created options and through it the chainstate manager will
1064   *                             associate with this kernel context for the duration of their lifetimes.
1065   * @param[in] data_directory   Non-null, non-empty path string of the directory containing the
1066   *                             chainstate data. If the directory does not exist yet, it will be
1067   *                             created.
1068   * @param[in] blocks_directory Non-null, non-empty path string of the directory containing the block
1069   *                             data. If the directory does not exist yet, it will be created.
1070   * @return                     The allocated chainstate manager options, or null on error.
1071   */
1072  BITCOINKERNEL_API btck_ChainstateManagerOptions* BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_options_create(
1073      const btck_Context* context,
1074      const char* data_directory,
1075      size_t data_directory_len,
1076      const char* blocks_directory,
1077      size_t blocks_directory_len) BITCOINKERNEL_ARG_NONNULL(1);
1078  
1079  /**
1080   * @brief Set the number of available worker threads used during validation.
1081   *
1082   * @param[in] chainstate_manager_options Non-null, options to be set.
1083   * @param[in] worker_threads             The number of worker threads that should be spawned in the thread pool
1084   *                                       used for validation. When set to 0 no parallel verification is done.
1085   *                                       The value range is clamped internally between 0 and 15.
1086   */
1087  BITCOINKERNEL_API void btck_chainstate_manager_options_set_worker_threads_num(
1088      btck_ChainstateManagerOptions* chainstate_manager_options,
1089      int worker_threads) BITCOINKERNEL_ARG_NONNULL(1);
1090  
1091  /**
1092   * @brief Sets wipe db in the options. In combination with calling
1093   * @ref btck_chainstate_manager_import_blocks this triggers either a full reindex,
1094   * or a reindex of just the chainstate database.
1095   *
1096   * @param[in] chainstate_manager_options Non-null, created by @ref btck_chainstate_manager_options_create.
1097   * @param[in] wipe_block_tree_db         Set wipe block tree db. Should only be 1 if wipe_chainstate_db is 1 too.
1098   * @param[in] wipe_chainstate_db         Set wipe chainstate db.
1099   * @return                               0 if the set was successful, non-zero if the set failed.
1100   */
1101  BITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_options_set_wipe_dbs(
1102      btck_ChainstateManagerOptions* chainstate_manager_options,
1103      int wipe_block_tree_db,
1104      int wipe_chainstate_db) BITCOINKERNEL_ARG_NONNULL(1);
1105  
1106  /**
1107   * @brief Sets block tree db in memory in the options.
1108   *
1109   * @param[in] chainstate_manager_options   Non-null, created by @ref btck_chainstate_manager_options_create.
1110   * @param[in] block_tree_db_in_memory      Set block tree db in memory.
1111   */
1112  BITCOINKERNEL_API void btck_chainstate_manager_options_update_block_tree_db_in_memory(
1113      btck_ChainstateManagerOptions* chainstate_manager_options,
1114      int block_tree_db_in_memory) BITCOINKERNEL_ARG_NONNULL(1);
1115  
1116  /**
1117   * @brief Sets chainstate db in memory in the options.
1118   *
1119   * @param[in] chainstate_manager_options Non-null, created by @ref btck_chainstate_manager_options_create.
1120   * @param[in] chainstate_db_in_memory    Set chainstate db in memory.
1121   */
1122  BITCOINKERNEL_API void btck_chainstate_manager_options_update_chainstate_db_in_memory(
1123      btck_ChainstateManagerOptions* chainstate_manager_options,
1124      int chainstate_db_in_memory) BITCOINKERNEL_ARG_NONNULL(1);
1125  
1126  /**
1127   * Destroy the chainstate manager options.
1128   */
1129  BITCOINKERNEL_API void btck_chainstate_manager_options_destroy(btck_ChainstateManagerOptions* chainstate_manager_options);
1130  
1131  ///@}
1132  
1133  /** @name ChainstateManager
1134   * Functions for chainstate management.
1135   */
1136  ///@{
1137  
1138  /**
1139   * @brief Create a chainstate manager. This is the main object for many
1140   * validation tasks as well as for retrieving data from the chain and
1141   * interacting with its chainstate and indexes.
1142   *
1143   * @param[in] chainstate_manager_options Non-null, created by @ref btck_chainstate_manager_options_create.
1144   * @return                               The allocated chainstate manager, or null on error.
1145   */
1146  BITCOINKERNEL_API btck_ChainstateManager* BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_create(
1147      const btck_ChainstateManagerOptions* chainstate_manager_options) BITCOINKERNEL_ARG_NONNULL(1);
1148  
1149  /**
1150   * @brief Get the btck_BlockTreeEntry whose associated btck_BlockHeader has the most
1151   * known cumulative proof of work.
1152   *
1153   * @param[in] chainstate_manager Non-null.
1154   * @return                       The btck_BlockTreeEntry.
1155   */
1156  BITCOINKERNEL_API const btck_BlockTreeEntry* BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_get_best_entry(
1157      const btck_ChainstateManager* chainstate_manager) BITCOINKERNEL_ARG_NONNULL(1);
1158  
1159  /**
1160   * @brief Processes and validates the provided btck_BlockHeader.
1161   *
1162   * @param[in] chainstate_manager        Non-null.
1163   * @param[in] header                    Non-null btck_BlockHeader to be validated.
1164   * @param[out] block_validation_state   The result of the btck_BlockHeader validation.
1165   * @return                              0 if btck_BlockHeader processing completed successfully, non-zero on error.
1166   */
1167  BITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_process_block_header(
1168      btck_ChainstateManager* chainstate_manager,
1169      const btck_BlockHeader* header,
1170      btck_BlockValidationState* block_validation_state) BITCOINKERNEL_ARG_NONNULL(1, 2, 3);
1171  
1172  /**
1173   * @brief Triggers the start of a reindex if the wipe options were previously
1174   * set for the chainstate manager. Can also import an array of existing block
1175   * files selected by the user.
1176   *
1177   * @param[in] chainstate_manager        Non-null.
1178   * @param[in] block_file_paths_data     Nullable, array of block files described by their full filesystem paths.
1179   * @param[in] block_file_paths_lens     Nullable, array containing the lengths of each of the paths.
1180   * @param[in] block_file_paths_data_len Length of the block_file_paths_data and block_file_paths_len arrays.
1181   * @return                              0 if the import blocks call was completed successfully, non-zero otherwise.
1182   */
1183  BITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_import_blocks(
1184      btck_ChainstateManager* chainstate_manager,
1185      const char** block_file_paths_data, size_t* block_file_paths_lens,
1186      size_t block_file_paths_data_len) BITCOINKERNEL_ARG_NONNULL(1);
1187  
1188  /**
1189   * @brief Process and validate the passed in block with the chainstate
1190   * manager. Processing first does checks on the block, and if these passed,
1191   * saves it to disk. It then validates the block against the utxo set. If it is
1192   * valid, the chain is extended with it. The return value is not indicative of
1193   * the block's validity. Detailed information on the validity of the block can
1194   * be retrieved by registering the `block_checked` callback in the validation
1195   * interface.
1196   *
1197   * @param[in] chainstate_manager Non-null.
1198   * @param[in] block              Non-null, block to be validated.
1199   *
1200   * @param[out] new_block         Nullable, will be set to 1 if this block was not processed before. Note that this means it
1201   *                               might also not be 1 if processing was attempted before, but the block was found invalid
1202   *                               before its data was persisted.
1203   * @return                       0 if processing the block was successful. Will also return 0 for valid, but duplicate blocks.
1204   */
1205  BITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_process_block(
1206      btck_ChainstateManager* chainstate_manager,
1207      const btck_Block* block,
1208      int* new_block) BITCOINKERNEL_ARG_NONNULL(1, 2, 3);
1209  
1210  /**
1211   * @brief Returns the best known currently active chain. Its lifetime is
1212   * dependent on the chainstate manager. It can be thought of as a view on a
1213   * vector of block tree entries that form the best chain. The returned chain
1214   * reference always points to the currently active best chain. However, state
1215   * transitions within the chainstate manager (e.g., processing blocks) will
1216   * update the chain's contents. Data retrieved from this chain is only
1217   * consistent up to the point when new data is processed in the chainstate
1218   * manager. It is the user's responsibility to guard against these
1219   * inconsistencies.
1220   *
1221   * @param[in] chainstate_manager Non-null.
1222   * @return                       The chain.
1223   */
1224  BITCOINKERNEL_API const btck_Chain* BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_get_active_chain(
1225      const btck_ChainstateManager* chainstate_manager) BITCOINKERNEL_ARG_NONNULL(1);
1226  
1227  /**
1228   * @brief Retrieve a block tree entry by its block hash.
1229   *
1230   * @param[in] chainstate_manager Non-null.
1231   * @param[in] block_hash         Non-null.
1232   * @return                       The block tree entry of the block with the passed in hash, or null if
1233   *                               the block hash is not found.
1234   */
1235  BITCOINKERNEL_API const btck_BlockTreeEntry* BITCOINKERNEL_WARN_UNUSED_RESULT btck_chainstate_manager_get_block_tree_entry_by_hash(
1236      const btck_ChainstateManager* chainstate_manager,
1237      const btck_BlockHash* block_hash) BITCOINKERNEL_ARG_NONNULL(1, 2);
1238  
1239  /**
1240   * Destroy the chainstate manager.
1241   */
1242  BITCOINKERNEL_API void btck_chainstate_manager_destroy(btck_ChainstateManager* chainstate_manager);
1243  
1244  ///@}
1245  
1246  /** @name Block
1247   * Functions for working with blocks.
1248   */
1249  ///@{
1250  
1251  /**
1252   * @brief Reads the block the passed in block tree entry points to from disk and
1253   * returns it.
1254   *
1255   * @param[in] chainstate_manager Non-null.
1256   * @param[in] block_tree_entry   Non-null.
1257   * @return                       The read out block, or null on error.
1258   */
1259  BITCOINKERNEL_API btck_Block* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_read(
1260      const btck_ChainstateManager* chainstate_manager,
1261      const btck_BlockTreeEntry* block_tree_entry) BITCOINKERNEL_ARG_NONNULL(1, 2);
1262  
1263  /**
1264   * @brief Parse a serialized raw block into a new block object.
1265   *
1266   * @param[in] raw_block     Serialized block.
1267   * @param[in] raw_block_len Length of the serialized block.
1268   * @return                  The allocated block, or null on error.
1269   */
1270  BITCOINKERNEL_API btck_Block* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_create(
1271      const void* raw_block, size_t raw_block_len);
1272  
1273  /**
1274   * @brief Copy a block. Blocks are reference counted, so this just increments
1275   * the reference count.
1276   *
1277   * @param[in] block Non-null.
1278   * @return          The copied block.
1279   */
1280  BITCOINKERNEL_API btck_Block* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_copy(
1281      const btck_Block* block) BITCOINKERNEL_ARG_NONNULL(1);
1282  
1283  /** Bitflags to control context-free block checks (optional). */
1284  typedef uint32_t btck_BlockCheckFlags;
1285  #define btck_BlockCheckFlags_BASE   ((btck_BlockCheckFlags)0)                                                        //!< run the base context-free block checks only
1286  #define btck_BlockCheckFlags_POW    ((btck_BlockCheckFlags)(1U << 0))                                                //!< run CheckProofOfWork via CheckBlockHeader
1287  #define btck_BlockCheckFlags_MERKLE ((btck_BlockCheckFlags)(1U << 1))                                                //!< verify merkle root (and mutation detection)
1288  #define btck_BlockCheckFlags_ALL    ((btck_BlockCheckFlags)(btck_BlockCheckFlags_POW | btck_BlockCheckFlags_MERKLE)) //!< enable all optional context-free block checks
1289  
1290  /**
1291   * @brief Perform context-free validation checks on a btck_Block.
1292   *
1293   * Runs the base context-free block checks (size limits, coinbase structure,
1294   * transaction checks, and sigop limits) using the supplied
1295   * btck_ConsensusParams. The proof-of-work and merkle-root checks are optional
1296   * and can be toggled via @p flags. Note that this does not include any
1297   * transaction script, timestamps, order, or other checks that may require more
1298   * context.
1299   *
1300   * @param[in]     block             Non-null, btck_Block to validate.
1301   * @param[in]     consensus_params  Non-null, btck_ConsensusParams for validation.
1302   * @param[in]     flags             Bitmask of btck_BlockCheckFlags controlling the
1303   *                                  optional POW and merkle-root checks. Use
1304   *                                  btck_BlockCheckFlags_BASE to run only the base
1305   *                                  checks.
1306   * @param[in,out] validation_state  Non-null, previously created with
1307   *                                  btck_block_validation_state_create and updated
1308   *                                  in-place with the validation result.
1309   * @return                          1 if the btck_Block passed the checks, 0 otherwise.
1310   */
1311  BITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_check(
1312      const btck_Block* block,
1313      const btck_ConsensusParams* consensus_params,
1314      btck_BlockCheckFlags flags,
1315      btck_BlockValidationState* validation_state) BITCOINKERNEL_ARG_NONNULL(1, 2, 4);
1316  
1317  /**
1318   * @brief Count the number of transactions contained in a block.
1319   *
1320   * @param[in] block Non-null.
1321   * @return          The number of transactions in the block.
1322   */
1323  BITCOINKERNEL_API size_t BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_count_transactions(
1324      const btck_Block* block) BITCOINKERNEL_ARG_NONNULL(1);
1325  
1326  /**
1327   * @brief Get the transaction at the provided index. The returned transaction
1328   * is not owned and depends on the lifetime of the block.
1329   *
1330   * @param[in] block             Non-null.
1331   * @param[in] transaction_index The index of the transaction to be retrieved.
1332   * @return                      The transaction.
1333   */
1334  BITCOINKERNEL_API const btck_Transaction* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_get_transaction_at(
1335      const btck_Block* block, size_t transaction_index) BITCOINKERNEL_ARG_NONNULL(1);
1336  
1337  /**
1338   * @brief Get the btck_BlockHeader from the block.
1339   *
1340   * Creates a new btck_BlockHeader object from the block's header data.
1341   *
1342   * @param[in] block Non-null btck_Block
1343   * @return          btck_BlockHeader.
1344   */
1345  BITCOINKERNEL_API btck_BlockHeader* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_get_header(
1346      const btck_Block* block) BITCOINKERNEL_ARG_NONNULL(1);
1347  
1348  /**
1349   * @brief Calculate and return the hash of a block.
1350   *
1351   * @param[in] block Non-null.
1352   * @return    The block hash.
1353   */
1354  BITCOINKERNEL_API btck_BlockHash* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_get_hash(
1355      const btck_Block* block) BITCOINKERNEL_ARG_NONNULL(1);
1356  
1357  /**
1358   * @brief Serializes the block through the passed in callback to bytes.
1359   * This is consensus serialization that is also used for the P2P network.
1360   *
1361   * @param[in] block     Non-null.
1362   * @param[in] writer    Non-null, callback to a write bytes function.
1363   * @param[in] user_data Holds a user-defined opaque structure that will be
1364   *                      passed back through the writer callback.
1365   * @return              0 on success.
1366   */
1367  BITCOINKERNEL_API int btck_block_to_bytes(
1368      const btck_Block* block,
1369      btck_WriteBytes writer,
1370      void* user_data) BITCOINKERNEL_ARG_NONNULL(1, 2);
1371  
1372  /**
1373   * Destroy the block.
1374   */
1375  BITCOINKERNEL_API void btck_block_destroy(btck_Block* block);
1376  
1377  ///@}
1378  
1379  /** @name BlockValidationState
1380   * Functions for working with block validation states.
1381   */
1382  ///@{
1383  
1384  /**
1385   * Create a new btck_BlockValidationState.
1386   */
1387  BITCOINKERNEL_API btck_BlockValidationState* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_validation_state_create();
1388  
1389  /**
1390   * Returns the validation mode from an opaque btck_BlockValidationState pointer.
1391   */
1392  BITCOINKERNEL_API btck_ValidationMode btck_block_validation_state_get_validation_mode(
1393      const btck_BlockValidationState* block_validation_state) BITCOINKERNEL_ARG_NONNULL(1);
1394  
1395  /**
1396   * Returns the validation result from an opaque btck_BlockValidationState pointer.
1397   */
1398  BITCOINKERNEL_API btck_BlockValidationResult btck_block_validation_state_get_block_validation_result(
1399      const btck_BlockValidationState* block_validation_state) BITCOINKERNEL_ARG_NONNULL(1);
1400  
1401  /**
1402   * @brief Copies the btck_BlockValidationState.
1403   *
1404   * @param[in] block_validation_state Non-null.
1405   * @return                           The copied btck_BlockValidationState.
1406   */
1407  BITCOINKERNEL_API btck_BlockValidationState* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_validation_state_copy(
1408      const btck_BlockValidationState* block_validation_state) BITCOINKERNEL_ARG_NONNULL(1);
1409  
1410  /**
1411   * Destroy the btck_BlockValidationState.
1412   */
1413  BITCOINKERNEL_API void btck_block_validation_state_destroy(
1414      btck_BlockValidationState* block_validation_state);
1415  
1416  ///@}
1417  
1418  /** @name Chain
1419   * Functions for working with the chain
1420   */
1421  ///@{
1422  
1423  /**
1424   * @brief Return the height of the tip of the chain.
1425   *
1426   * @param[in] chain Non-null.
1427   * @return          The current height.
1428   */
1429  BITCOINKERNEL_API int32_t BITCOINKERNEL_WARN_UNUSED_RESULT btck_chain_get_height(
1430      const btck_Chain* chain) BITCOINKERNEL_ARG_NONNULL(1);
1431  
1432  /**
1433   * @brief Retrieve a block tree entry by its height in the currently active chain.
1434   * Once retrieved there is no guarantee that it remains in the active chain.
1435   *
1436   * @param[in] chain        Non-null.
1437   * @param[in] block_height Height in the chain of the to be retrieved block tree entry.
1438   * @return                 The block tree entry at a certain height in the currently active chain, or null
1439   *                         if the height is out of bounds.
1440   */
1441  BITCOINKERNEL_API const btck_BlockTreeEntry* BITCOINKERNEL_WARN_UNUSED_RESULT btck_chain_get_by_height(
1442      const btck_Chain* chain,
1443      int32_t block_height) BITCOINKERNEL_ARG_NONNULL(1);
1444  
1445  /**
1446   * @brief Return true if the passed in chain contains the block tree entry.
1447   *
1448   * @param[in] chain            Non-null.
1449   * @param[in] block_tree_entry Non-null.
1450   * @return                     1 if the block_tree_entry is in the chain, 0 otherwise.
1451   *
1452   */
1453  BITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_chain_contains(
1454      const btck_Chain* chain,
1455      const btck_BlockTreeEntry* block_tree_entry) BITCOINKERNEL_ARG_NONNULL(1, 2);
1456  
1457  ///@}
1458  
1459  /** @name BlockSpentOutputs
1460   * Functions for working with block spent outputs.
1461   */
1462  ///@{
1463  
1464  /**
1465   * @brief Reads the block spent coins data the passed in block tree entry points to from
1466   * disk and returns it.
1467   *
1468   * @param[in] chainstate_manager Non-null.
1469   * @param[in] block_tree_entry   Non-null.
1470   * @return                       The read out block spent outputs, or null on error.
1471   */
1472  BITCOINKERNEL_API btck_BlockSpentOutputs* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_spent_outputs_read(
1473      const btck_ChainstateManager* chainstate_manager,
1474      const btck_BlockTreeEntry* block_tree_entry) BITCOINKERNEL_ARG_NONNULL(1, 2);
1475  
1476  /**
1477   * @brief Copy a block's spent outputs.
1478   *
1479   * @param[in] block_spent_outputs Non-null.
1480   * @return                        The copied block spent outputs.
1481   */
1482  BITCOINKERNEL_API btck_BlockSpentOutputs* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_spent_outputs_copy(
1483      const btck_BlockSpentOutputs* block_spent_outputs) BITCOINKERNEL_ARG_NONNULL(1);
1484  
1485  /**
1486   * @brief Returns the number of transaction spent outputs whose data is contained in
1487   * block spent outputs.
1488   *
1489   * @param[in] block_spent_outputs Non-null.
1490   * @return                        The number of transaction spent outputs data in the block spent outputs.
1491   */
1492  BITCOINKERNEL_API size_t BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_spent_outputs_count(
1493      const btck_BlockSpentOutputs* block_spent_outputs) BITCOINKERNEL_ARG_NONNULL(1);
1494  
1495  /**
1496   * @brief Returns a transaction spent outputs contained in the block spent
1497   * outputs at a certain index. The returned pointer is unowned and only valid
1498   * for the lifetime of block_spent_outputs.
1499   *
1500   * @param[in] block_spent_outputs             Non-null.
1501   * @param[in] transaction_spent_outputs_index The index of the transaction spent outputs within the block spent outputs.
1502   * @return                                    A transaction spent outputs pointer.
1503   */
1504  BITCOINKERNEL_API const btck_TransactionSpentOutputs* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_spent_outputs_get_transaction_spent_outputs_at(
1505      const btck_BlockSpentOutputs* block_spent_outputs,
1506      size_t transaction_spent_outputs_index) BITCOINKERNEL_ARG_NONNULL(1);
1507  
1508  /**
1509   * Destroy the block spent outputs.
1510   */
1511  BITCOINKERNEL_API void btck_block_spent_outputs_destroy(btck_BlockSpentOutputs* block_spent_outputs);
1512  
1513  ///@}
1514  
1515  /** @name TransactionSpentOutputs
1516   * Functions for working with the spent coins of a transaction
1517   */
1518  ///@{
1519  
1520  /**
1521   * @brief Copy a transaction's spent outputs.
1522   *
1523   * @param[in] transaction_spent_outputs Non-null.
1524   * @return                              The copied transaction spent outputs.
1525   */
1526  BITCOINKERNEL_API btck_TransactionSpentOutputs* BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_spent_outputs_copy(
1527      const btck_TransactionSpentOutputs* transaction_spent_outputs) BITCOINKERNEL_ARG_NONNULL(1);
1528  
1529  /**
1530   * @brief Returns the number of previous transaction outputs contained in the
1531   * transaction spent outputs data.
1532   *
1533   * @param[in] transaction_spent_outputs Non-null
1534   * @return                              The number of spent transaction outputs for the transaction.
1535   */
1536  BITCOINKERNEL_API size_t BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_spent_outputs_count(
1537      const btck_TransactionSpentOutputs* transaction_spent_outputs) BITCOINKERNEL_ARG_NONNULL(1);
1538  
1539  /**
1540   * @brief Returns a coin contained in the transaction spent outputs at a
1541   * certain index. The returned pointer is unowned and only valid for the
1542   * lifetime of transaction_spent_outputs.
1543   *
1544   * @param[in] transaction_spent_outputs Non-null.
1545   * @param[in] coin_index                The index of the to be retrieved coin within the
1546   *                                      transaction spent outputs.
1547   * @return                              A coin pointer.
1548   */
1549  BITCOINKERNEL_API const btck_Coin* BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_spent_outputs_get_coin_at(
1550      const btck_TransactionSpentOutputs* transaction_spent_outputs,
1551      size_t coin_index) BITCOINKERNEL_ARG_NONNULL(1);
1552  
1553  /**
1554   * Destroy the transaction spent outputs.
1555   */
1556  BITCOINKERNEL_API void btck_transaction_spent_outputs_destroy(btck_TransactionSpentOutputs* transaction_spent_outputs);
1557  
1558  ///@}
1559  
1560  /** @name Transaction Input
1561   * Functions for working with transaction inputs.
1562   */
1563  ///@{
1564  
1565  /**
1566   * @brief Copy a transaction input.
1567   *
1568   * @param[in] transaction_input Non-null.
1569   * @return                      The copied transaction input.
1570   */
1571  BITCOINKERNEL_API btck_TransactionInput* BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_input_copy(
1572      const btck_TransactionInput* transaction_input) BITCOINKERNEL_ARG_NONNULL(1);
1573  
1574  /**
1575   * @brief Get the transaction out point. The returned transaction out point is
1576   * not owned and depends on the lifetime of the transaction.
1577   *
1578   * @param[in] transaction_input Non-null.
1579   * @return                      The transaction out point.
1580   */
1581  BITCOINKERNEL_API const btck_TransactionOutPoint* BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_input_get_out_point(
1582      const btck_TransactionInput* transaction_input) BITCOINKERNEL_ARG_NONNULL(1);
1583  
1584  /**
1585   * @brief Get a transaction input's nSequence value.
1586   *
1587   * @param[in] transaction_input Non-null.
1588   * @return                      The nSequence value.
1589   */
1590  BITCOINKERNEL_API uint32_t BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_input_get_sequence(
1591      const btck_TransactionInput* transaction_input) BITCOINKERNEL_ARG_NONNULL(1);
1592  
1593  /**
1594   * Destroy the transaction input.
1595   */
1596  BITCOINKERNEL_API void btck_transaction_input_destroy(btck_TransactionInput* transaction_input);
1597  
1598  ///@}
1599  
1600  /** @name Transaction Out Point
1601   * Functions for working with transaction out points.
1602   */
1603  ///@{
1604  
1605  /**
1606   * @brief Copy a transaction out point.
1607   *
1608   * @param[in] transaction_out_point Non-null.
1609   * @return                          The copied transaction out point.
1610   */
1611  BITCOINKERNEL_API btck_TransactionOutPoint* BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_out_point_copy(
1612      const btck_TransactionOutPoint* transaction_out_point) BITCOINKERNEL_ARG_NONNULL(1);
1613  
1614  /**
1615   * @brief Get the output position from the transaction out point.
1616   *
1617   * @param[in] transaction_out_point Non-null.
1618   * @return                          The output index.
1619   */
1620  BITCOINKERNEL_API uint32_t BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_out_point_get_index(
1621      const btck_TransactionOutPoint* transaction_out_point) BITCOINKERNEL_ARG_NONNULL(1);
1622  
1623  /**
1624   * @brief Get the txid from the transaction out point. The returned txid is
1625   * not owned and depends on the lifetime of the transaction out point.
1626   *
1627   * @param[in] transaction_out_point Non-null.
1628   * @return                          The txid.
1629   */
1630  BITCOINKERNEL_API const btck_Txid* BITCOINKERNEL_WARN_UNUSED_RESULT btck_transaction_out_point_get_txid(
1631      const btck_TransactionOutPoint* transaction_out_point) BITCOINKERNEL_ARG_NONNULL(1);
1632  
1633  /**
1634   * Destroy the transaction out point.
1635   */
1636  BITCOINKERNEL_API void btck_transaction_out_point_destroy(btck_TransactionOutPoint* transaction_out_point);
1637  
1638  ///@}
1639  
1640  /** @name Txid
1641   * Functions for working with txids.
1642   */
1643  ///@{
1644  
1645  /**
1646   * @brief Copy a txid.
1647   *
1648   * @param[in] txid Non-null.
1649   * @return         The copied txid.
1650   */
1651  BITCOINKERNEL_API btck_Txid* BITCOINKERNEL_WARN_UNUSED_RESULT btck_txid_copy(
1652      const btck_Txid* txid) BITCOINKERNEL_ARG_NONNULL(1);
1653  
1654  /**
1655   * @brief Check if two txids are equal.
1656   *
1657   * @param[in] txid1 Non-null.
1658   * @param[in] txid2 Non-null.
1659   * @return          0 if the txid is not equal.
1660   */
1661  BITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_txid_equals(
1662      const btck_Txid* txid1, const btck_Txid* txid2) BITCOINKERNEL_ARG_NONNULL(1, 2);
1663  
1664  /**
1665   * @brief Serializes the txid to bytes.
1666   *
1667   * @param[in] txid    Non-null.
1668   * @param[out] output The serialized txid.
1669   */
1670  BITCOINKERNEL_API void btck_txid_to_bytes(
1671      const btck_Txid* txid, unsigned char output[32]) BITCOINKERNEL_ARG_NONNULL(1, 2);
1672  
1673  /**
1674   * Destroy the txid.
1675   */
1676  BITCOINKERNEL_API void btck_txid_destroy(btck_Txid* txid);
1677  
1678  ///@}
1679  
1680  /** @name Coin
1681   * Functions for working with coins.
1682   */
1683  ///@{
1684  
1685  /**
1686   * @brief Copy a coin.
1687   *
1688   * @param[in] coin Non-null.
1689   * @return         The copied coin.
1690   */
1691  BITCOINKERNEL_API btck_Coin* BITCOINKERNEL_WARN_UNUSED_RESULT btck_coin_copy(
1692      const btck_Coin* coin) BITCOINKERNEL_ARG_NONNULL(1);
1693  
1694  /**
1695   * @brief Returns the block height where the transaction that
1696   * created this coin was included in.
1697   *
1698   * @param[in] coin Non-null.
1699   * @return         The block height of the coin.
1700   */
1701  BITCOINKERNEL_API uint32_t BITCOINKERNEL_WARN_UNUSED_RESULT btck_coin_confirmation_height(
1702      const btck_Coin* coin) BITCOINKERNEL_ARG_NONNULL(1);
1703  
1704  /**
1705   * @brief Returns whether the containing transaction was a coinbase.
1706   *
1707   * @param[in] coin Non-null.
1708   * @return         1 if the coin is a coinbase coin, 0 otherwise.
1709   */
1710  BITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_coin_is_coinbase(
1711      const btck_Coin* coin) BITCOINKERNEL_ARG_NONNULL(1);
1712  
1713  /**
1714   * @brief Return the transaction output of a coin. The returned pointer is
1715   * unowned and only valid for the lifetime of the coin.
1716   *
1717   * @param[in] coin Non-null.
1718   * @return         A transaction output pointer.
1719   */
1720  BITCOINKERNEL_API const btck_TransactionOutput* BITCOINKERNEL_WARN_UNUSED_RESULT btck_coin_get_output(
1721      const btck_Coin* coin) BITCOINKERNEL_ARG_NONNULL(1);
1722  
1723  /**
1724   * Destroy the coin.
1725   */
1726  BITCOINKERNEL_API void btck_coin_destroy(btck_Coin* coin);
1727  
1728  ///@}
1729  
1730  /** @name BlockHash
1731   * Functions for working with block hashes.
1732   */
1733  ///@{
1734  
1735  /**
1736   * @brief Create a block hash from its raw data.
1737   */
1738  BITCOINKERNEL_API btck_BlockHash* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_hash_create(
1739      const unsigned char block_hash[32]) BITCOINKERNEL_ARG_NONNULL(1);
1740  
1741  /**
1742   * @brief Check if two block hashes are equal.
1743   *
1744   * @param[in] hash1 Non-null.
1745   * @param[in] hash2 Non-null.
1746   * @return          0 if the block hashes are not equal.
1747   */
1748  BITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_hash_equals(
1749      const btck_BlockHash* hash1, const btck_BlockHash* hash2) BITCOINKERNEL_ARG_NONNULL(1, 2);
1750  
1751  /**
1752   * @brief Copy a block hash.
1753   *
1754   * @param[in] block_hash Non-null.
1755   * @return               The copied block hash.
1756   */
1757  BITCOINKERNEL_API btck_BlockHash* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_hash_copy(
1758      const btck_BlockHash* block_hash) BITCOINKERNEL_ARG_NONNULL(1);
1759  
1760  /**
1761   * @brief Serializes the block hash to bytes.
1762   *
1763   * @param[in] block_hash     Non-null.
1764   * @param[in] output         The serialized block hash.
1765   */
1766  BITCOINKERNEL_API void btck_block_hash_to_bytes(
1767      const btck_BlockHash* block_hash, unsigned char output[32]) BITCOINKERNEL_ARG_NONNULL(1, 2);
1768  
1769  /**
1770   * Destroy the block hash.
1771   */
1772  BITCOINKERNEL_API void btck_block_hash_destroy(btck_BlockHash* block_hash);
1773  
1774  ///@}
1775  
1776  /**
1777   * @name Block Header
1778   * Functions for working with block headers.
1779   */
1780  ///@{
1781  
1782  /**
1783   * @brief Create a btck_BlockHeader from serialized data.
1784   *
1785   * @param[in] raw_block_header      Non-null, serialized header data (80 bytes)
1786   * @param[in] raw_block_header_len  Length of serialized header (must be 80)
1787   * @return                          btck_BlockHeader, or null on error.
1788   */
1789  BITCOINKERNEL_API btck_BlockHeader* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_header_create(
1790      const void* raw_block_header, size_t raw_block_header_len);
1791  
1792  /**
1793   * @brief Copy a btck_BlockHeader.
1794   *
1795   * @param[in] header    Non-null btck_BlockHeader.
1796   * @return              Copied btck_BlockHeader.
1797   */
1798  BITCOINKERNEL_API btck_BlockHeader* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_header_copy(
1799      const btck_BlockHeader* header) BITCOINKERNEL_ARG_NONNULL(1);
1800  
1801  /**
1802   * @brief Get the btck_BlockHash.
1803   *
1804   * @param[in] header    Non-null header
1805   * @return              btck_BlockHash.
1806   */
1807  BITCOINKERNEL_API btck_BlockHash* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_header_get_hash(
1808      const btck_BlockHeader* header) BITCOINKERNEL_ARG_NONNULL(1);
1809  
1810  /**
1811   * @brief Get the previous btck_BlockHash from btck_BlockHeader. The returned hash
1812   * is unowned and only valid for the lifetime of the btck_BlockHeader.
1813   *
1814   * @param[in] header    Non-null btck_BlockHeader
1815   * @return              Previous btck_BlockHash
1816   */
1817  BITCOINKERNEL_API const btck_BlockHash* BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_header_get_prev_hash(
1818      const btck_BlockHeader* header) BITCOINKERNEL_ARG_NONNULL(1);
1819  
1820  /**
1821   * @brief Get the timestamp from btck_BlockHeader.
1822   *
1823   * @param[in] header    Non-null btck_BlockHeader
1824   * @return              Block timestamp (Unix epoch seconds)
1825   */
1826  BITCOINKERNEL_API uint32_t BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_header_get_timestamp(
1827      const btck_BlockHeader* header) BITCOINKERNEL_ARG_NONNULL(1);
1828  
1829  /**
1830   * @brief Get the nBits difficulty target from btck_BlockHeader.
1831   *
1832   * @param[in] header    Non-null btck_BlockHeader
1833   * @return              Difficulty target (compact format)
1834   */
1835  BITCOINKERNEL_API uint32_t BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_header_get_bits(
1836      const btck_BlockHeader* header) BITCOINKERNEL_ARG_NONNULL(1);
1837  
1838  /**
1839   * @brief Get the version from btck_BlockHeader.
1840   *
1841   * @param[in] header    Non-null btck_BlockHeader
1842   * @return              Block version
1843   */
1844  BITCOINKERNEL_API int32_t BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_header_get_version(
1845      const btck_BlockHeader* header) BITCOINKERNEL_ARG_NONNULL(1);
1846  
1847  /**
1848   * @brief Get the nonce from btck_BlockHeader.
1849   *
1850   * @param[in] header    Non-null btck_BlockHeader
1851   * @return              Nonce
1852   */
1853  BITCOINKERNEL_API uint32_t BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_header_get_nonce(
1854      const btck_BlockHeader* header) BITCOINKERNEL_ARG_NONNULL(1);
1855  
1856  /**
1857   * @brief Serializes the btck_BlockHeader to bytes.
1858   * This is consensus serialization that is also used for the P2P network.
1859   *
1860   * @param[in] header    Non-null.
1861   * @param[out] output   The serialized block header (80 bytes).
1862   * @return              0 on success.
1863   */
1864  BITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_header_to_bytes(
1865      const btck_BlockHeader* header, unsigned char output[80]) BITCOINKERNEL_ARG_NONNULL(1, 2);
1866  
1867  /**
1868   * Destroy the btck_BlockHeader.
1869   */
1870  BITCOINKERNEL_API void btck_block_header_destroy(btck_BlockHeader* header);
1871  
1872  ///@}
1873  
1874  #ifdef __cplusplus
1875  } // extern "C"
1876  #endif // __cplusplus
1877  
1878  #endif // BITCOIN_KERNEL_BITCOINKERNEL_H