5#define BITCOINKERNEL_BUILD
93 : m_writer{writer}, m_user_data{user_data} {}
98 void write(std::span<const std::byte> src)
100 if (m_writer(src.data(), src.size(), m_user_data) != 0) {
101 throw std::runtime_error(
"Failed to write serialization data");
105 template <
typename T>
113template <
typename C,
typename CPP>
115 static C* ref(CPP* cpp_type)
117 return reinterpret_cast<C*
>(cpp_type);
120 static const C* ref(
const CPP* cpp_type)
122 return reinterpret_cast<const C*
>(cpp_type);
125 template <
typename... Args>
126 static C* create(Args&&...
args)
128 auto cpp_obj{std::make_unique<CPP>(std::forward<Args>(
args)...)};
129 return ref(cpp_obj.release());
132 static C* copy(
const C* ptr)
134 auto cpp_obj{std::make_unique<CPP>(get(ptr))};
135 return ref(cpp_obj.release());
138 static const CPP& get(
const C* ptr)
140 return *
reinterpret_cast<const CPP*
>(ptr);
143 static CPP& get(C* ptr)
145 return *
reinterpret_cast<CPP*
>(ptr);
148 static void operator delete(
void* ptr)
150 delete reinterpret_cast<CPP*
>(ptr);
157struct btck_Block : Handle<btck_Block, std::shared_ptr<const CBlock>> {};
249#ifdef DEBUG_LOCKCONTENTION
296 ~KernelNotifications()
343 ~KernelValidationInterface()
357 btck_Block::copy(btck_Block::ref(&block)),
358 btck_BlockValidationState::ref(&stateIn));
366 btck_Block::copy(btck_Block::ref(&block)),
367 btck_BlockTreeEntry::ref(pindex));
375 btck_Block::copy(btck_Block::ref(&block)),
376 btck_BlockTreeEntry::ref(pindex));
384 btck_Block::copy(btck_Block::ref(&block)),
385 btck_BlockTreeEntry::ref(pindex));
390struct ContextOptions {
391 mutable Mutex m_mutex;
392 std::unique_ptr<const CChainParams> m_chainparams
GUARDED_BY(m_mutex);
394 std::shared_ptr<KernelValidationInterface> m_validation_interface
GUARDED_BY(m_mutex);
400 std::unique_ptr<kernel::Context>
m_context;
404 std::unique_ptr<util::SignalInterrupt> m_interrupt;
406 std::unique_ptr<ValidationSignals>
m_signals;
408 std::unique_ptr<const CChainParams> m_chainparams;
410 std::shared_ptr<KernelValidationInterface> m_validation_interface;
412 Context(
const ContextOptions* options,
bool& sane)
414 m_interrupt{
std::make_unique<
util::SignalInterrupt>()}
417 LOCK(options->m_mutex);
418 if (options->m_chainparams) {
419 m_chainparams = std::make_unique<const CChainParams>(*options->m_chainparams);
421 if (options->m_notifications) {
424 if (options->m_validation_interface) {
425 m_signals = std::make_unique<ValidationSignals>(std::make_unique<ImmediateTaskRunner>());
426 m_validation_interface = options->m_validation_interface;
431 if (!m_chainparams) {
436 nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr});
453struct ChainstateManagerOptions {
454 mutable Mutex m_mutex;
457 std::shared_ptr<const Context>
m_context;
461 ChainstateManagerOptions(
const std::shared_ptr<const Context>&
context,
const fs::path& data_dir,
const fs::path& blocks_dir)
463 .chainparams = *
context->m_chainparams,
467 m_blockman_options{
node::BlockManager::Options{
468 .chainparams = *
context->m_chainparams,
469 .blocks_dir = blocks_dir,
472 .path = data_dir /
"blocks" /
"index",
481 std::unique_ptr<ChainstateManager> m_chainman;
482 std::shared_ptr<const Context>
m_context;
484 ChainMan(std::unique_ptr<ChainstateManager> chainman, std::shared_ptr<const Context>
context)
488struct UserDataDeleter {
490 void operator()(
void* user_data)
const
492 if (destroy) destroy(user_data);
496using UserData = std::unique_ptr<void, UserDataDeleter>;
507 void operator()(
const btck_LogEntry* entry)
const { fn(user_data.get(), entry); }
512 std::list<Callback> m_callbacks
GUARDED_BY(m_mutex);
514 std::atomic<size_t> m_callback_count{0};
527 KernelLogger* m_logger;
528 std::list<Callback>::iterator m_it;
531 CallbackHandle(KernelLogger& logger
LIFETIMEBOUND, std::list<Callback>::iterator it)
532 : m_logger{&logger}, m_it{it} {}
533 CallbackHandle(CallbackHandle&& other) noexcept
534 : m_logger{std::exchange(other.m_logger,
nullptr)}, m_it{other.m_it} {}
535 CallbackHandle& operator=(CallbackHandle&&) =
delete;
538 if (m_logger) m_logger->UnregisterCallback(m_it);
547 m_min_level.store(to_util(level), std::memory_order_relaxed);
553 return level >= m_min_level.load(std::memory_order_relaxed) &&
554 m_callback_count.load(std::memory_order_relaxed) > 0;
562 if (ShouldLog(entry.level)) {
568KernelLogger::CallbackHandle KernelLogger::RegisterCallback(
btck_LogCallback fn, UserData user_data)
571 Callback cb{fn, std::move(user_data)};
573 m_callbacks.push_back(std::move(cb));
574 m_callback_count.fetch_add(1, std::memory_order_relaxed);
575 return {*
this, std::prev(m_callbacks.end())};
578void KernelLogger::UnregisterCallback(std::list<Callback>::iterator it)
581 std::list<Callback> dying;
584 dying.splice(dying.begin(), m_callbacks, it);
585 m_callback_count.fetch_sub(1, std::memory_order_relaxed);
594 const auto timestamp_ns{TicksSinceEpoch<std::chrono::nanoseconds>(entry.
timestamp)};
600 .message_len = message.size(),
601 .thread_name = thread_name.data(),
602 .thread_name_len = thread_name.size(),
603 .timestamp_ns = timestamp_ns,
604 .mocktime_s = entry.
mocktime.count(),
605 .file_name = file_name.data(),
606 .file_name_len = file_name.size(),
607 .function_name = function_name.data(),
608 .function_name_len = function_name.size(),
610 .level = to_btck(entry.
level),
615 for (
const auto& callback : m_callbacks) {
617 callback(&btck_entry);
632struct btck_Context : Handle<btck_Context, std::shared_ptr<const Context>> {};
652 assert(raw_transaction !=
nullptr || raw_transaction_len == 0);
654 SpanReader stream{std::span{
reinterpret_cast<const std::byte*
>(raw_transaction), raw_transaction_len}};
663 return btck_Transaction::get(transaction)->vout.size();
668 const CTransaction& tx = *btck_Transaction::get(transaction);
670 return btck_TransactionOutput::ref(&tx.
vout[output_index]);
675 return btck_Transaction::get(transaction)->vin.size();
680 assert(input_index < btck_Transaction::get(transaction)->vin.size());
681 return btck_TransactionInput::ref(&btck_Transaction::get(transaction)->vin[input_index]);
686 return btck_Transaction::get(transaction)->version;
691 return btck_Transaction::get(transaction)->nLockTime;
696 return btck_Txid::ref(&btck_Transaction::get(transaction)->GetHash());
701 return btck_Transaction::get(transaction)->HasWitness() ? 1 : 0;
706 return btck_Wtxid::ref(&btck_Transaction::get(transaction)->GetWitnessHash());
711 return btck_Transaction::copy(transaction);
717 WriterStream ws{writer, user_data};
732 assert(script_pubkey !=
nullptr || script_pubkey_len == 0);
733 auto data = std::span{
reinterpret_cast<const uint8_t*
>(script_pubkey), script_pubkey_len};
734 return btck_ScriptPubkey::create(
data.begin(),
data.end());
739 const auto& script_pubkey{btck_ScriptPubkey::get(script_pubkey_)};
740 return writer(script_pubkey.data(), script_pubkey.size(), user_data);
745 return btck_ScriptPubkey::copy(script_pubkey);
750 delete script_pubkey;
755 return btck_TransactionOutput::create(amount, btck_ScriptPubkey::get(script_pubkey));
760 return btck_TransactionOutput::copy(output);
765 return btck_ScriptPubkey::ref(&btck_TransactionOutput::get(output).scriptPubKey);
770 return btck_TransactionOutput::get(output).nValue;
784 auto txdata{btck_PrecomputedTransactionData::create()};
785 if (spent_outputs_ !=
nullptr && spent_outputs_len > 0) {
786 assert(spent_outputs_len == tx.vin.size());
787 std::vector<CTxOut> spent_outputs;
788 spent_outputs.reserve(spent_outputs_len);
789 for (
size_t i = 0; i < spent_outputs_len; i++) {
790 const CTxOut& tx_out{btck_TransactionOutput::get(spent_outputs_[i])};
791 spent_outputs.push_back(tx_out);
793 btck_PrecomputedTransactionData::get(txdata).Init(tx, std::move(spent_outputs));
795 btck_PrecomputedTransactionData::get(txdata).Init(tx, {});
806 return btck_PrecomputedTransactionData::copy(precomputed_txdata);
811 delete precomputed_txdata;
815 const int64_t amount,
818 const unsigned int input_index,
831 assert(input_index < tx.vin.size());
842 bool result =
VerifyScript(tx.vin[input_index].scriptSig,
843 btck_ScriptPubkey::get(script_pubkey),
844 &tx.vin[input_index].scriptWitness,
848 return result ? 1 : 0;
853 return btck_TransactionInput::copy(input);
858 return btck_TransactionOutPoint::ref(&btck_TransactionInput::get(input).prevout);
863 return btck_TransactionInput::get(input).nSequence;
868 return btck_WitnessStack::ref(&btck_TransactionInput::get(input).scriptWitness);
873 const auto& script_sig{btck_TransactionInput::get(input).scriptSig};
874 return writer(script_sig.data(), script_sig.size(), user_data);
884 return btck_WitnessStack::get(witness_stack).stack.size();
889 const auto& stack{btck_WitnessStack::get(witness_stack).stack};
890 assert(index < stack.size());
891 return writer(stack[index].
data(), stack[index].size(), user_data);
896 return btck_WitnessStack::copy(witness_stack);
901 delete witness_stack;
906 return btck_TransactionOutPoint::copy(out_point);
911 return btck_TransactionOutPoint::get(out_point).n;
916 return btck_Txid::ref(&btck_TransactionOutPoint::get(out_point).hash);
926 return btck_Txid::copy(txid);
931 std::memcpy(output, btck_Txid::get(txid).begin(), 32);
936 return btck_Txid::get(txid1) == btck_Txid::get(txid2);
946 return btck_Wtxid::copy(wtxid);
951 std::memcpy(output, btck_Wtxid::get(wtxid).begin(), 32);
956 return btck_Wtxid::get(wtxid1) == btck_Wtxid::get(wtxid2);
967KernelLogger& GetKernelLogger()
969 static KernelLogger* logger{
new KernelLogger};
991 GetKernelLogger().MaybeLog(entry);
998 GetKernelLogger().SetMinLevel(level);
1006 UserData
data{user_data, {user_data_destroy_callback}};
1007 auto handle{GetKernelLogger().RegisterCallback(callback, std::move(
data))};
1009 return btck_LoggingConnection::create(std::move(handle));
1017 if (!connection)
return;
1024 switch (chain_type) {
1046 assert(challenge !=
nullptr || challenge_len == 0);
1047 const uint8_t* p =
static_cast<const uint8_t*
>(challenge);
1049 .challenge = std::vector<uint8_t>{p, p + challenge_len},
1056 return btck_ChainParameters::copy(chain_parameters);
1061 return btck_ConsensusParams::ref(&btck_ChainParameters::get(chain_parameters).GetConsensus());
1066 delete chain_parameters;
1071 return btck_ContextOptions::create();
1077 LOCK(btck_ContextOptions::get(options).m_mutex);
1078 btck_ContextOptions::get(options).m_chainparams = std::make_unique<const CChainParams>(btck_ChainParameters::get(chain_parameters));
1084 LOCK(btck_ContextOptions::get(options).m_mutex);
1085 btck_ContextOptions::get(options).m_notifications = std::make_shared<KernelNotifications>(notifications);
1090 LOCK(btck_ContextOptions::get(options).m_mutex);
1091 btck_ContextOptions::get(options).m_validation_interface = std::make_shared<KernelValidationInterface>(vi_cbs);
1102 const ContextOptions* opts = options ? &btck_ContextOptions::get(options) :
nullptr;
1103 auto context{std::make_shared<const Context>(opts, sane)};
1105 LogError(
"Kernel context sanity check failed.");
1108 return btck_Context::create(
context);
1113 return btck_Context::copy(
context);
1118 return (*btck_Context::get(
context)->m_interrupt)() ? 0 : -1;
1128 if (!btck_BlockTreeEntry::get(entry).pprev) {
1129 LogInfo(
"Genesis block has no previous.");
1133 return btck_BlockTreeEntry::ref(btck_BlockTreeEntry::get(entry).pprev);
1138 const auto* ancestor{btck_BlockTreeEntry::get(block_tree_entry).GetAncestor(height)};
1140 return btck_BlockTreeEntry::ref(ancestor);
1145 return btck_BlockValidationState::create();
1150 return btck_BlockValidationState::copy(state);
1160 auto& block_validation_state = btck_BlockValidationState::get(block_validation_state_);
1168 auto& block_validation_state = btck_BlockValidationState::get(block_validation_state_);
1169 switch (block_validation_state.GetResult()) {
1194 assert(data_dir !=
nullptr || data_dir_len == 0);
1195 assert(blocks_dir !=
nullptr || blocks_dir_len == 0);
1196 if (data_dir_len == 0 || blocks_dir_len == 0) {
1197 LogError(
"Failed to create chainstate manager options: dir must be non-null and non-empty");
1202 fs::create_directories(abs_data_dir);
1204 fs::create_directories(abs_blocks_dir);
1205 return btck_ChainstateManagerOptions::create(btck_Context::get(
context), abs_data_dir, abs_blocks_dir);
1206 }
catch (
const std::exception& e) {
1207 LogError(
"Failed to create chainstate manager options: %s", e.what());
1214 LOCK(btck_ChainstateManagerOptions::get(opts).m_mutex);
1215 btck_ChainstateManagerOptions::get(opts).m_chainman_options.worker_threads_num = worker_threads;
1220 if (database_cache_bytes < MIN_DBCACHE_BYTES || database_cache_bytes >
MAX_DBCACHE_BYTES) {
1221 LogError(
"Failed to set database cache: size is outside the supported range.");
1225 auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1227 opts.m_db_cache_bytes = database_cache_bytes;
1239 if (wipe_block_tree_db == 1 && wipe_chainstate_db != 1) {
1240 LogError(
"Wiping the block tree db without also wiping the chainstate db is currently unsupported.");
1243 auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1245 opts.m_blockman_options.block_tree_db_params.wipe_data = wipe_block_tree_db == 1;
1246 opts.m_chainstate_load_options.wipe_chainstate_db = wipe_chainstate_db == 1;
1252 int block_tree_db_in_memory)
1254 auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1256 opts.m_blockman_options.block_tree_db_params.memory_only = block_tree_db_in_memory == 1;
1261 int chainstate_db_in_memory)
1263 auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1265 opts.m_chainstate_load_options.coins_db_in_memory = chainstate_db_in_memory == 1;
1271 auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1272 std::unique_ptr<ChainstateManager> chainman;
1275 chainman = std::make_unique<ChainstateManager>(*opts.m_context->m_interrupt, opts.m_chainman_options, opts.m_blockman_options);
1276 }
catch (
const std::exception& e) {
1277 LogError(
"Failed to create chainstate manager: %s", e.what());
1282 const auto chainstate_load_opts{
WITH_LOCK(opts.m_mutex,
return opts.m_chainstate_load_options)};
1285 auto [status, chainstate_err]{
node::LoadChainstate(*chainman, cache_sizes, chainstate_load_opts)};
1287 LogError(
"Failed to load chain state from your data directory: %s", chainstate_err.original);
1292 LogError(
"Failed to verify loaded chain state from your datadir: %s", chainstate_err.original);
1295 if (
auto result = chainman->ActivateBestChains(); !result) {
1299 }
catch (
const std::exception& e) {
1300 LogError(
"Failed to load chainstate: %s", e.what());
1304 return btck_ChainstateManager::create(std::move(chainman), opts.m_context);
1309 auto block_index =
WITH_LOCK(btck_ChainstateManager::get(chainman).m_chainman->GetMutex(),
1310 return btck_ChainstateManager::get(chainman).m_chainman->m_blockman.LookupBlockIndex(btck_BlockHash::get(block_hash)));
1315 return btck_BlockTreeEntry::ref(block_index);
1320 auto& chainman = *btck_ChainstateManager::get(chainstate_manager).m_chainman;
1321 return btck_BlockTreeEntry::ref(
WITH_LOCK(chainman.GetMutex(),
return chainman.m_best_header));
1327 LOCK(btck_ChainstateManager::get(chainman).m_chainman->GetMutex());
1328 for (
const auto& chainstate : btck_ChainstateManager::get(chainman).m_chainman->m_chainstates) {
1329 if (chainstate->CanFlushToDisk()) {
1330 chainstate->ForceFlushStateToDisk();
1331 chainstate->ResetCoinsViews();
1342 std::vector<fs::path> import_files;
1343 import_files.reserve(block_file_paths_data_len);
1344 for (uint32_t i = 0; i < block_file_paths_data_len; i++) {
1345 if (block_file_paths_data[i] !=
nullptr) {
1346 import_files.emplace_back(std::string{block_file_paths_data[i], block_file_paths_lens[i]}.c_str());
1349 auto& chainman_ref{*btck_ChainstateManager::get(chainman).m_chainman};
1352 }
catch (
const std::exception& e) {
1353 LogError(
"Failed to import blocks: %s", e.what());
1361 assert(raw_block !=
nullptr || raw_block_length == 0);
1362 auto block{std::make_shared<CBlock>()};
1364 SpanReader stream{std::span{
reinterpret_cast<const std::byte*
>(raw_block), raw_block_length}};
1373 return btck_Block::create(block);
1378 return btck_Block::copy(block);
1383 auto& state = btck_BlockValidationState::get(validation_state);
1389 const bool result =
CheckBlock(*btck_Block::get(block), state, btck_ConsensusParams::get(consensus_params), check_pow, check_merkle);
1391 return result ? 1 : 0;
1396 return btck_Block::get(block)->vtx.size();
1401 assert(index < btck_Block::get(block)->vtx.size());
1402 return btck_Transaction::ref(&btck_Block::get(block)->vtx[index]);
1407 const auto& block_ptr = btck_Block::get(block);
1408 return btck_BlockHeader::create(
static_cast<const CBlockHeader&
>(*block_ptr));
1414 WriterStream ws{writer, user_data};
1424 return btck_BlockHash::create(btck_Block::get(block)->GetHash());
1434 auto block{std::make_shared<CBlock>()};
1435 if (!btck_ChainstateManager::get(chainman).m_chainman->m_blockman.ReadBlock(*block, btck_BlockTreeEntry::get(entry))) {
1439 return btck_Block::create(block);
1444 return btck_BlockHeader::create(btck_BlockTreeEntry::get(entry).GetBlockHeader());
1449 return btck_BlockTreeEntry::get(entry).nHeight;
1454 return btck_BlockHash::ref(btck_BlockTreeEntry::get(entry).phashBlock);
1459 return &btck_BlockTreeEntry::get(entry1) == &btck_BlockTreeEntry::get(entry2);
1464 return btck_BlockHash::create(std::span<const unsigned char>{block_hash, 32});
1469 return btck_BlockHash::copy(block_hash);
1474 std::memcpy(output, btck_BlockHash::get(block_hash).begin(), 32);
1479 return btck_BlockHash::get(hash1) == btck_BlockHash::get(hash2);
1489 auto block_undo{std::make_shared<CBlockUndo>()};
1490 if (btck_BlockTreeEntry::get(entry).
nHeight < 1) {
1492 return btck_BlockSpentOutputs::create(block_undo);
1494 if (!btck_ChainstateManager::get(chainman).m_chainman->m_blockman.ReadBlockUndo(*block_undo, btck_BlockTreeEntry::get(entry))) {
1495 LogError(
"Failed to read block spent outputs data.");
1498 return btck_BlockSpentOutputs::create(block_undo);
1503 return btck_BlockSpentOutputs::copy(block_spent_outputs);
1508 return btck_BlockSpentOutputs::get(block_spent_outputs)->vtxundo.size();
1513 assert(transaction_index < btck_BlockSpentOutputs::get(block_spent_outputs)->vtxundo.size());
1514 const auto* tx_undo{&btck_BlockSpentOutputs::get(block_spent_outputs)->vtxundo.at(transaction_index)};
1515 return btck_TransactionSpentOutputs::ref(tx_undo);
1520 delete block_spent_outputs;
1525 return btck_TransactionSpentOutputs::copy(transaction_spent_outputs);
1530 return btck_TransactionSpentOutputs::get(transaction_spent_outputs).vprevout.size();
1535 delete transaction_spent_outputs;
1540 assert(coin_index < btck_TransactionSpentOutputs::get(transaction_spent_outputs).vprevout.size());
1541 const Coin* coin{&btck_TransactionSpentOutputs::get(transaction_spent_outputs).vprevout.at(coin_index)};
1542 return btck_Coin::ref(coin);
1547 return btck_Coin::copy(coin);
1552 return btck_Coin::get(coin).nHeight;
1557 return btck_Coin::get(coin).IsCoinBase() ? 1 : 0;
1562 return btck_TransactionOutput::ref(&btck_Coin::get(coin).
out);
1576 auto result = btck_ChainstateManager::get(chainman).m_chainman->ProcessNewBlock(btck_Block::get(block),
true,
true, &new_block);
1578 *_new_block = new_block ? 1 : 0;
1580 return result ? 0 : -1;
1588 auto& chainman = btck_ChainstateManager::get(chainstate_manager).m_chainman;
1590 auto state = btck_BlockValidationState::create();
1591 bool result{chainman->ProcessNewBlockHeaders({&btck_BlockHeader::get(header), 1},
true, btck_BlockValidationState::get(state))};
1592 assert(result == btck_BlockValidationState::get(state).IsValid());
1594 }
catch (
const std::exception& e) {
1595 LogError(
"Failed to process block header: %s", e.what());
1602 return btck_Chain::ref(&
WITH_LOCK(btck_ChainstateManager::get(chainman).m_chainman->GetMutex(),
return btck_ChainstateManager::get(chainman).m_chainman->ActiveChain()));
1608 return btck_Chain::get(chain).Height();
1614 return btck_BlockTreeEntry::ref(btck_Chain::get(chain)[height]);
1620 return btck_Chain::get(chain).Contains(btck_BlockTreeEntry::get(entry)) ? 1 : 0;
1625 assert(raw_block_header !=
nullptr && raw_block_header_len == 80);
1626 auto header{std::make_unique<CBlockHeader>()};
1627 SpanReader stream{std::span{
reinterpret_cast<const std::byte*
>(raw_block_header), raw_block_header_len}};
1632 LogError(
"Block header decode failed.");
1636 return btck_BlockHeader::ref(header.release());
1641 return btck_BlockHeader::copy(header);
1646 return btck_BlockHash::create(btck_BlockHeader::get(header).GetHash());
1651 return btck_BlockHash::ref(&btck_BlockHeader::get(header).hashPrevBlock);
1656 std::memcpy(output, btck_BlockHeader::get(header).hashMerkleRoot.begin(), 32);
1661 return btck_BlockHeader::get(header).nTime;
1666 return btck_BlockHeader::get(header).nBits;
1671 return btck_BlockHeader::get(header).nVersion;
1676 return btck_BlockHeader::get(header).nNonce;
1682 SpanWriter{std::as_writable_bytes(std::span{output, 80})} << btck_BlockHeader::get(header);
1696 const auto& state = btck_TxValidationState::get(state_);
1704 return btck_TxValidationState::create();
1709 switch (btck_TxValidationState::get(state_).GetResult()) {
1734 auto& state = btck_TxValidationState::get(validation_state);
1742 constexpr int64_t max_time{std::numeric_limits<uint32_t>::max()};
1743 if (timestamp < 0 || timestamp > max_time) {
int btck_block_to_bytes(const btck_Block *block, btck_WriteBytes writer, void *user_data)
btck_ScriptPubkey * btck_script_pubkey_copy(const btck_ScriptPubkey *script_pubkey)
Copy a script pubkey.
btck_BlockHash * btck_block_hash_copy(const btck_BlockHash *block_hash)
Copy a block hash.
void btck_txid_destroy(btck_Txid *txid)
Destroy the txid.
int btck_script_pubkey_to_bytes(const btck_ScriptPubkey *script_pubkey_, btck_WriteBytes writer, void *user_data)
void btck_script_pubkey_destroy(btck_ScriptPubkey *script_pubkey)
Destroy the script pubkey.
btck_TxValidationResult btck_tx_validation_state_get_tx_validation_result(const btck_TxValidationState *state_)
Returns the validation result from an opaque btck_TxValidationState pointer.
btck_Wtxid * btck_wtxid_copy(const btck_Wtxid *wtxid)
Copy a wtxid.
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)
Triggers the start of a reindex if the wipe options were previously set for the chainstate manager.
const btck_Coin * btck_transaction_spent_outputs_get_coin_at(const btck_TransactionSpentOutputs *transaction_spent_outputs, size_t coin_index)
Returns a coin contained in the transaction spent outputs at a certain index.
const btck_TransactionInput * btck_transaction_get_input_at(const btck_Transaction *transaction, size_t input_index)
Get the transaction input at the provided index.
uint32_t btck_coin_confirmation_height(const btck_Coin *coin)
Returns the block height where the transaction that created this coin was included in.
void btck_context_destroy(btck_Context *context)
Destroy the context.
void btck_context_options_set_notifications(btck_ContextOptions *options, btck_NotificationInterfaceCallbacks notifications)
Set the kernel notifications for the context options.
btck_ContextOptions * btck_context_options_create()
Creates an empty context options.
void btck_transaction_destroy(btck_Transaction *transaction)
Destroy the transaction.
btck_PrecomputedTransactionData * btck_precomputed_transaction_data_create(const btck_Transaction *tx_to, const btck_TransactionOutput **spent_outputs_, size_t spent_outputs_len)
Create precomputed transaction data for script verification.
const btck_BlockTreeEntry * btck_block_tree_entry_get_ancestor(const btck_BlockTreeEntry *block_tree_entry, int32_t height)
Return the ancestor of a btck_BlockTreeEntry at the given height.
int64_t btck_transaction_output_get_amount(const btck_TransactionOutput *output)
Get the amount in the output.
void btck_chainstate_manager_options_update_chainstate_db_in_memory(btck_ChainstateManagerOptions *chainman_opts, int chainstate_db_in_memory)
Sets chainstate db in memory in the options.
uint32_t btck_block_header_get_nonce(const btck_BlockHeader *header)
Get the nonce from btck_BlockHeader.
const btck_Txid * btck_transaction_out_point_get_txid(const btck_TransactionOutPoint *out_point)
Get the txid from the transaction out point.
btck_BlockValidationState * btck_block_validation_state_create()
Create a new btck_BlockValidationState.
void btck_transaction_spent_outputs_destroy(btck_TransactionSpentOutputs *transaction_spent_outputs)
Destroy the transaction spent outputs.
const btck_BlockTreeEntry * btck_block_tree_entry_get_previous(const btck_BlockTreeEntry *entry)
Returns the previous block tree entry in the tree, or null if the current block tree entry is the gen...
void btck_chain_parameters_destroy(btck_ChainParameters *chain_parameters)
Destroy the chain parameters.
size_t btck_transaction_count_outputs(const btck_Transaction *transaction)
Get the number of outputs of a transaction.
int btck_witness_stack_get_item_at(const btck_WitnessStack *witness_stack, size_t index, btck_WriteBytes writer, void *user_data)
size_t btck_witness_stack_count_items(const btck_WitnessStack *witness_stack)
Return the number of items in a witness stack.
void btck_block_destroy(btck_Block *block)
Destroy the block.
btck_ScriptPubkey * btck_script_pubkey_create(const void *script_pubkey, size_t script_pubkey_len)
Create a script pubkey from serialized data.
btck_Context * btck_context_copy(const btck_Context *context)
Copy the context.
const btck_BlockTreeEntry * btck_chainstate_manager_get_best_entry(const btck_ChainstateManager *chainstate_manager)
Get the btck_BlockTreeEntry whose associated btck_BlockHeader has the most known cumulative proof of ...
btck_ChainParameters * btck_chain_parameters_create(const btck_ChainType chain_type)
Creates a chain parameters struct with default parameters based on the passed in chain type.
int32_t btck_block_header_get_version(const btck_BlockHeader *header)
Get the version from btck_BlockHeader.
int btck_set_mock_time(int64_t timestamp)
Override the current time with a fixed timestamp for testing.
btck_ValidationMode btck_block_validation_state_get_validation_mode(const btck_BlockValidationState *block_validation_state_)
Returns the validation mode from an opaque btck_BlockValidationState pointer.
btck_Block * btck_block_create(const void *raw_block, size_t raw_block_length)
Parse a serialized raw block into a new block object.
void btck_chainstate_manager_options_update_block_tree_db_in_memory(btck_ChainstateManagerOptions *chainman_opts, int block_tree_db_in_memory)
Sets block tree db in memory in the options.
static const kernel::Context btck_context_static
void btck_witness_stack_destroy(btck_WitnessStack *witness_stack)
Destroy the witness stack.
btck_ChainParameters * btck_chain_parameters_copy(const btck_ChainParameters *chain_parameters)
Copy the chain parameters.
int btck_block_tree_entry_equals(const btck_BlockTreeEntry *entry1, const btck_BlockTreeEntry *entry2)
uint32_t btck_block_header_get_bits(const btck_BlockHeader *header)
Get the nBits difficulty target from btck_BlockHeader.
const btck_Wtxid * btck_transaction_get_wtxid(const btck_Transaction *transaction)
Get the wtxid of a transaction.
int32_t btck_chain_get_height(const btck_Chain *chain)
Return the height of the tip of the chain.
btck_BlockHeader * btck_block_get_header(const btck_Block *block)
Get the btck_BlockHeader from the block.
size_t btck_block_count_transactions(const btck_Block *block)
Count the number of transactions contained in a block.
void btck_context_options_destroy(btck_ContextOptions *options)
Destroy the context options.
void btck_logging_set_min_level(btck_LogLevel level)
Set the minimum log level.
void btck_block_header_get_merkle_root(const btck_BlockHeader *header, unsigned char output[32])
btck_LoggingConnection * btck_logging_connection_create(btck_LogCallback callback, void *user_data, btck_DestroyCallback user_data_destroy_callback)
Start logging messages through the provided callback.
btck_BlockHeader * btck_block_header_copy(const btck_BlockHeader *header)
Copy a btck_BlockHeader.
int btck_script_pubkey_verify(const btck_ScriptPubkey *script_pubkey, const int64_t amount, const btck_Transaction *tx_to, const btck_PrecomputedTransactionData *precomputed_txdata, const unsigned int input_index, const btck_ScriptVerificationFlags flags, btck_ScriptVerifyStatus *status)
btck_BlockSpentOutputs * btck_block_spent_outputs_copy(const btck_BlockSpentOutputs *block_spent_outputs)
Copy a block's spent outputs.
void btck_precomputed_transaction_data_destroy(btck_PrecomputedTransactionData *precomputed_txdata)
Destroy the precomputed transaction data.
const btck_TransactionOutPoint * btck_transaction_input_get_out_point(const btck_TransactionInput *input)
Get the transaction out point.
btck_BlockSpentOutputs * btck_block_spent_outputs_read(const btck_ChainstateManager *chainman, const btck_BlockTreeEntry *entry)
void btck_tx_validation_state_destroy(btck_TxValidationState *state)
Destroy the btck_TxValidationState.
btck_ChainstateManager * btck_chainstate_manager_create(const btck_ChainstateManagerOptions *chainman_opts)
Create a chainstate manager.
int btck_transaction_check(const btck_Transaction *tx, btck_TxValidationState *validation_state)
void btck_block_validation_state_destroy(btck_BlockValidationState *state)
Destroy the btck_BlockValidationState.
btck_BlockHash * btck_block_get_hash(const btck_Block *block)
Calculate and return the hash of a block.
btck_Txid * btck_txid_copy(const btck_Txid *txid)
Copy a txid.
const btck_TransactionSpentOutputs * btck_block_spent_outputs_get_transaction_spent_outputs_at(const btck_BlockSpentOutputs *block_spent_outputs, size_t transaction_index)
Returns a transaction spent outputs contained in the block spent outputs at a certain index.
btck_Context * btck_context_create(const btck_ContextOptions *options)
Create a new kernel context.
const btck_TransactionOutput * btck_coin_get_output(const btck_Coin *coin)
Return the transaction output of a coin.
void btck_transaction_out_point_destroy(btck_TransactionOutPoint *out_point)
Destroy the transaction out point.
uint32_t btck_transaction_get_locktime(const btck_Transaction *transaction)
Get a transaction's nLockTime value.
int btck_coin_is_coinbase(const btck_Coin *coin)
Returns whether the containing transaction was a coinbase.
int btck_wtxid_equals(const btck_Wtxid *wtxid1, const btck_Wtxid *wtxid2)
void btck_txid_to_bytes(const btck_Txid *txid, unsigned char output[32])
void btck_block_hash_destroy(btck_BlockHash *hash)
Destroy the block hash.
int btck_chainstate_manager_options_set_wipe_dbs(btck_ChainstateManagerOptions *chainman_opts, int wipe_block_tree_db, int wipe_chainstate_db)
Sets wipe db in the options.
uint32_t btck_transaction_get_version(const btck_Transaction *transaction)
Get a transaction's version.
btck_BlockHeader * btck_block_tree_entry_get_block_header(const btck_BlockTreeEntry *entry)
Return the btck_BlockHeader associated with this entry.
int btck_context_interrupt(btck_Context *context)
Interrupt can be used to halt long-running validation functions like when reindexing,...
const btck_ConsensusParams * btck_chain_parameters_get_consensus_params(const btck_ChainParameters *chain_parameters)
Get btck_ConsensusParams from btck_ChainParameters.
void btck_transaction_input_destroy(btck_TransactionInput *input)
Destroy the transaction input.
const btck_TransactionOutput * btck_transaction_get_output_at(const btck_Transaction *transaction, size_t output_index)
Get the transaction outputs at the provided index.
const btck_BlockTreeEntry * btck_chain_get_by_height(const btck_Chain *chain, int32_t height)
Retrieve a block tree entry by its height in the currently active chain.
void btck_coin_destroy(btck_Coin *coin)
Destroy the coin.
void btck_context_options_set_chainparams(btck_ContextOptions *options, const btck_ChainParameters *chain_parameters)
btck_WitnessStack * btck_witness_stack_copy(const btck_WitnessStack *witness_stack)
Copy a witness stack.
int btck_block_header_to_bytes(const btck_BlockHeader *header, unsigned char output[80])
int btck_chainstate_manager_options_set_database_cache_bytes(btck_ChainstateManagerOptions *chainman_opts, uint64_t database_cache_bytes)
Set the total database cache used by the chainstate manager.
const btck_WitnessStack * btck_transaction_input_get_witness_stack(const btck_TransactionInput *input)
Get the witness stack of a transaction input.
btck_BlockHeader * btck_block_header_create(const void *raw_block_header, size_t raw_block_header_len)
Create a btck_BlockHeader from serialized data.
uint32_t btck_block_header_get_timestamp(const btck_BlockHeader *header)
Get the timestamp from btck_BlockHeader.
btck_ChainParameters * btck_chain_parameters_create_signet(const void *challenge, size_t challenge_len)
Create a signet chain parameters struct with a user-provided challenge.
void btck_block_header_destroy(btck_BlockHeader *header)
Destroy the btck_BlockHeader.
btck_PrecomputedTransactionData * btck_precomputed_transaction_data_copy(const btck_PrecomputedTransactionData *precomputed_txdata)
Copy precomputed transaction data.
btck_BlockHash * btck_block_hash_create(const unsigned char block_hash[32])
Create a block hash from its raw data.
btck_BlockHash * btck_block_header_get_hash(const btck_BlockHeader *header)
Get the btck_BlockHash.
const TranslateFn G_TRANSLATION_FUN
btck_ValidationMode btck_tx_validation_state_get_validation_mode(const btck_TxValidationState *state_)
Returns the validation mode from an opaque btck_TxValidationState pointer.
void btck_wtxid_to_bytes(const btck_Wtxid *wtxid, unsigned char output[32])
int btck_transaction_input_get_script_sig(const btck_TransactionInput *input, btck_WriteBytes writer, void *user_data)
int btck_transaction_has_witness(const btck_Transaction *transaction)
Check whether a transaction has witness data.
void btck_context_options_set_validation_interface(btck_ContextOptions *options, btck_ValidationInterfaceCallbacks vi_cbs)
Set the validation interface callbacks for the context options.
uint32_t btck_transaction_out_point_get_index(const btck_TransactionOutPoint *out_point)
Get the output position from the transaction out point.
const btck_BlockHash * btck_block_header_get_prev_hash(const btck_BlockHeader *header)
Get the previous btck_BlockHash from btck_BlockHeader.
btck_Block * btck_block_read(const btck_ChainstateManager *chainman, const btck_BlockTreeEntry *entry)
const btck_Txid * btck_transaction_get_txid(const btck_Transaction *transaction)
Get the txid of a transaction.
btck_TransactionOutPoint * btck_transaction_out_point_copy(const btck_TransactionOutPoint *out_point)
Copy a transaction out point.
btck_BlockValidationState * btck_chainstate_manager_process_block_header(btck_ChainstateManager *chainstate_manager, const btck_BlockHeader *header)
btck_TransactionInput * btck_transaction_input_copy(const btck_TransactionInput *input)
Copy a transaction input.
int btck_chain_contains(const btck_Chain *chain, const btck_BlockTreeEntry *entry)
const btck_BlockTreeEntry * btck_chainstate_manager_get_block_tree_entry_by_hash(const btck_ChainstateManager *chainman, const btck_BlockHash *block_hash)
void btck_wtxid_destroy(btck_Wtxid *wtxid)
Destroy the wtxid.
size_t btck_block_spent_outputs_count(const btck_BlockSpentOutputs *block_spent_outputs)
Returns the number of transaction spent outputs whose data is contained in block spent outputs.
btck_TransactionOutput * btck_transaction_output_copy(const btck_TransactionOutput *output)
Copy a transaction output.
int btck_block_hash_equals(const btck_BlockHash *hash1, const btck_BlockHash *hash2)
void btck_logging_connection_destroy(btck_LoggingConnection *connection)
Stop logging and destroy the logging connection.
btck_TransactionSpentOutputs * btck_transaction_spent_outputs_copy(const btck_TransactionSpentOutputs *transaction_spent_outputs)
Copy a transaction's spent outputs.
int32_t btck_block_tree_entry_get_height(const btck_BlockTreeEntry *entry)
Return the height of a certain block tree entry.
void btck_block_spent_outputs_destroy(btck_BlockSpentOutputs *block_spent_outputs)
Destroy the block spent outputs.
const btck_ScriptPubkey * btck_transaction_output_get_script_pubkey(const btck_TransactionOutput *output)
Get the script pubkey of the output.
int btck_chainstate_manager_process_block(btck_ChainstateManager *chainman, const btck_Block *block, int *_new_block)
size_t btck_transaction_count_inputs(const btck_Transaction *transaction)
Get the number of inputs of a transaction.
int btck_block_check(const btck_Block *block, const btck_ConsensusParams *consensus_params, btck_BlockCheckFlags flags, btck_BlockValidationState *validation_state)
int btck_txid_equals(const btck_Txid *txid1, const btck_Txid *txid2)
btck_Block * btck_block_copy(const btck_Block *block)
Copy a block.
void btck_chainstate_manager_destroy(btck_ChainstateManager *chainman)
Destroy the chainstate manager.
void btck_chainstate_manager_options_destroy(btck_ChainstateManagerOptions *options)
Destroy the chainstate manager options.
btck_Transaction * btck_transaction_create(const void *raw_transaction, size_t raw_transaction_len)
Create a new transaction from the serialized data.
btck_Coin * btck_coin_copy(const btck_Coin *coin)
Copy a coin.
const btck_BlockHash * btck_block_tree_entry_get_block_hash(const btck_BlockTreeEntry *entry)
Return the block hash associated with a block tree entry.
void btck_chainstate_manager_options_set_worker_threads_num(btck_ChainstateManagerOptions *opts, int worker_threads)
Set the number of available worker threads used during validation.
int btck_transaction_to_bytes(const btck_Transaction *transaction, btck_WriteBytes writer, void *user_data)
btck_TransactionOutput * btck_transaction_output_create(const btck_ScriptPubkey *script_pubkey, int64_t amount)
Create a transaction output from a script pubkey and an amount.
btck_Transaction * btck_transaction_copy(const btck_Transaction *transaction)
Copy a transaction.
btck_TxValidationState * btck_tx_validation_state_create()
Create a new btck_TxValidationState.
const btck_Transaction * btck_block_get_transaction_at(const btck_Block *block, size_t index)
Get the transaction at the provided index.
const btck_Chain * btck_chainstate_manager_get_active_chain(const btck_ChainstateManager *chainman)
Returns the best known currently active chain.
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)
Create options for the chainstate manager.
btck_BlockValidationResult btck_block_validation_state_get_block_validation_result(const btck_BlockValidationState *block_validation_state_)
Returns the validation result from an opaque btck_BlockValidationState pointer.
btck_BlockValidationState * btck_block_validation_state_copy(const btck_BlockValidationState *state)
Copies the btck_BlockValidationState.
void btck_block_hash_to_bytes(const btck_BlockHash *block_hash, unsigned char output[32])
uint32_t btck_transaction_input_get_sequence(const btck_TransactionInput *input)
Get a transaction input's nSequence value.
void btck_transaction_output_destroy(btck_TransactionOutput *output)
Destroy the transaction output.
size_t btck_transaction_spent_outputs_count(const btck_TransactionSpentOutputs *transaction_spent_outputs)
Returns the number of previous transaction outputs contained in the transaction spent outputs data.
#define btck_ChainType_REGTEST
uint8_t btck_LogLevel
The severity of a log statement.
#define btck_TxValidationResult_NOT_STANDARD
otherwise didn't meet local policy rules
#define btck_TxValidationResult_CONFLICT
tx already in mempool or conflicts with a tx in the chain
#define btck_LogLevel_WARNING
int(* btck_WriteBytes)(const void *bytes, size_t size, void *userdata)
Function signature for serializing data.
#define btck_TxValidationResult_RECONSIDERABLE
fails some policy, but might be acceptable if submitted in a (different) package
uint32_t btck_TxValidationResult
Indicates the reason why a transaction failed validation.
#define btck_ChainType_MAINNET
#define btck_BlockValidationResult_HEADER_LOW_WORK
the block header may be on a too-little-work chain
#define btck_Warning_UNKNOWN_NEW_RULES_ACTIVATED
#define btck_TxValidationResult_MISSING_INPUTS
transaction was missing some of its inputs
#define btck_BlockValidationResult_INVALID_PREV
A block this one builds on is invalid.
#define btck_BlockCheckFlags_MERKLE
verify merkle root (and mutation detection)
#define btck_LogCategory_MEMPOOL
#define btck_TxValidationResult_UNKNOWN
transaction was not validated because package failed
#define btck_LogLevel_TRACE
#define btck_ChainType_TESTNET
#define btck_SynchronizationState_INIT_REINDEX
#define btck_ScriptVerifyStatus_ERROR_INVALID_FLAGS_COMBINATION
The flags were combined in an invalid way.
uint32_t btck_BlockValidationResult
A granular "reason" why a block was invalid.
#define btck_LogCategory_BENCH
uint8_t btck_ValidationMode
Whether a validated data structure is valid, invalid, or an error was encountered during processing.
#define btck_ScriptVerificationFlags_ALL
void(* btck_LogCallback)(void *user_data, const btck_LogEntry *entry)
Callback function types.
#define btck_LogCategory_LOCK
#define btck_LogCategory_PRUNE
uint8_t btck_SynchronizationState
Current sync state passed to tip changed callbacks.
#define btck_ChainType_TESTNET_4
#define btck_LogCategory_COINDB
#define btck_TxValidationResult_NO_MEMPOOL
this node does not have a mempool so can't validate the transaction
#define btck_ScriptVerificationFlags_TAPROOT
enable TAPROOT (BIPs 341 & 342)
#define btck_ScriptVerifyStatus_ERROR_SPENT_OUTPUTS_REQUIRED
The taproot flag was set, so valid spent_outputs have to be provided.
#define btck_BlockCheckFlags_POW
run CheckProofOfWork via CheckBlockHeader
void(* btck_DestroyCallback)(void *user_data)
Function signature for freeing user data.
uint32_t btck_ScriptVerificationFlags
Script verification flags that may be composed with each other.
#define btck_LogCategory_VALIDATION
#define btck_LogCategory_REINDEX
#define btck_LogLevel_DEBUG
#define btck_ScriptVerifyStatus_OK
#define btck_TxValidationResult_WITNESS_STRIPPED
transaction is missing a witness
#define btck_LogCategory_RAND
#define btck_TxValidationResult_INPUTS_NOT_STANDARD
inputs (covered by txid) failed policy rules
#define btck_BlockValidationResult_CONSENSUS
invalid by consensus rules (excluding any below reasons)
#define btck_BlockValidationResult_UNSET
initial value. Block has not yet been rejected
#define btck_TxValidationResult_UNSET
initial value. Tx has not yet been rejected
#define btck_SynchronizationState_POST_INIT
#define btck_BlockValidationResult_MISSING_PREV
We don't have the previous block the checked one is built on.
uint8_t btck_ScriptVerifyStatus
A collection of status codes that may be issued by the script verify function.
#define btck_ValidationMode_INTERNAL_ERROR
#define btck_TxValidationResult_WITNESS_MUTATED
witness may have been malleated or is prior to SegWit activation
uint8_t btck_LogCategory
A collection of logging categories that may be encountered by kernel code.
#define btck_ValidationMode_INVALID
#define btck_ChainType_SIGNET
#define btck_TxValidationResult_CONSENSUS
invalid by consensus rules
uint32_t btck_BlockCheckFlags
Bitflags to control context-free block checks (optional).
#define btck_BlockValidationResult_INVALID_HEADER
invalid proof of work or time too old
uint8_t btck_Warning
Possible warning types issued by validation.
#define btck_LogCategory_NONE
Not tied to a specific category, e.g. most INFO, WARNING and ERROR entries.
#define btck_BlockValidationResult_TIME_FUTURE
block timestamp was > 2 hours in the future (or our clock is bad)
#define btck_LogCategory_LEVELDB
#define btck_LogLevel_ERROR
#define btck_BlockValidationResult_CACHED_INVALID
this block was cached as being invalid and we didn't store the reason why
#define btck_Warning_LARGE_WORK_INVALID_CHAIN
#define btck_LogLevel_INFO
#define btck_TxValidationResult_PREMATURE_SPEND
transaction spends a coinbase too early, or violates locktime/sequence locks
#define btck_LogCategory_BLOCKSTORAGE
#define btck_ValidationMode_VALID
#define btck_LogCategory_KERNEL
#define btck_BlockValidationResult_MUTATED
the block's data didn't match the data committed to by the PoW
#define btck_LogCategory_TXPACKAGES
#define btck_TxValidationResult_MEMPOOL_POLICY
violated mempool's fee/size/descendant/RBF/etc limits
#define btck_SynchronizationState_INIT_DOWNLOAD
const CChainParams & Params()
Return the currently selected parameters.
#define Assume(val)
Assume is the identity function.
The block chain is a tree shaped structure starting with the genesis block at the root,...
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
static std::unique_ptr< const CChainParams > TestNet4()
static std::unique_ptr< const CChainParams > Main()
static std::unique_ptr< const CChainParams > TestNet()
static std::unique_ptr< const CChainParams > SigNet()
static std::unique_ptr< const CChainParams > RegTest()
The basic transaction that is broadcasted on the network and contained in blocks.
const std::vector< CTxOut > vout
An output of a transaction.
Implement this to subscribe to events generated in validation and mempool.
virtual void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr< const CBlock > &block)
Notifies listeners that a block which builds directly on our current tip has been received and connec...
virtual void BlockChecked(const std::shared_ptr< const CBlock > &, const BlockValidationState &)
Notifies listeners of a block validation result.
virtual void BlockDisconnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being disconnected Provides the block that was disconnected.
virtual void BlockConnected(const kernel::ChainstateRole &role, const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being connected.
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
std::string_view function_name_short() const
std::string_view file_name() const
std::uint_least32_t line() const
Minimal stream for reading from an existing byte array by std::span.
Minimal stream for writing to an existing span of bytes.
void RegisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Register subscriber.
void UnregisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Unregister subscriber.
A base class defining functions for notifying about certain kernel events.
virtual void headerTip(SynchronizationState state, int64_t height, int64_t timestamp, bool presync)
virtual void fatalError(const bilingual_str &message)
The fatal error notification is sent to notify the user when an error occurs in kernel code that can'...
virtual void warningSet(Warning id, const bilingual_str &message)
virtual void progress(const bilingual_str &title, int progress_percent, bool resume_possible)
virtual InterruptResult blockTip(SynchronizationState state, const CBlockIndex &index, double verification_progress)
virtual void flushError(const bilingual_str &message)
The flush error notification is sent to notify the user that an error occurred while flushing block d...
virtual void warningUnset(Warning id)
static constexpr script_verify_flags from_int(value_type f)
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
@ BLOCK_HEADER_LOW_WORK
the block header may be on a too-little-work chain
@ BLOCK_INVALID_HEADER
invalid proof of work or time too old
@ BLOCK_CACHED_INVALID
this block was cached as being invalid and we didn't store the reason why
@ BLOCK_CONSENSUS
invalid by consensus rules (excluding any below reasons)
@ BLOCK_MISSING_PREV
We don't have the previous block the checked one is built on.
@ BLOCK_INVALID_PREV
A block this one builds on is invalid.
@ BLOCK_MUTATED
the block's data didn't match the data committed to by the PoW
@ BLOCK_TIME_FUTURE
block timestamp was > 2 hours in the future (or our clock is bad)
@ BLOCK_RESULT_UNSET
initial value. Block has not yet been rejected
@ TX_MISSING_INPUTS
transaction was missing some of its inputs
@ TX_MEMPOOL_POLICY
violated mempool's fee/size/descendant/RBF/etc limits
@ TX_UNKNOWN
transaction was not validated because package failed
@ TX_PREMATURE_SPEND
transaction spends a coinbase too early, or violates locktime/sequence locks
@ TX_INPUTS_NOT_STANDARD
inputs (covered by txid) failed policy rules
@ TX_WITNESS_STRIPPED
Transaction is missing a witness.
@ TX_CONFLICT
Tx already in mempool or conflicts with a tx in the chain (if it conflicts with another tx in mempool...
@ TX_NOT_STANDARD
otherwise didn't meet our local policy rules
@ TX_WITNESS_MUTATED
Transaction might have a witness prior to SegWit activation, or witness may have been malleated (whic...
@ TX_NO_MEMPOOL
this node does not have a mempool so can't validate the transaction
@ TX_RESULT_UNSET
initial value. Tx has not yet been rejected
@ TX_CONSENSUS
invalid by consensus rules
@ TX_RECONSIDERABLE
fails some policy, but might be acceptable if submitted in a (different) package
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
static path absolute(const path &p)
static path PathFromString(const std::string &string)
Convert byte string to path object.
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, script_verify_flags flags, const BaseSignatureChecker &checker, ScriptError *serror)
@ FAIL
Just act as if the signature was invalid.
@ SCRIPT_VERIFY_CLEANSTACK
constexpr uint64_t MAX_DBCACHE_BYTES
Maximum total database cache on current architecture (bytes)
constexpr uint64_t DEFAULT_KERNEL_CACHE
Suggested default amount of cache reserved for the kernel (bytes)
#define LogDebug(category,...)
Transaction validation functions.
std::ostream & operator<<(std::ostream &os, BigO const &bigO)
std::variant< std::monostate, Interrupted > InterruptResult
Simple result type for functions that need to propagate an interrupt status and don't have other retu...
@ UNKNOWN_NEW_RULES_ACTIVATED
@ LARGE_WORK_INVALID_CHAIN
util::Result< void > SanityChecks(const Context &)
Ensure a usable environment with all necessary library support.
ChainstateLoadResult LoadChainstate(ChainstateManager &chainman, const CacheSizes &cache_sizes, const ChainstateLoadOptions &options)
ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager &chainman, const ChainstateLoadOptions &options)
void ImportBlocks(ChainstateManager &chainman, std::span< const fs::path > import_paths)
void Log(Entry entry)
Send message to be logged.
bool ShouldDebugLog(Category)
Return whether messages with specified category should be debug logged.
bool ShouldTraceLog(Category)
Return whether messages with specified category should be trace logged.
uint64_t Category
Opaque to util::log; interpreted by consumers (e.g., BCLog::LogFlags).
bilingual_str ErrorString(const Result< T > &result)
std::string_view RemoveSuffixView(std::string_view str LIFETIMEBOUND, std::string_view suffix)
ValidationSignals & m_signals
std::shared_ptr< Chain::Notifications > m_notifications
constexpr TransactionSerParams TX_WITH_WITNESS
void Serialize(Stream &, V)=delete
constexpr deserialize_type deserialize
SigNetOptions holds configurations for creating a signet CChainParams.
Application-specific storage settings.
A log entry passed to the logging callback.
const char * message
Log message text.
A struct for holding the kernel notification callbacks.
btck_NotifyWarningUnset warning_unset
A previous condition leading to the issuance of a warning is no longer given.
btck_NotifyBlockTip block_tip
The chain's tip was updated to the provided block entry.
btck_NotifyWarningSet warning_set
A warning issued by the kernel library during validation.
btck_NotifyFlushError flush_error
An error encountered when flushing data to disk.
btck_NotifyProgress progress
Reports on current block synchronization progress.
btck_NotifyFatalError fatal_error
An unrecoverable system error encountered by the library.
btck_DestroyCallback user_data_destroy
Frees the provided user data structure.
void * user_data
Holds a user-defined opaque structure that is passed to the notification callbacks.
btck_NotifyHeaderTip header_tip
A new best block header was added.
Holds the validation interface callbacks.
btck_DestroyCallback user_data_destroy
Frees the provided user data structure.
btck_ValidationInterfaceBlockConnected block_connected
Called when a block is valid and has now been connected to the best chain.
btck_ValidationInterfaceBlockChecked block_checked
Called when a new block has been fully validated.
btck_ValidationInterfaceBlockDisconnected block_disconnected
Called during a re-org when a block has been removed from the best chain.
void * user_data
Holds a user-defined opaque structure that is passed to the validation interface callbacks.
btck_ValidationInterfacePoWValidBlock pow_valid_block
Called when a new block extends the header chain and has a valid transaction and segwit merkle root.
An options struct for BlockManager, more ergonomically referred to as BlockManager::Options due to th...
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
Information about chainstate that notifications are sent from.
Context struct holding the kernel library's logically global state, and passed to external libbitcoin...
SourceLocation source_loc
SystemClock::time_point timestamp
std::chrono::seconds mocktime
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
This header provides an interface and simple implementation for a task runner.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
std::function< std::string(const char *)> TranslateFn
Translate a message to the native language of the user.
bool CheckTransaction(const CTransaction &tx, TxValidationState &state)
void SetMockTime(std::chrono::time_point< NodeClock, std::chrono::seconds > mock)
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
Functions for validating blocks and updating the block tree.
SynchronizationState
Current sync state passed to tip changed callbacks.