Bitcoin Core 31.99.0
P2P Digital Currency
bitcoinkernel.cpp
Go to the documentation of this file.
1// Copyright (c) 2022-present The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#define BITCOINKERNEL_BUILD
6
8
9#include <chain.h>
10#include <coins.h>
11#include <consensus/tx_check.h>
13#include <dbwrapper.h>
14#include <kernel/caches.h>
15#include <kernel/chainparams.h>
16#include <kernel/checks.h>
17#include <kernel/context.h>
19#include <kernel/warning.h>
20#include <logging.h>
21#include <node/blockstorage.h>
22#include <node/chainstate.h>
23#include <primitives/block.h>
25#include <script/interpreter.h>
26#include <script/script.h>
27#include <script/verify_flags.h>
28#include <serialize.h>
29#include <streams.h>
30#include <sync.h>
31#include <uint256.h>
32#include <undo.h>
33#include <util/check.h>
34#include <util/fs.h>
35#include <util/result.h>
37#include <util/task_runner.h>
38#include <util/translation.h>
39#include <validation.h>
40#include <validationinterface.h>
41
42#include <cstddef>
43#include <cstring>
44#include <exception>
45#include <functional>
46#include <list>
47#include <memory>
48#include <optional>
49#include <span>
50#include <stdexcept>
51#include <string>
52#include <tuple>
53#include <utility>
54#include <vector>
55
56namespace Consensus {
57struct Params;
58} // namespace Consensus
59
62
63// Define G_TRANSLATION_FUN symbol in libbitcoinkernel library so users of the
64// library aren't required to export this symbol
65extern const TranslateFn G_TRANSLATION_FUN{nullptr};
66
68
69namespace {
70
71bool is_valid_flag_combination(script_verify_flags flags)
72{
74 if (flags & SCRIPT_VERIFY_WITNESS && ~flags & SCRIPT_VERIFY_P2SH) return false;
75 return true;
76}
77
78class WriterStream
79{
80private:
81 btck_WriteBytes m_writer;
82 void* m_user_data;
83
84public:
85 WriterStream(btck_WriteBytes writer, void* user_data)
86 : m_writer{writer}, m_user_data{user_data} {}
87
88 //
89 // Stream subset
90 //
91 void write(std::span<const std::byte> src)
92 {
93 if (m_writer(src.data(), src.size(), m_user_data) != 0) {
94 throw std::runtime_error("Failed to write serialization data");
95 }
96 }
97
98 template <typename T>
99 WriterStream& operator<<(const T& obj)
100 {
101 ::Serialize(*this, obj);
102 return *this;
103 }
104};
105
106template <typename C, typename CPP>
107struct Handle {
108 static C* ref(CPP* cpp_type)
109 {
110 return reinterpret_cast<C*>(cpp_type);
111 }
112
113 static const C* ref(const CPP* cpp_type)
114 {
115 return reinterpret_cast<const C*>(cpp_type);
116 }
117
118 template <typename... Args>
119 static C* create(Args&&... args)
120 {
121 auto cpp_obj{std::make_unique<CPP>(std::forward<Args>(args)...)};
122 return ref(cpp_obj.release());
123 }
124
125 static C* copy(const C* ptr)
126 {
127 auto cpp_obj{std::make_unique<CPP>(get(ptr))};
128 return ref(cpp_obj.release());
129 }
130
131 static const CPP& get(const C* ptr)
132 {
133 return *reinterpret_cast<const CPP*>(ptr);
134 }
135
136 static CPP& get(C* ptr)
137 {
138 return *reinterpret_cast<CPP*>(ptr);
139 }
140
141 static void operator delete(void* ptr)
142 {
143 delete reinterpret_cast<CPP*>(ptr);
144 }
145};
146
147} // namespace
148
149struct btck_BlockTreeEntry: Handle<btck_BlockTreeEntry, CBlockIndex> {};
150struct btck_Block : Handle<btck_Block, std::shared_ptr<const CBlock>> {};
151struct btck_BlockValidationState : Handle<btck_BlockValidationState, BlockValidationState> {};
152struct btck_TxValidationState : Handle<btck_TxValidationState, TxValidationState> {};
153
154namespace {
155
156BCLog::Level get_bclog_level(btck_LogLevel level)
157{
158 switch (level) {
159 case btck_LogLevel_INFO: {
160 return BCLog::Level::Info;
161 }
162 case btck_LogLevel_DEBUG: {
163 return BCLog::Level::Debug;
164 }
165 case btck_LogLevel_TRACE: {
166 return BCLog::Level::Trace;
167 }
168 }
169 assert(false);
170}
171
172BCLog::LogFlags get_bclog_flag(btck_LogCategory category)
173{
174 switch (category) {
177 }
180 }
183 }
186 }
189 }
192 }
195 }
198 }
201 }
204 }
207 }
208 }
209 assert(false);
210}
211
213{
214 switch (state) {
221 } // no default case, so the compiler can warn about missing cases
222 assert(false);
223}
224
225btck_Warning cast_btck_warning(kernel::Warning warning)
226{
227 switch (warning) {
232 } // no default case, so the compiler can warn about missing cases
233 assert(false);
234}
235
236struct LoggingConnection {
237 std::unique_ptr<std::list<std::function<void(const std::string&)>>::iterator> m_connection;
238 void* m_user_data;
239 std::function<void(void* user_data)> m_deleter;
240
241 LoggingConnection(btck_LogCallback callback, void* user_data, btck_DestroyCallback user_data_destroy_callback)
242 {
243 LOCK(cs_main);
244
245 auto connection{LogInstance().PushBackCallback([callback, user_data](const std::string& str) { callback(user_data, str.c_str(), str.length()); })};
246
247 // Only start logging if we just added the connection.
248 if (LogInstance().NumConnections() == 1 && !LogInstance().StartLogging()) {
249 LogError("Logger start failed.");
250 LogInstance().DeleteCallback(connection);
251 if (user_data && user_data_destroy_callback) {
252 user_data_destroy_callback(user_data);
253 }
254 throw std::runtime_error("Failed to start logging");
255 }
256
257 m_connection = std::make_unique<std::list<std::function<void(const std::string&)>>::iterator>(connection);
258 m_user_data = user_data;
259 m_deleter = user_data_destroy_callback;
260
261 LogDebug(BCLog::KERNEL, "Logger connected.");
262 }
263
264 ~LoggingConnection()
265 {
266 LOCK(cs_main);
267 LogDebug(BCLog::KERNEL, "Logger disconnecting.");
268
269 // Switch back to buffering by calling DisconnectTestLogger if the
270 // connection that we are about to remove is the last one.
271 if (LogInstance().NumConnections() == 1) {
273 } else {
275 }
276
277 m_connection.reset();
278 if (m_user_data && m_deleter) {
279 m_deleter(m_user_data);
280 }
281 }
282};
283
284class KernelNotifications final : public kernel::Notifications
285{
286private:
288
289public:
290 KernelNotifications(btck_NotificationInterfaceCallbacks cbs)
291 : m_cbs{cbs}
292 {
293 }
294
295 ~KernelNotifications()
296 {
297 if (m_cbs.user_data && m_cbs.user_data_destroy) {
298 m_cbs.user_data_destroy(m_cbs.user_data);
299 }
300 m_cbs.user_data_destroy = nullptr;
301 m_cbs.user_data = nullptr;
302 }
303
304 kernel::InterruptResult blockTip(SynchronizationState state, const CBlockIndex& index, double verification_progress) override
305 {
306 if (m_cbs.block_tip) m_cbs.block_tip(m_cbs.user_data, cast_state(state), btck_BlockTreeEntry::ref(&index), verification_progress);
307 return {};
308 }
309 void headerTip(SynchronizationState state, int64_t height, int64_t timestamp, bool presync) override
310 {
311 if (m_cbs.header_tip) m_cbs.header_tip(m_cbs.user_data, cast_state(state), height, timestamp, presync ? 1 : 0);
312 }
313 void progress(const bilingual_str& title, int progress_percent, bool resume_possible) override
314 {
315 if (m_cbs.progress) m_cbs.progress(m_cbs.user_data, title.original.c_str(), title.original.length(), progress_percent, resume_possible ? 1 : 0);
316 }
317 void warningSet(kernel::Warning id, const bilingual_str& message) override
318 {
319 if (m_cbs.warning_set) m_cbs.warning_set(m_cbs.user_data, cast_btck_warning(id), message.original.c_str(), message.original.length());
320 }
321 void warningUnset(kernel::Warning id) override
322 {
323 if (m_cbs.warning_unset) m_cbs.warning_unset(m_cbs.user_data, cast_btck_warning(id));
324 }
325 void flushError(const bilingual_str& message) override
326 {
327 if (m_cbs.flush_error) m_cbs.flush_error(m_cbs.user_data, message.original.c_str(), message.original.length());
328 }
329 void fatalError(const bilingual_str& message) override
330 {
331 if (m_cbs.fatal_error) m_cbs.fatal_error(m_cbs.user_data, message.original.c_str(), message.original.length());
332 }
333};
334
335class KernelValidationInterface final : public CValidationInterface
336{
337public:
339
340 explicit KernelValidationInterface(const btck_ValidationInterfaceCallbacks vi_cbs) : m_cbs{vi_cbs} {}
341
342 ~KernelValidationInterface()
343 {
344 if (m_cbs.user_data && m_cbs.user_data_destroy) {
345 m_cbs.user_data_destroy(m_cbs.user_data);
346 }
347 m_cbs.user_data = nullptr;
348 m_cbs.user_data_destroy = nullptr;
349 }
350
351protected:
352 void BlockChecked(const std::shared_ptr<const CBlock>& block, const BlockValidationState& stateIn) override
353 {
354 if (m_cbs.block_checked) {
355 m_cbs.block_checked(m_cbs.user_data,
356 btck_Block::copy(btck_Block::ref(&block)),
357 btck_BlockValidationState::ref(&stateIn));
358 }
359 }
360
361 void NewPoWValidBlock(const CBlockIndex* pindex, const std::shared_ptr<const CBlock>& block) override
362 {
363 if (m_cbs.pow_valid_block) {
364 m_cbs.pow_valid_block(m_cbs.user_data,
365 btck_Block::copy(btck_Block::ref(&block)),
366 btck_BlockTreeEntry::ref(pindex));
367 }
368 }
369
370 void BlockConnected(const ChainstateRole& role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) override
371 {
372 if (m_cbs.block_connected) {
373 m_cbs.block_connected(m_cbs.user_data,
374 btck_Block::copy(btck_Block::ref(&block)),
375 btck_BlockTreeEntry::ref(pindex));
376 }
377 }
378
379 void BlockDisconnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) override
380 {
381 if (m_cbs.block_disconnected) {
382 m_cbs.block_disconnected(m_cbs.user_data,
383 btck_Block::copy(btck_Block::ref(&block)),
384 btck_BlockTreeEntry::ref(pindex));
385 }
386 }
387};
388
389struct ContextOptions {
390 mutable Mutex m_mutex;
391 std::unique_ptr<const CChainParams> m_chainparams GUARDED_BY(m_mutex);
392 std::shared_ptr<KernelNotifications> m_notifications GUARDED_BY(m_mutex);
393 std::shared_ptr<KernelValidationInterface> m_validation_interface GUARDED_BY(m_mutex);
394};
395
396class Context
397{
398public:
399 std::unique_ptr<kernel::Context> m_context;
400
401 std::shared_ptr<KernelNotifications> m_notifications;
402
403 std::unique_ptr<util::SignalInterrupt> m_interrupt;
404
405 std::unique_ptr<ValidationSignals> m_signals;
406
407 std::unique_ptr<const CChainParams> m_chainparams;
408
409 std::shared_ptr<KernelValidationInterface> m_validation_interface;
410
411 Context(const ContextOptions* options, bool& sane)
412 : m_context{std::make_unique<kernel::Context>()},
413 m_interrupt{std::make_unique<util::SignalInterrupt>()}
414 {
415 if (options) {
416 LOCK(options->m_mutex);
417 if (options->m_chainparams) {
418 m_chainparams = std::make_unique<const CChainParams>(*options->m_chainparams);
419 }
420 if (options->m_notifications) {
421 m_notifications = options->m_notifications;
422 }
423 if (options->m_validation_interface) {
424 m_signals = std::make_unique<ValidationSignals>(std::make_unique<ImmediateTaskRunner>());
425 m_validation_interface = options->m_validation_interface;
426 m_signals->RegisterSharedValidationInterface(m_validation_interface);
427 }
428 }
429
430 if (!m_chainparams) {
431 m_chainparams = CChainParams::Main();
432 }
433 if (!m_notifications) {
434 m_notifications = std::make_shared<KernelNotifications>(btck_NotificationInterfaceCallbacks{
435 nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr});
436 }
437
439 sane = false;
440 }
441 }
442
443 ~Context()
444 {
445 if (m_signals) {
446 m_signals->UnregisterSharedValidationInterface(m_validation_interface);
447 }
448 }
449};
450
452struct ChainstateManagerOptions {
453 mutable Mutex m_mutex;
454 ChainstateManager::Options m_chainman_options GUARDED_BY(m_mutex);
455 node::BlockManager::Options m_blockman_options GUARDED_BY(m_mutex);
456 std::shared_ptr<const Context> m_context;
457 node::ChainstateLoadOptions m_chainstate_load_options GUARDED_BY(m_mutex);
458
459 ChainstateManagerOptions(const std::shared_ptr<const Context>& context, const fs::path& data_dir, const fs::path& blocks_dir)
460 : m_chainman_options{ChainstateManager::Options{
461 .chainparams = *context->m_chainparams,
462 .datadir = data_dir,
463 .notifications = *context->m_notifications,
464 .signals = context->m_signals.get()}},
465 m_blockman_options{node::BlockManager::Options{
466 .chainparams = *context->m_chainparams,
467 .blocks_dir = blocks_dir,
468 .notifications = *context->m_notifications,
469 .block_tree_db_params = DBParams{
470 .path = data_dir / "blocks" / "index",
471 .cache_bytes = kernel::CacheSizes{DEFAULT_KERNEL_CACHE}.block_tree_db,
472 }}},
473 m_context{context}, m_chainstate_load_options{node::ChainstateLoadOptions{}}
474 {
475 }
476};
477
478struct ChainMan {
479 std::unique_ptr<ChainstateManager> m_chainman;
480 std::shared_ptr<const Context> m_context;
481
482 ChainMan(std::unique_ptr<ChainstateManager> chainman, std::shared_ptr<const Context> context)
483 : m_chainman(std::move(chainman)), m_context(std::move(context)) {}
484};
485
486} // namespace
487
488struct btck_Transaction : Handle<btck_Transaction, std::shared_ptr<const CTransaction>> {};
489struct btck_TransactionOutput : Handle<btck_TransactionOutput, CTxOut> {};
490struct btck_ScriptPubkey : Handle<btck_ScriptPubkey, CScript> {};
491struct btck_LoggingConnection : Handle<btck_LoggingConnection, LoggingConnection> {};
492struct btck_ContextOptions : Handle<btck_ContextOptions, ContextOptions> {};
493struct btck_Context : Handle<btck_Context, std::shared_ptr<const Context>> {};
494struct btck_ChainParameters : Handle<btck_ChainParameters, CChainParams> {};
495struct btck_ChainstateManagerOptions : Handle<btck_ChainstateManagerOptions, ChainstateManagerOptions> {};
496struct btck_ChainstateManager : Handle<btck_ChainstateManager, ChainMan> {};
497struct btck_Chain : Handle<btck_Chain, CChain> {};
498struct btck_BlockSpentOutputs : Handle<btck_BlockSpentOutputs, std::shared_ptr<CBlockUndo>> {};
499struct btck_TransactionSpentOutputs : Handle<btck_TransactionSpentOutputs, CTxUndo> {};
500struct btck_Coin : Handle<btck_Coin, Coin> {};
501struct btck_BlockHash : Handle<btck_BlockHash, uint256> {};
502struct btck_TransactionInput : Handle<btck_TransactionInput, CTxIn> {};
503struct btck_WitnessStack : Handle<btck_WitnessStack, CScriptWitness> {};
504struct btck_TransactionOutPoint: Handle<btck_TransactionOutPoint, COutPoint> {};
505struct btck_Txid: Handle<btck_Txid, Txid> {};
506struct btck_PrecomputedTransactionData : Handle<btck_PrecomputedTransactionData, PrecomputedTransactionData> {};
507struct btck_BlockHeader: Handle<btck_BlockHeader, CBlockHeader> {};
508struct btck_ConsensusParams: Handle<btck_ConsensusParams, Consensus::Params> {};
509
510btck_Transaction* btck_transaction_create(const void* raw_transaction, size_t raw_transaction_len)
511{
512 assert(raw_transaction != nullptr || raw_transaction_len == 0);
513 try {
514 SpanReader stream{std::span{reinterpret_cast<const std::byte*>(raw_transaction), raw_transaction_len}};
515 return btck_Transaction::create(std::make_shared<const CTransaction>(deserialize, TX_WITH_WITNESS, stream));
516 } catch (...) {
517 return nullptr;
518 }
519}
520
522{
523 return btck_Transaction::get(transaction)->vout.size();
524}
525
526const btck_TransactionOutput* btck_transaction_get_output_at(const btck_Transaction* transaction, size_t output_index)
527{
528 const CTransaction& tx = *btck_Transaction::get(transaction);
529 assert(output_index < tx.vout.size());
530 return btck_TransactionOutput::ref(&tx.vout[output_index]);
531}
532
534{
535 return btck_Transaction::get(transaction)->vin.size();
536}
537
538const btck_TransactionInput* btck_transaction_get_input_at(const btck_Transaction* transaction, size_t input_index)
539{
540 assert(input_index < btck_Transaction::get(transaction)->vin.size());
541 return btck_TransactionInput::ref(&btck_Transaction::get(transaction)->vin[input_index]);
542}
543
545{
546 return btck_Transaction::get(transaction)->nLockTime;
547}
548
550{
551 return btck_Txid::ref(&btck_Transaction::get(transaction)->GetHash());
552}
553
555{
556 return btck_Transaction::copy(transaction);
557}
558
559int btck_transaction_to_bytes(const btck_Transaction* transaction, btck_WriteBytes writer, void* user_data)
560{
561 try {
562 WriterStream ws{writer, user_data};
563 ws << TX_WITH_WITNESS(btck_Transaction::get(transaction));
564 return 0;
565 } catch (...) {
566 return -1;
567 }
568}
569
571{
572 delete transaction;
573}
574
575btck_ScriptPubkey* btck_script_pubkey_create(const void* script_pubkey, size_t script_pubkey_len)
576{
577 assert(script_pubkey != nullptr || script_pubkey_len == 0);
578 auto data = std::span{reinterpret_cast<const uint8_t*>(script_pubkey), script_pubkey_len};
579 return btck_ScriptPubkey::create(data.begin(), data.end());
580}
581
582int btck_script_pubkey_to_bytes(const btck_ScriptPubkey* script_pubkey_, btck_WriteBytes writer, void* user_data)
583{
584 const auto& script_pubkey{btck_ScriptPubkey::get(script_pubkey_)};
585 return writer(script_pubkey.data(), script_pubkey.size(), user_data);
586}
587
589{
590 return btck_ScriptPubkey::copy(script_pubkey);
591}
592
594{
595 delete script_pubkey;
596}
597
599{
600 return btck_TransactionOutput::create(amount, btck_ScriptPubkey::get(script_pubkey));
601}
602
604{
605 return btck_TransactionOutput::copy(output);
606}
607
609{
610 return btck_ScriptPubkey::ref(&btck_TransactionOutput::get(output).scriptPubKey);
611}
612
614{
615 return btck_TransactionOutput::get(output).nValue;
616}
617
619{
620 delete output;
621}
622
624 const btck_Transaction* tx_to,
625 const btck_TransactionOutput** spent_outputs_, size_t spent_outputs_len)
626{
627 try {
628 const CTransaction& tx{*btck_Transaction::get(tx_to)};
629 auto txdata{btck_PrecomputedTransactionData::create()};
630 if (spent_outputs_ != nullptr && spent_outputs_len > 0) {
631 assert(spent_outputs_len == tx.vin.size());
632 std::vector<CTxOut> spent_outputs;
633 spent_outputs.reserve(spent_outputs_len);
634 for (size_t i = 0; i < spent_outputs_len; i++) {
635 const CTxOut& tx_out{btck_TransactionOutput::get(spent_outputs_[i])};
636 spent_outputs.push_back(tx_out);
637 }
638 btck_PrecomputedTransactionData::get(txdata).Init(tx, std::move(spent_outputs));
639 } else {
640 btck_PrecomputedTransactionData::get(txdata).Init(tx, {});
641 }
642
643 return txdata;
644 } catch (...) {
645 return nullptr;
646 }
647}
648
650{
651 return btck_PrecomputedTransactionData::copy(precomputed_txdata);
652}
653
655{
656 delete precomputed_txdata;
657}
658
660 const int64_t amount,
661 const btck_Transaction* tx_to,
662 const btck_PrecomputedTransactionData* precomputed_txdata,
663 const unsigned int input_index,
666{
667 // Assert that all specified flags are part of the interface before continuing
669
670 if (!is_valid_flag_combination(script_verify_flags::from_int(flags))) {
672 return 0;
673 }
674
675 const CTransaction& tx{*btck_Transaction::get(tx_to)};
676 assert(input_index < tx.vin.size());
677
678 const PrecomputedTransactionData& txdata{precomputed_txdata ? btck_PrecomputedTransactionData::get(precomputed_txdata) : PrecomputedTransactionData(tx)};
679
680 if (flags & btck_ScriptVerificationFlags_TAPROOT && txdata.m_spent_outputs.empty()) {
682 return 0;
683 }
684
685 if (status) *status = btck_ScriptVerifyStatus_OK;
686
687 bool result = VerifyScript(tx.vin[input_index].scriptSig,
688 btck_ScriptPubkey::get(script_pubkey),
689 &tx.vin[input_index].scriptWitness,
691 TransactionSignatureChecker(&tx, input_index, amount, txdata, MissingDataBehavior::FAIL),
692 nullptr);
693 return result ? 1 : 0;
694}
695
697{
698 return btck_TransactionInput::copy(input);
699}
700
702{
703 return btck_TransactionOutPoint::ref(&btck_TransactionInput::get(input).prevout);
704}
705
707{
708 return btck_TransactionInput::get(input).nSequence;
709}
710
712{
713 return btck_WitnessStack::ref(&btck_TransactionInput::get(input).scriptWitness);
714}
715
717{
718 const auto& script_sig{btck_TransactionInput::get(input).scriptSig};
719 return writer(script_sig.data(), script_sig.size(), user_data);
720}
721
723{
724 delete input;
725}
726
728{
729 return btck_WitnessStack::get(witness_stack).stack.size();
730}
731
732int btck_witness_stack_get_item_at(const btck_WitnessStack* witness_stack, size_t index, btck_WriteBytes writer, void* user_data)
733{
734 const auto& stack{btck_WitnessStack::get(witness_stack).stack};
735 assert(index < stack.size());
736 return writer(stack[index].data(), stack[index].size(), user_data);
737}
738
740{
741 return btck_WitnessStack::copy(witness_stack);
742}
743
745{
746 delete witness_stack;
747}
748
750{
751 return btck_TransactionOutPoint::copy(out_point);
752}
753
755{
756 return btck_TransactionOutPoint::get(out_point).n;
757}
758
760{
761 return btck_Txid::ref(&btck_TransactionOutPoint::get(out_point).hash);
762}
763
765{
766 delete out_point;
767}
768
770{
771 return btck_Txid::copy(txid);
772}
773
774void btck_txid_to_bytes(const btck_Txid* txid, unsigned char output[32])
775{
776 std::memcpy(output, btck_Txid::get(txid).begin(), 32);
777}
778
779int btck_txid_equals(const btck_Txid* txid1, const btck_Txid* txid2)
780{
781 return btck_Txid::get(txid1) == btck_Txid::get(txid2);
782}
783
785{
786 delete txid;
787}
788
790{
791 LOCK(cs_main);
797}
798
800{
801 LOCK(cs_main);
802 if (category == btck_LogCategory_ALL) {
803 LogInstance().SetLogLevel(get_bclog_level(level));
804 }
805
806 LogInstance().AddCategoryLogLevel(get_bclog_flag(category), get_bclog_level(level));
807}
808
810{
811 LogInstance().EnableCategory(get_bclog_flag(category));
812}
813
815{
816 LogInstance().DisableCategory(get_bclog_flag(category));
817}
818
820{
822}
823
825{
826 try {
827 return btck_LoggingConnection::create(callback, user_data, user_data_destroy_callback);
828 } catch (const std::exception&) {
829 return nullptr;
830 }
831}
832
834{
835 delete connection;
836}
837
839{
840 switch (chain_type) {
842 return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::Main().release()));
843 }
845 return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::TestNet().release()));
846 }
848 return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::TestNet4().release()));
849 }
851 return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::SigNet().release()));
852 }
854 return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::RegTest().release()));
855 }
856 }
857 assert(false);
858}
859
860btck_ChainParameters* btck_chain_parameters_create_signet(const void* challenge, size_t challenge_len)
861{
862 assert(challenge != nullptr || challenge_len == 0);
863 const uint8_t* p = static_cast<const uint8_t*>(challenge);
865 .challenge = std::vector<uint8_t>{p, p + challenge_len},
866 };
867 return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::SigNet(options).release()));
868}
869
871{
872 return btck_ChainParameters::copy(chain_parameters);
873}
874
876{
877 return btck_ConsensusParams::ref(&btck_ChainParameters::get(chain_parameters).GetConsensus());
878}
879
881{
882 delete chain_parameters;
883}
884
886{
887 return btck_ContextOptions::create();
888}
889
891{
892 // Copy the chainparams, so the caller can free it again
893 LOCK(btck_ContextOptions::get(options).m_mutex);
894 btck_ContextOptions::get(options).m_chainparams = std::make_unique<const CChainParams>(btck_ChainParameters::get(chain_parameters));
895}
896
898{
899 // The KernelNotifications are copy-initialized, so the caller can free them again.
900 LOCK(btck_ContextOptions::get(options).m_mutex);
901 btck_ContextOptions::get(options).m_notifications = std::make_shared<KernelNotifications>(notifications);
902}
903
905{
906 LOCK(btck_ContextOptions::get(options).m_mutex);
907 btck_ContextOptions::get(options).m_validation_interface = std::make_shared<KernelValidationInterface>(vi_cbs);
908}
909
911{
912 delete options;
913}
914
916{
917 bool sane{true};
918 const ContextOptions* opts = options ? &btck_ContextOptions::get(options) : nullptr;
919 auto context{std::make_shared<const Context>(opts, sane)};
920 if (!sane) {
921 LogError("Kernel context sanity check failed.");
922 return nullptr;
923 }
924 return btck_Context::create(context);
925}
926
928{
929 return btck_Context::copy(context);
930}
931
933{
934 return (*btck_Context::get(context)->m_interrupt)() ? 0 : -1;
935}
936
938{
939 delete context;
940}
941
943{
944 if (!btck_BlockTreeEntry::get(entry).pprev) {
945 LogInfo("Genesis block has no previous.");
946 return nullptr;
947 }
948
949 return btck_BlockTreeEntry::ref(btck_BlockTreeEntry::get(entry).pprev);
950}
951
953{
954 const auto* ancestor{btck_BlockTreeEntry::get(block_tree_entry).GetAncestor(height)};
955 assert(ancestor);
956 return btck_BlockTreeEntry::ref(ancestor);
957}
958
960{
961 return btck_BlockValidationState::create();
962}
963
965{
966 return btck_BlockValidationState::copy(state);
967}
968
970{
971 delete state;
972}
973
975{
976 auto& block_validation_state = btck_BlockValidationState::get(block_validation_state_);
977 if (block_validation_state.IsValid()) return btck_ValidationMode_VALID;
978 if (block_validation_state.IsInvalid()) return btck_ValidationMode_INVALID;
980}
981
983{
984 auto& block_validation_state = btck_BlockValidationState::get(block_validation_state_);
985 switch (block_validation_state.GetResult()) {
1004 } // no default case, so the compiler can warn about missing cases
1005 assert(false);
1006}
1007
1008btck_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)
1009{
1010 assert(data_dir != nullptr || data_dir_len == 0);
1011 assert(blocks_dir != nullptr || blocks_dir_len == 0);
1012 if (data_dir_len == 0 || blocks_dir_len == 0) {
1013 LogError("Failed to create chainstate manager options: dir must be non-null and non-empty");
1014 return nullptr;
1015 }
1016 try {
1017 fs::path abs_data_dir{fs::absolute(fs::PathFromString({data_dir, data_dir_len}))};
1018 fs::create_directories(abs_data_dir);
1019 fs::path abs_blocks_dir{fs::absolute(fs::PathFromString({blocks_dir, blocks_dir_len}))};
1020 fs::create_directories(abs_blocks_dir);
1021 return btck_ChainstateManagerOptions::create(btck_Context::get(context), abs_data_dir, abs_blocks_dir);
1022 } catch (const std::exception& e) {
1023 LogError("Failed to create chainstate manager options: %s", e.what());
1024 return nullptr;
1025 }
1026}
1027
1029{
1030 LOCK(btck_ChainstateManagerOptions::get(opts).m_mutex);
1031 btck_ChainstateManagerOptions::get(opts).m_chainman_options.worker_threads_num = worker_threads;
1032}
1033
1035{
1036 delete options;
1037}
1038
1039int btck_chainstate_manager_options_set_wipe_dbs(btck_ChainstateManagerOptions* chainman_opts, int wipe_block_tree_db, int wipe_chainstate_db)
1040{
1041 if (wipe_block_tree_db == 1 && wipe_chainstate_db != 1) {
1042 LogError("Wiping the block tree db without also wiping the chainstate db is currently unsupported.");
1043 return -1;
1044 }
1045 auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1046 LOCK(opts.m_mutex);
1047 opts.m_blockman_options.block_tree_db_params.wipe_data = wipe_block_tree_db == 1;
1048 opts.m_chainstate_load_options.wipe_chainstate_db = wipe_chainstate_db == 1;
1049 return 0;
1050}
1051
1053 btck_ChainstateManagerOptions* chainman_opts,
1054 int block_tree_db_in_memory)
1055{
1056 auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1057 LOCK(opts.m_mutex);
1058 opts.m_blockman_options.block_tree_db_params.memory_only = block_tree_db_in_memory == 1;
1059}
1060
1062 btck_ChainstateManagerOptions* chainman_opts,
1063 int chainstate_db_in_memory)
1064{
1065 auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1066 LOCK(opts.m_mutex);
1067 opts.m_chainstate_load_options.coins_db_in_memory = chainstate_db_in_memory == 1;
1068}
1069
1071 const btck_ChainstateManagerOptions* chainman_opts)
1072{
1073 auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1074 std::unique_ptr<ChainstateManager> chainman;
1075 try {
1076 LOCK(opts.m_mutex);
1077 chainman = std::make_unique<ChainstateManager>(*opts.m_context->m_interrupt, opts.m_chainman_options, opts.m_blockman_options);
1078 } catch (const std::exception& e) {
1079 LogError("Failed to create chainstate manager: %s", e.what());
1080 return nullptr;
1081 }
1082
1083 try {
1084 const auto chainstate_load_opts{WITH_LOCK(opts.m_mutex, return opts.m_chainstate_load_options)};
1085
1087 auto [status, chainstate_err]{node::LoadChainstate(*chainman, cache_sizes, chainstate_load_opts)};
1089 LogError("Failed to load chain state from your data directory: %s", chainstate_err.original);
1090 return nullptr;
1091 }
1092 std::tie(status, chainstate_err) = node::VerifyLoadedChainstate(*chainman, chainstate_load_opts);
1094 LogError("Failed to verify loaded chain state from your datadir: %s", chainstate_err.original);
1095 return nullptr;
1096 }
1097 if (auto result = chainman->ActivateBestChains(); !result) {
1098 LogError("%s", util::ErrorString(result).original);
1099 return nullptr;
1100 }
1101 } catch (const std::exception& e) {
1102 LogError("Failed to load chainstate: %s", e.what());
1103 return nullptr;
1104 }
1105
1106 return btck_ChainstateManager::create(std::move(chainman), opts.m_context);
1107}
1108
1110{
1111 auto block_index = WITH_LOCK(btck_ChainstateManager::get(chainman).m_chainman->GetMutex(),
1112 return btck_ChainstateManager::get(chainman).m_chainman->m_blockman.LookupBlockIndex(btck_BlockHash::get(block_hash)));
1113 if (!block_index) {
1114 LogDebug(BCLog::KERNEL, "A block with the given hash is not indexed.");
1115 return nullptr;
1116 }
1117 return btck_BlockTreeEntry::ref(block_index);
1118}
1119
1121{
1122 auto& chainman = *btck_ChainstateManager::get(chainstate_manager).m_chainman;
1123 return btck_BlockTreeEntry::ref(WITH_LOCK(chainman.GetMutex(), return chainman.m_best_header));
1124}
1125
1127{
1128 {
1129 LOCK(btck_ChainstateManager::get(chainman).m_chainman->GetMutex());
1130 for (const auto& chainstate : btck_ChainstateManager::get(chainman).m_chainman->m_chainstates) {
1131 if (chainstate->CanFlushToDisk()) {
1132 chainstate->ForceFlushStateToDisk();
1133 chainstate->ResetCoinsViews();
1134 }
1135 }
1136 }
1137
1138 delete chainman;
1139}
1140
1141int 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)
1142{
1143 try {
1144 std::vector<fs::path> import_files;
1145 import_files.reserve(block_file_paths_data_len);
1146 for (uint32_t i = 0; i < block_file_paths_data_len; i++) {
1147 if (block_file_paths_data[i] != nullptr) {
1148 import_files.emplace_back(std::string{block_file_paths_data[i], block_file_paths_lens[i]}.c_str());
1149 }
1150 }
1151 auto& chainman_ref{*btck_ChainstateManager::get(chainman).m_chainman};
1152 node::ImportBlocks(chainman_ref, import_files);
1153 WITH_LOCK(::cs_main, chainman_ref.UpdateIBDStatus());
1154 } catch (const std::exception& e) {
1155 LogError("Failed to import blocks: %s", e.what());
1156 return -1;
1157 }
1158 return 0;
1159}
1160
1161btck_Block* btck_block_create(const void* raw_block, size_t raw_block_length)
1162{
1163 assert(raw_block != nullptr || raw_block_length == 0);
1164 auto block{std::make_shared<CBlock>()};
1165
1166 SpanReader stream{std::span{reinterpret_cast<const std::byte*>(raw_block), raw_block_length}};
1167
1168 try {
1169 stream >> TX_WITH_WITNESS(*block);
1170 } catch (...) {
1171 LogDebug(BCLog::KERNEL, "Block decode failed.");
1172 return nullptr;
1173 }
1174
1175 return btck_Block::create(block);
1176}
1177
1179{
1180 return btck_Block::copy(block);
1181}
1182
1183int btck_block_check(const btck_Block* block, const btck_ConsensusParams* consensus_params, btck_BlockCheckFlags flags, btck_BlockValidationState* validation_state)
1184{
1185 auto& state = btck_BlockValidationState::get(validation_state);
1186 state = BlockValidationState{};
1187
1188 const bool check_pow = (flags & btck_BlockCheckFlags_POW) != 0;
1189 const bool check_merkle = (flags & btck_BlockCheckFlags_MERKLE) != 0;
1190
1191 const bool result = CheckBlock(*btck_Block::get(block), state, btck_ConsensusParams::get(consensus_params), /*fCheckPOW=*/check_pow, /*fCheckMerkleRoot=*/check_merkle);
1192
1193 return result ? 1 : 0;
1194}
1195
1197{
1198 return btck_Block::get(block)->vtx.size();
1199}
1200
1202{
1203 assert(index < btck_Block::get(block)->vtx.size());
1204 return btck_Transaction::ref(&btck_Block::get(block)->vtx[index]);
1205}
1206
1208{
1209 const auto& block_ptr = btck_Block::get(block);
1210 return btck_BlockHeader::create(static_cast<const CBlockHeader&>(*block_ptr));
1211}
1212
1213int btck_block_to_bytes(const btck_Block* block, btck_WriteBytes writer, void* user_data)
1214{
1215 try {
1216 WriterStream ws{writer, user_data};
1217 ws << TX_WITH_WITNESS(*btck_Block::get(block));
1218 return 0;
1219 } catch (...) {
1220 return -1;
1221 }
1222}
1223
1225{
1226 return btck_BlockHash::create(btck_Block::get(block)->GetHash());
1227}
1228
1230{
1231 delete block;
1232}
1233
1235{
1236 auto block{std::make_shared<CBlock>()};
1237 if (!btck_ChainstateManager::get(chainman).m_chainman->m_blockman.ReadBlock(*block, btck_BlockTreeEntry::get(entry))) {
1238 LogError("Failed to read block.");
1239 return nullptr;
1240 }
1241 return btck_Block::create(block);
1242}
1243
1245{
1246 return btck_BlockHeader::create(btck_BlockTreeEntry::get(entry).GetBlockHeader());
1247}
1248
1250{
1251 return btck_BlockTreeEntry::get(entry).nHeight;
1252}
1253
1255{
1256 return btck_BlockHash::ref(btck_BlockTreeEntry::get(entry).phashBlock);
1257}
1258
1260{
1261 return &btck_BlockTreeEntry::get(entry1) == &btck_BlockTreeEntry::get(entry2);
1262}
1263
1264btck_BlockHash* btck_block_hash_create(const unsigned char block_hash[32])
1265{
1266 return btck_BlockHash::create(std::span<const unsigned char>{block_hash, 32});
1267}
1268
1270{
1271 return btck_BlockHash::copy(block_hash);
1272}
1273
1274void btck_block_hash_to_bytes(const btck_BlockHash* block_hash, unsigned char output[32])
1275{
1276 std::memcpy(output, btck_BlockHash::get(block_hash).begin(), 32);
1277}
1278
1280{
1281 return btck_BlockHash::get(hash1) == btck_BlockHash::get(hash2);
1282}
1283
1285{
1286 delete hash;
1287}
1288
1290{
1291 auto block_undo{std::make_shared<CBlockUndo>()};
1292 if (btck_BlockTreeEntry::get(entry).nHeight < 1) {
1293 LogDebug(BCLog::KERNEL, "The genesis block does not have any spent outputs.");
1294 return btck_BlockSpentOutputs::create(block_undo);
1295 }
1296 if (!btck_ChainstateManager::get(chainman).m_chainman->m_blockman.ReadBlockUndo(*block_undo, btck_BlockTreeEntry::get(entry))) {
1297 LogError("Failed to read block spent outputs data.");
1298 return nullptr;
1299 }
1300 return btck_BlockSpentOutputs::create(block_undo);
1301}
1302
1304{
1305 return btck_BlockSpentOutputs::copy(block_spent_outputs);
1306}
1307
1309{
1310 return btck_BlockSpentOutputs::get(block_spent_outputs)->vtxundo.size();
1311}
1312
1314{
1315 assert(transaction_index < btck_BlockSpentOutputs::get(block_spent_outputs)->vtxundo.size());
1316 const auto* tx_undo{&btck_BlockSpentOutputs::get(block_spent_outputs)->vtxundo.at(transaction_index)};
1317 return btck_TransactionSpentOutputs::ref(tx_undo);
1318}
1319
1321{
1322 delete block_spent_outputs;
1323}
1324
1326{
1327 return btck_TransactionSpentOutputs::copy(transaction_spent_outputs);
1328}
1329
1331{
1332 return btck_TransactionSpentOutputs::get(transaction_spent_outputs).vprevout.size();
1333}
1334
1336{
1337 delete transaction_spent_outputs;
1338}
1339
1340const btck_Coin* btck_transaction_spent_outputs_get_coin_at(const btck_TransactionSpentOutputs* transaction_spent_outputs, size_t coin_index)
1341{
1342 assert(coin_index < btck_TransactionSpentOutputs::get(transaction_spent_outputs).vprevout.size());
1343 const Coin* coin{&btck_TransactionSpentOutputs::get(transaction_spent_outputs).vprevout.at(coin_index)};
1344 return btck_Coin::ref(coin);
1345}
1346
1348{
1349 return btck_Coin::copy(coin);
1350}
1351
1353{
1354 return btck_Coin::get(coin).nHeight;
1355}
1356
1358{
1359 return btck_Coin::get(coin).IsCoinBase() ? 1 : 0;
1360}
1361
1363{
1364 return btck_TransactionOutput::ref(&btck_Coin::get(coin).out);
1365}
1366
1368{
1369 delete coin;
1370}
1371
1373 btck_ChainstateManager* chainman,
1374 const btck_Block* block,
1375 int* _new_block)
1376{
1377 bool new_block;
1378 auto result = btck_ChainstateManager::get(chainman).m_chainman->ProcessNewBlock(btck_Block::get(block), /*force_processing=*/true, /*min_pow_checked=*/true, /*new_block=*/&new_block);
1379 if (_new_block) {
1380 *_new_block = new_block ? 1 : 0;
1381 }
1382 return result ? 0 : -1;
1383}
1384
1386 btck_ChainstateManager* chainstate_manager,
1387 const btck_BlockHeader* header)
1388{
1389 try {
1390 auto& chainman = btck_ChainstateManager::get(chainstate_manager).m_chainman;
1391
1392 auto state = btck_BlockValidationState::create();
1393 bool result{chainman->ProcessNewBlockHeaders({&btck_BlockHeader::get(header), 1}, /*min_pow_checked=*/true, btck_BlockValidationState::get(state))};
1394 assert(result == btck_BlockValidationState::get(state).IsValid());
1395 return state;
1396 } catch (const std::exception& e) {
1397 LogError("Failed to process block header: %s", e.what());
1398 return nullptr;
1399 }
1400}
1401
1403{
1404 return btck_Chain::ref(&WITH_LOCK(btck_ChainstateManager::get(chainman).m_chainman->GetMutex(), return btck_ChainstateManager::get(chainman).m_chainman->ActiveChain()));
1405}
1406
1408{
1409 LOCK(::cs_main);
1410 return btck_Chain::get(chain).Height();
1411}
1412
1413const btck_BlockTreeEntry* btck_chain_get_by_height(const btck_Chain* chain, int32_t height)
1414{
1415 LOCK(::cs_main);
1416 return btck_BlockTreeEntry::ref(btck_Chain::get(chain)[height]);
1417}
1418
1420{
1421 LOCK(::cs_main);
1422 return btck_Chain::get(chain).Contains(btck_BlockTreeEntry::get(entry)) ? 1 : 0;
1423}
1424
1425btck_BlockHeader* btck_block_header_create(const void* raw_block_header, size_t raw_block_header_len)
1426{
1427 assert(raw_block_header != nullptr && raw_block_header_len == 80);
1428 auto header{std::make_unique<CBlockHeader>()};
1429 SpanReader stream{std::span{reinterpret_cast<const std::byte*>(raw_block_header), raw_block_header_len}};
1430
1431 try {
1432 stream >> *header;
1433 } catch (...) {
1434 LogError("Block header decode failed.");
1435 return nullptr;
1436 }
1437
1438 return btck_BlockHeader::ref(header.release());
1439}
1440
1442{
1443 return btck_BlockHeader::copy(header);
1444}
1445
1447{
1448 return btck_BlockHash::create(btck_BlockHeader::get(header).GetHash());
1449}
1450
1452{
1453 return btck_BlockHash::ref(&btck_BlockHeader::get(header).hashPrevBlock);
1454}
1455
1457{
1458 return btck_BlockHeader::get(header).nTime;
1459}
1460
1462{
1463 return btck_BlockHeader::get(header).nBits;
1464}
1465
1467{
1468 return btck_BlockHeader::get(header).nVersion;
1469}
1470
1472{
1473 return btck_BlockHeader::get(header).nNonce;
1474}
1475
1476int btck_block_header_to_bytes(const btck_BlockHeader* header, unsigned char output[80])
1477{
1478 try {
1479 SpanWriter{std::as_writable_bytes(std::span{output, 80})} << btck_BlockHeader::get(header);
1480 return 0;
1481 } catch (...) {
1482 return -1;
1483 }
1484}
1485
1487{
1488 delete header;
1489}
1490
1492{
1493 const auto& state = btck_TxValidationState::get(state_);
1494 if (state.IsValid()) return btck_ValidationMode_VALID;
1495 if (state.IsInvalid()) return btck_ValidationMode_INVALID;
1497}
1498
1500{
1501 return btck_TxValidationState::create();
1502}
1503
1505{
1506 switch (btck_TxValidationState::get(state_).GetResult()) {
1520 } // no default case, so the compiler can warn about missing cases
1521 assert(false);
1522}
1523
1525{
1526 delete state;
1527}
1528
1530{
1531 auto& state = btck_TxValidationState::get(validation_state);
1532 state = TxValidationState{};
1533 const bool ok = CheckTransaction(*btck_Transaction::get(tx), state);
1534 return ok ? 1 : 0;
1535}
int flags
Definition: bitcoin-tx.cpp:530
ArgsManager & args
Definition: bitcoind.cpp:280
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.
void btck_logging_disable()
This disables the global internal logger.
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.
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.
void btck_logging_enable_category(btck_LogCategory category)
Enable a specific log category for the global internal logger.
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.
void btck_logging_disable_category(btck_LogCategory category)
Disable a specific log category for the global internal logger.
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.
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.
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.
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.
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.
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_logging_set_level_category(btck_LogCategory category, btck_LogLevel level)
Set the log level of the global internal logger.
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])
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
Definition: bitcoin-cli.cpp:61
btck_ValidationMode btck_tx_validation_state_get_validation_mode(const btck_TxValidationState *state_)
Returns the validation mode from an opaque btck_TxValidationState pointer.
int btck_transaction_input_get_script_sig(const btck_TransactionInput *input, btck_WriteBytes writer, void *user_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)
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_logging_set_options(const btck_LoggingOptions options)
Set some options for the global internal logger.
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 level at which logs should be produced.
#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
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
uint8_t btck_ChainType
#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
void(* btck_LogCallback)(void *user_data, const char *message, size_t message_len)
Callback function types.
#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
#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.
#define btck_LogCategory_ALL
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_BlockValidationResult_TIME_FUTURE
block timestamp was > 2 hours in the future (or our clock is bad)
#define btck_LogCategory_LEVELDB
#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_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.
bool m_always_print_category_level
Definition: logging.h:175
bool m_log_sourcelocations
Definition: logging.h:174
void SetLogLevel(Level level)
Definition: logging.h:250
size_t NumConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.h:205
bool m_log_time_micros
Definition: logging.h:172
bool m_log_threadnames
Definition: logging.h:173
std::list< std::function< void(conststd::string &)> >::iterator PushBackCallback(std::function< void(const std::string &)> fun) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Connect a slot to the print signal and return the connection.
Definition: logging.h:191
void DisableLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Disable logging This offers a slight speedup and slightly smaller memory usage compared to leaving th...
Definition: logging.cpp:116
bool StartLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Start logging (and flush all buffered messages)
Definition: logging.cpp:54
void EnableCategory(LogFlags flag)
Definition: logging.cpp:128
void AddCategoryLogLevel(LogFlags category, Level level) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.h:242
bool m_log_timestamps
Definition: logging.h:171
void DeleteCallback(std::list< std::function< void(const std::string &)> >::iterator it) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Delete a connection.
Definition: logging.h:199
void DisconnectTestLogger() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Only for testing.
Definition: logging.cpp:103
void DisableCategory(LogFlags flag)
Definition: logging.cpp:142
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:27
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:94
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:77
static std::unique_ptr< const CChainParams > TestNet4()
Definition: chainparams.h:179
static std::unique_ptr< const CChainParams > Main()
Definition: chainparams.h:175
static std::unique_ptr< const CChainParams > TestNet()
Definition: chainparams.h:177
static std::unique_ptr< const CChainParams > SigNet()
Definition: chainparams.h:173
static std::unique_ptr< const CChainParams > RegTest()
Definition: chainparams.h:171
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:281
const std::vector< CTxOut > vout
Definition: transaction.h:292
An output of a transaction.
Definition: transaction.h:140
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...
Definition: validation.h:945
A UTXO entry.
Definition: coins.h:46
Minimal stream for reading from an existing byte array by std::span.
Definition: streams.h:83
Minimal stream for writing to an existing span of bytes.
Definition: streams.h:130
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)
Definition: verify_flags.h:35
NumConnections
Definition: clientmodel.h:48
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
btcsignals::scoped_connection m_connection
Definition: interfaces.cpp:30
@ 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.
Definition: cs_main.cpp:8
static path absolute(const path &p)
Definition: fs.h:89
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:185
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.
Context m_context
Definition: protocol.cpp:141
static constexpr uint64_t DEFAULT_KERNEL_CACHE
Suggested default amount of cache reserved for the kernel (bytes)
Definition: caches.h:14
#define LogInfo(...)
Definition: log.h:125
#define LogError(...)
Definition: log.h:127
#define LogDebug(category,...)
Definition: log.h:143
BCLog::Logger & LogInstance()
Definition: logging.cpp:26
unsigned int nHeight
LogFlags
Definition: categories.h:14
@ RAND
Definition: categories.h:29
@ BLOCKSTORAGE
Definition: categories.h:42
@ COINDB
Definition: categories.h:33
@ REINDEX
Definition: categories.h:27
@ ALL
Definition: categories.h:48
@ LEVELDB
Definition: categories.h:35
@ VALIDATION
Definition: categories.h:36
@ PRUNE
Definition: categories.h:30
@ MEMPOOL
Definition: categories.h:18
@ BENCH
Definition: categories.h:20
@ KERNEL
Definition: categories.h:46
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...
Warning
Definition: warning.h:9
util::Result< void > SanityChecks(const Context &)
Ensure a usable environment with all necessary library support.
Definition: checks.cpp:15
Definition: messages.h:21
ChainstateLoadResult LoadChainstate(ChainstateManager &chainman, const CacheSizes &cache_sizes, const ChainstateLoadOptions &options)
Definition: chainstate.cpp:151
ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager &chainman, const ChainstateLoadOptions &options)
Definition: chainstate.cpp:240
void ImportBlocks(ChainstateManager &chainman, std::span< const fs::path > import_paths)
Level
Definition: log.h:52
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:93
ValidationSignals & m_signals
Definition: interfaces.cpp:515
std::shared_ptr< Chain::Notifications > m_notifications
Definition: interfaces.cpp:496
static constexpr TransactionSerParams TX_WITH_WITNESS
Definition: transaction.h:180
void Serialize(Stream &, V)=delete
constexpr deserialize_type deserialize
Definition: serialize.h:52
SigNetOptions holds configurations for creating a signet CChainParams.
Definition: chainparams.h:147
Application-specific storage settings.
Definition: dbwrapper.h:41
Bilingual messages:
Definition: translation.h:24
std::string original
Definition: translation.h:25
Options controlling the format of log messages.
int always_print_category_levels
Prepend the log category and level to log messages.
int log_time_micros
Log timestamps in microsecond precision.
int log_threadnames
Prepend the name of the thread to log messages.
int log_sourcelocations
Prepend the source location to log messages.
int log_timestamps
Prepend a timestamp to log messages.
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.
Definition: types.h:18
Context struct holding the kernel library's logically global state, and passed to external libbitcoin...
Definition: context.h:16
#define LOCK(cs)
Definition: sync.h:268
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:299
This header provides an interface and simple implementation for a task runner.
#define GUARDED_BY(x)
Definition: threadsafety.h:37
std::function< std::string(const char *)> TranslateFn
Translate a message to the native language of the user.
Definition: translation.h:16
bool CheckTransaction(const CTransaction &tx, TxValidationState &state)
Definition: tx_check.cpp:11
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
Functions for validating blocks and updating the block tree.
assert(!tx.IsCoinBase())
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:96