Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
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 <attributes.h>
10#include <chain.h>
11#include <coins.h>
12#include <consensus/tx_check.h>
14#include <dbwrapper.h>
15#include <kernel/caches.h>
16#include <kernel/chainparams.h>
17#include <kernel/checks.h>
18#include <kernel/context.h>
20#include <kernel/warning.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/log.h>
36#include <util/result.h>
38#include <util/stdmutex.h>
39#include <util/string.h>
40#include <util/task_runner.h>
41#include <util/time.h>
42#include <util/translation.h>
43#include <validation.h>
44#include <validationinterface.h>
45
46#include <atomic>
47#include <cstddef>
48#include <cstring>
49#include <exception>
50#include <iterator>
51#include <limits>
52#include <list>
53#include <memory>
54#include <optional>
55#include <span>
56#include <stdexcept>
57#include <string>
58#include <string_view>
59#include <tuple>
60#include <utility>
61#include <vector>
62
63namespace Consensus {
64struct Params;
65} // namespace Consensus
66
69
70// Define G_TRANSLATION_FUN symbol in libbitcoinkernel library so users of the
71// library aren't required to export this symbol
72extern const TranslateFn G_TRANSLATION_FUN{nullptr};
73
75
76namespace {
77
79{
81 if (flags & SCRIPT_VERIFY_WITNESS && ~flags & SCRIPT_VERIFY_P2SH) return false;
82 return true;
83}
84
85class WriterStream
86{
87private:
88 btck_WriteBytes m_writer;
89 void* m_user_data;
90
91public:
92 WriterStream(btck_WriteBytes writer, void* user_data)
93 : m_writer{writer}, m_user_data{user_data} {}
94
95 //
96 // Stream subset
97 //
98 void write(std::span<const std::byte> src)
99 {
100 if (m_writer(src.data(), src.size(), m_user_data) != 0) {
101 throw std::runtime_error("Failed to write serialization data");
102 }
103 }
104
105 template <typename T>
106 WriterStream& operator<<(const T& obj)
107 {
108 ::Serialize(*this, obj);
109 return *this;
110 }
111};
112
113template <typename C, typename CPP>
114struct Handle {
115 static C* ref(CPP* cpp_type)
116 {
117 return reinterpret_cast<C*>(cpp_type);
118 }
119
120 static const C* ref(const CPP* cpp_type)
121 {
122 return reinterpret_cast<const C*>(cpp_type);
123 }
124
125 template <typename... Args>
126 static C* create(Args&&... args)
127 {
128 auto cpp_obj{std::make_unique<CPP>(std::forward<Args>(args)...)};
129 return ref(cpp_obj.release());
130 }
131
132 static C* copy(const C* ptr)
133 {
134 auto cpp_obj{std::make_unique<CPP>(get(ptr))};
135 return ref(cpp_obj.release());
136 }
137
138 static const CPP& get(const C* ptr)
139 {
140 return *reinterpret_cast<const CPP*>(ptr);
141 }
142
143 static CPP& get(C* ptr)
144 {
145 return *reinterpret_cast<CPP*>(ptr);
146 }
147
148 static void operator delete(void* ptr)
149 {
150 delete reinterpret_cast<CPP*>(ptr);
151 }
152};
153
154} // namespace
155
156struct btck_BlockTreeEntry: Handle<btck_BlockTreeEntry, CBlockIndex> {};
157struct btck_LogEntry : Handle<btck_LogEntry, util::log::Entry> {};
158struct btck_Block : Handle<btck_Block, std::shared_ptr<const CBlock>> {};
159struct btck_BlockValidationState : Handle<btck_BlockValidationState, BlockValidationState> {};
160struct btck_TxValidationState : Handle<btck_TxValidationState, TxValidationState> {};
161
162namespace {
163
165{
166 switch (level) {
167 case btck_LogLevel_TRACE: {
169 }
170 case btck_LogLevel_DEBUG: {
172 }
173 case btck_LogLevel_INFO: {
175 }
178 }
179 case btck_LogLevel_ERROR: {
181 }
182 }
183 assert(false);
184}
185
187{
188 switch (state) {
195 } // no default case, so the compiler can warn about missing cases
196 assert(false);
197}
198
200{
201 switch (warning) {
206 } // no default case, so the compiler can warn about missing cases
207 assert(false);
208}
209
211{
212 switch (level) {
214 return btck_LogLevel_TRACE;
215 }
217 return btck_LogLevel_DEBUG;
218 }
220 return btck_LogLevel_INFO;
221 }
224 }
226 return btck_LogLevel_ERROR;
227 }
228 } // no default case, so the compiler can warn about missing cases
229 assert(false);
230}
231
232constexpr btck_StringView to_btck(std::string_view str)
233{
234 return {.data = str.data(), .len = str.size()};
235}
236
238{
239 switch (flag) {
242 }
245 }
248 }
251 }
254 }
255#ifdef DEBUG_LOCKCONTENTION
256 case BCLog::LogFlags::LOCK: {
258 }
259#endif
262 }
265 }
268 }
271 }
274 }
277 }
280 }
281 default: {
282 // Every category the kernel library can emit must be mapped above. This cannot be enforced
283 // at compile time, so abort in debug builds to catch it early, and deliver the entry as
284 // uncategorized otherwise.
285 Assume(false);
287 }
288 }
289}
290
291class KernelNotifications final : public kernel::Notifications
292{
293private:
295
296public:
297 KernelNotifications(btck_NotificationInterfaceCallbacks cbs)
298 : m_cbs{cbs}
299 {
300 }
301
302 ~KernelNotifications()
303 {
304 if (m_cbs.user_data && m_cbs.user_data_destroy) {
305 m_cbs.user_data_destroy(m_cbs.user_data);
306 }
307 m_cbs.user_data_destroy = nullptr;
308 m_cbs.user_data = nullptr;
309 }
310
311 kernel::InterruptResult blockTip(SynchronizationState state, const CBlockIndex& index, double verification_progress) override
312 {
313 if (m_cbs.block_tip) m_cbs.block_tip(m_cbs.user_data, cast_state(state), btck_BlockTreeEntry::ref(&index), verification_progress);
314 return {};
315 }
316 void headerTip(SynchronizationState state, int64_t height, int64_t timestamp, bool presync) override
317 {
318 if (m_cbs.header_tip) m_cbs.header_tip(m_cbs.user_data, cast_state(state), height, timestamp, presync ? 1 : 0);
319 }
320 void progress(const bilingual_str& title, int progress_percent, bool resume_possible) override
321 {
322 if (m_cbs.progress) m_cbs.progress(m_cbs.user_data, title.original.c_str(), title.original.length(), progress_percent, resume_possible ? 1 : 0);
323 }
324 void warningSet(kernel::Warning id, const bilingual_str& message) override
325 {
326 if (m_cbs.warning_set) m_cbs.warning_set(m_cbs.user_data, cast_btck_warning(id), message.original.c_str(), message.original.length());
327 }
328 void warningUnset(kernel::Warning id) override
329 {
330 if (m_cbs.warning_unset) m_cbs.warning_unset(m_cbs.user_data, cast_btck_warning(id));
331 }
332 void flushError(const bilingual_str& message) override
333 {
334 if (m_cbs.flush_error) m_cbs.flush_error(m_cbs.user_data, message.original.c_str(), message.original.length());
335 }
336 void fatalError(const bilingual_str& message) override
337 {
338 if (m_cbs.fatal_error) m_cbs.fatal_error(m_cbs.user_data, message.original.c_str(), message.original.length());
339 }
340};
341
342class KernelValidationInterface final : public CValidationInterface
343{
344public:
346
347 explicit KernelValidationInterface(const btck_ValidationInterfaceCallbacks vi_cbs) : m_cbs{vi_cbs} {}
348
350 {
351 if (m_cbs.user_data && m_cbs.user_data_destroy) {
352 m_cbs.user_data_destroy(m_cbs.user_data);
353 }
354 m_cbs.user_data = nullptr;
355 m_cbs.user_data_destroy = nullptr;
356 }
357
358protected:
359 void BlockChecked(const std::shared_ptr<const CBlock>& block, const BlockValidationState& stateIn) override
360 {
361 if (m_cbs.block_checked) {
362 m_cbs.block_checked(m_cbs.user_data,
363 btck_Block::copy(btck_Block::ref(&block)),
364 btck_BlockValidationState::ref(&stateIn));
365 }
366 }
367
368 void NewPoWValidBlock(const CBlockIndex* pindex, const std::shared_ptr<const CBlock>& block) override
369 {
370 if (m_cbs.pow_valid_block) {
371 m_cbs.pow_valid_block(m_cbs.user_data,
372 btck_Block::copy(btck_Block::ref(&block)),
373 btck_BlockTreeEntry::ref(pindex));
374 }
375 }
376
377 void BlockConnected(const ChainstateRole& role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) override
378 {
379 if (m_cbs.block_connected) {
380 m_cbs.block_connected(m_cbs.user_data,
381 btck_Block::copy(btck_Block::ref(&block)),
382 btck_BlockTreeEntry::ref(pindex));
383 }
384 }
385
386 void BlockDisconnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) override
387 {
388 if (m_cbs.block_disconnected) {
389 m_cbs.block_disconnected(m_cbs.user_data,
390 btck_Block::copy(btck_Block::ref(&block)),
391 btck_BlockTreeEntry::ref(pindex));
392 }
393 }
394};
395
396struct ContextOptions {
397 mutable Mutex m_mutex;
398 std::unique_ptr<const CChainParams> m_chainparams GUARDED_BY(m_mutex);
399 std::shared_ptr<KernelNotifications> m_notifications GUARDED_BY(m_mutex);
400 std::shared_ptr<KernelValidationInterface> m_validation_interface GUARDED_BY(m_mutex);
401};
402
403class Context
404{
405public:
406 std::unique_ptr<kernel::Context> m_context;
407
408 std::shared_ptr<KernelNotifications> m_notifications;
409
410 std::unique_ptr<util::SignalInterrupt> m_interrupt;
411
412 std::unique_ptr<ValidationSignals> m_signals;
413
414 std::unique_ptr<const CChainParams> m_chainparams;
415
416 std::shared_ptr<KernelValidationInterface> m_validation_interface;
417
418 Context(const ContextOptions* options, bool& sane)
419 : m_context{std::make_unique<kernel::Context>()},
420 m_interrupt{std::make_unique<util::SignalInterrupt>()}
421 {
422 if (options) {
423 LOCK(options->m_mutex);
424 if (options->m_chainparams) {
425 m_chainparams = std::make_unique<const CChainParams>(*options->m_chainparams);
426 }
427 if (options->m_notifications) {
428 m_notifications = options->m_notifications;
429 }
430 if (options->m_validation_interface) {
431 m_signals = std::make_unique<ValidationSignals>(std::make_unique<ImmediateTaskRunner>());
432 m_validation_interface = options->m_validation_interface;
433 m_signals->RegisterSharedValidationInterface(m_validation_interface);
434 }
435 }
436
437 if (!m_chainparams) {
438 m_chainparams = CChainParams::Main();
439 }
440 if (!m_notifications) {
441 m_notifications = std::make_shared<KernelNotifications>(btck_NotificationInterfaceCallbacks{
442 nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr});
443 }
444
445 if (!kernel::SanityChecks(*m_context)) {
446 sane = false;
447 }
448 }
449
450 ~Context()
451 {
452 if (m_signals) {
453 m_signals->UnregisterSharedValidationInterface(m_validation_interface);
454 }
455 }
456};
457
459struct ChainstateManagerOptions {
460 mutable Mutex m_mutex;
463 std::shared_ptr<const Context> m_context;
466
467 ChainstateManagerOptions(const std::shared_ptr<const Context>& context, const fs::path& data_dir, const fs::path& blocks_dir)
469 .chainparams = *context->m_chainparams,
470 .datadir = data_dir,
471 .notifications = *context->m_notifications,
472 .signals = context->m_signals.get()}},
473 m_blockman_options{node::BlockManager::Options{
474 .chainparams = *context->m_chainparams,
475 .blocks_dir = blocks_dir,
476 .notifications = *context->m_notifications,
477 .block_tree_db_params = DBParams{
478 .path = data_dir / "blocks" / "index",
479 .cache_bytes = kernel::CacheSizes{DEFAULT_KERNEL_CACHE}.block_tree_db,
480 }}},
481 m_context{context}, m_chainstate_load_options{node::ChainstateLoadOptions{}}
482 {
483 }
484};
485
486struct ChainMan {
487 std::unique_ptr<ChainstateManager> m_chainman;
488 std::shared_ptr<const Context> m_context;
489
490 ChainMan(std::unique_ptr<ChainstateManager> chainman, std::shared_ptr<const Context> context)
491 : m_chainman(std::move(chainman)), m_context(std::move(context)) {}
492};
493
494struct UserDataDeleter {
495 btck_DestroyCallback destroy;
496 void operator()(void* user_data) const
497 {
498 if (destroy) destroy(user_data);
499 }
500};
502using UserData = std::unique_ptr<void, UserDataDeleter>;
503
506class KernelLogger
507{
509 struct Callback {
511 UserData user_data;
512
513 void operator()(const btck_LogEntry* entry) const { fn(user_data.get(), entry); }
514 };
515
516 mutable StdMutex m_mutex;
518 std::list<Callback> m_callbacks GUARDED_BY(m_mutex);
520 std::atomic<size_t> m_callback_count{0};
522 std::atomic<util::log::Level> m_min_level{util::log::Level::Info};
523
526 void UnregisterCallback(std::list<Callback>::iterator it) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
527
528public:
531 class CallbackHandle
532 {
533 KernelLogger* m_logger;
534 std::list<Callback>::iterator m_it;
535
536 public:
537 CallbackHandle(KernelLogger& logger LIFETIMEBOUND, std::list<Callback>::iterator it)
538 : m_logger{&logger}, m_it{it} {}
539 CallbackHandle(CallbackHandle&& other) noexcept
540 : m_logger{std::exchange(other.m_logger, nullptr)}, m_it{other.m_it} {}
541 CallbackHandle& operator=(CallbackHandle&&) = delete;
543 {
544 if (m_logger) m_logger->UnregisterCallback(m_it);
545 }
546 };
547
549 [[nodiscard]] CallbackHandle RegisterCallback(btck_LogCallback fn, UserData user_data) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
551 void SetMinLevel(btck_LogLevel level)
552 {
553 m_min_level.store(to_util(level), std::memory_order_relaxed);
554 }
555
557 bool ShouldLog(util::log::Level level) const
558 {
559 return level >= m_min_level.load(std::memory_order_relaxed) &&
560 m_callback_count.load(std::memory_order_relaxed) > 0;
561 }
564 void Log(const util::log::Entry& entry) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
566 void MaybeLog(const util::log::Entry& entry) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
567 {
568 if (ShouldLog(entry.level)) {
569 Log(entry);
570 }
571 }
572};
573
574KernelLogger::CallbackHandle KernelLogger::RegisterCallback(btck_LogCallback fn, UserData user_data)
575{
576 // Construct before locking so that a failed push_back destroys user_data outside m_mutex.
577 Callback cb{fn, std::move(user_data)};
578 STDLOCK(m_mutex);
579 m_callbacks.push_back(std::move(cb));
580 m_callback_count.fetch_add(1, std::memory_order_relaxed);
581 return {*this, std::prev(m_callbacks.end())};
582}
583
584void KernelLogger::UnregisterCallback(std::list<Callback>::iterator it)
585{
586 // Avoid running the callback destructor while holding m_mutex.
587 std::list<Callback> dying;
588 {
589 STDLOCK(m_mutex);
590 dying.splice(dying.begin(), m_callbacks, it);
591 m_callback_count.fetch_sub(1, std::memory_order_relaxed);
592 }
593}
594
595void KernelLogger::Log(const util::log::Entry& entry) const
596{
597 STDLOCK(m_mutex);
598 for (const auto& callback : m_callbacks) {
599 try {
600 callback(btck_LogEntry::ref(&entry));
601 } catch (...) {
602 // Can't log the error here because we're already inside the logging path (would
603 // deadlock on m_mutex).
604 }
605 }
606}
607
608} // namespace
609
610struct btck_Transaction : Handle<btck_Transaction, std::shared_ptr<const CTransaction>> {};
611struct btck_TransactionOutput : Handle<btck_TransactionOutput, CTxOut> {};
612struct btck_ScriptPubkey : Handle<btck_ScriptPubkey, CScript> {};
613struct btck_LoggingConnection : Handle<btck_LoggingConnection, KernelLogger::CallbackHandle> {};
614struct btck_ContextOptions : Handle<btck_ContextOptions, ContextOptions> {};
615struct btck_Context : Handle<btck_Context, std::shared_ptr<const Context>> {};
616struct btck_ChainParameters : Handle<btck_ChainParameters, CChainParams> {};
617struct btck_ChainstateManagerOptions : Handle<btck_ChainstateManagerOptions, ChainstateManagerOptions> {};
618struct btck_ChainstateManager : Handle<btck_ChainstateManager, ChainMan> {};
619struct btck_Chain : Handle<btck_Chain, CChain> {};
620struct btck_BlockSpentOutputs : Handle<btck_BlockSpentOutputs, std::shared_ptr<CBlockUndo>> {};
621struct btck_TransactionSpentOutputs : Handle<btck_TransactionSpentOutputs, CTxUndo> {};
622struct btck_Coin : Handle<btck_Coin, Coin> {};
623struct btck_BlockHash : Handle<btck_BlockHash, uint256> {};
624struct btck_TransactionInput : Handle<btck_TransactionInput, CTxIn> {};
625struct btck_WitnessStack : Handle<btck_WitnessStack, CScriptWitness> {};
626struct btck_TransactionOutPoint: Handle<btck_TransactionOutPoint, COutPoint> {};
627struct btck_Txid: Handle<btck_Txid, Txid> {};
628struct btck_Wtxid: Handle<btck_Wtxid, Wtxid> {};
629struct btck_PrecomputedTransactionData : Handle<btck_PrecomputedTransactionData, PrecomputedTransactionData> {};
630struct btck_BlockHeader: Handle<btck_BlockHeader, CBlockHeader> {};
631struct btck_ConsensusParams: Handle<btck_ConsensusParams, Consensus::Params> {};
632
634{
635 assert(raw_transaction != nullptr || raw_transaction_len == 0);
636 try {
637 SpanReader stream{std::span{reinterpret_cast<const std::byte*>(raw_transaction), raw_transaction_len}};
638 return btck_Transaction::create(std::make_shared<const CTransaction>(deserialize, TX_WITH_WITNESS, stream));
639 } catch (...) {
640 return nullptr;
641 }
642}
643
645{
646 return btck_Transaction::get(transaction)->vout.size();
647}
648
650{
651 const CTransaction& tx = *btck_Transaction::get(transaction);
652 assert(output_index < tx.vout.size());
653 return btck_TransactionOutput::ref(&tx.vout[output_index]);
654}
655
657{
658 return btck_Transaction::get(transaction)->vin.size();
659}
660
662{
663 assert(input_index < btck_Transaction::get(transaction)->vin.size());
664 return btck_TransactionInput::ref(&btck_Transaction::get(transaction)->vin[input_index]);
665}
666
668{
669 return btck_Transaction::get(transaction)->version;
670}
671
673{
674 return btck_Transaction::get(transaction)->nLockTime;
675}
676
678{
679 return btck_Txid::ref(&btck_Transaction::get(transaction)->GetHash());
680}
681
683{
684 return btck_Transaction::get(transaction)->HasWitness() ? 1 : 0;
685}
686
688{
689 return btck_Wtxid::ref(&btck_Transaction::get(transaction)->GetWitnessHash());
690}
691
693{
694 return btck_Transaction::copy(transaction);
695}
696
698{
699 try {
700 WriterStream ws{writer, user_data};
701 ws << TX_WITH_WITNESS(btck_Transaction::get(transaction));
702 return 0;
703 } catch (...) {
704 return -1;
705 }
706}
707
712
714{
715 assert(script_pubkey != nullptr || script_pubkey_len == 0);
716 auto data = std::span{reinterpret_cast<const uint8_t*>(script_pubkey), script_pubkey_len};
717 return btck_ScriptPubkey::create(data.begin(), data.end());
718}
719
721{
722 const auto& script_pubkey{btck_ScriptPubkey::get(script_pubkey_)};
723 return writer(script_pubkey.data(), script_pubkey.size(), user_data);
724}
725
727{
728 return btck_ScriptPubkey::copy(script_pubkey);
729}
730
732{
733 delete script_pubkey;
734}
735
737{
738 return btck_TransactionOutput::create(amount, btck_ScriptPubkey::get(script_pubkey));
739}
740
742{
743 return btck_TransactionOutput::copy(output);
744}
745
747{
748 return btck_ScriptPubkey::ref(&btck_TransactionOutput::get(output).scriptPubKey);
749}
750
752{
753 return btck_TransactionOutput::get(output).nValue;
754}
755
757{
758 delete output;
759}
760
762 const btck_Transaction* tx_to,
764{
765 try {
766 const CTransaction& tx{*btck_Transaction::get(tx_to)};
767 auto txdata{btck_PrecomputedTransactionData::create()};
768 if (spent_outputs_ != nullptr && spent_outputs_len > 0) {
769 assert(spent_outputs_len == tx.vin.size());
770 std::vector<CTxOut> spent_outputs;
772 for (size_t i = 0; i < spent_outputs_len; i++) {
773 const CTxOut& tx_out{btck_TransactionOutput::get(spent_outputs_[i])};
774 spent_outputs.push_back(tx_out);
775 }
776 btck_PrecomputedTransactionData::get(txdata).Init(tx, std::move(spent_outputs));
777 } else {
778 btck_PrecomputedTransactionData::get(txdata).Init(tx, {});
779 }
780
781 return txdata;
782 } catch (...) {
783 return nullptr;
784 }
785}
786
791
796
798 const int64_t amount,
799 const btck_Transaction* tx_to,
801 const unsigned int input_index,
804{
805 // Assert that all specified flags are part of the interface before continuing
807
810 return 0;
811 }
812
813 const CTransaction& tx{*btck_Transaction::get(tx_to)};
814 assert(input_index < tx.vin.size());
815
816 const PrecomputedTransactionData& txdata{precomputed_txdata ? btck_PrecomputedTransactionData::get(precomputed_txdata) : PrecomputedTransactionData(tx)};
817
818 if (flags & btck_ScriptVerificationFlags_TAPROOT && txdata.m_spent_outputs.empty()) {
820 return 0;
821 }
822
823 if (status) *status = btck_ScriptVerifyStatus_OK;
824
825 bool result = VerifyScript(tx.vin[input_index].scriptSig,
826 btck_ScriptPubkey::get(script_pubkey),
827 &tx.vin[input_index].scriptWitness,
830 nullptr);
831 return result ? 1 : 0;
832}
833
835{
836 return btck_TransactionInput::copy(input);
837}
838
840{
841 return btck_TransactionOutPoint::ref(&btck_TransactionInput::get(input).prevout);
842}
843
845{
846 return btck_TransactionInput::get(input).nSequence;
847}
848
850{
851 return btck_WitnessStack::ref(&btck_TransactionInput::get(input).scriptWitness);
852}
853
855{
856 const auto& script_sig{btck_TransactionInput::get(input).scriptSig};
857 return writer(script_sig.data(), script_sig.size(), user_data);
858}
859
861{
862 delete input;
863}
864
866{
867 return btck_WitnessStack::get(witness_stack).stack.size();
868}
869
871{
872 const auto& stack{btck_WitnessStack::get(witness_stack).stack};
873 assert(index < stack.size());
874 return writer(stack[index].data(), stack[index].size(), user_data);
875}
876
878{
879 return btck_WitnessStack::copy(witness_stack);
880}
881
886
888{
889 return btck_TransactionOutPoint::copy(out_point);
890}
891
893{
894 return btck_TransactionOutPoint::get(out_point).n;
895}
896
898{
899 return btck_Txid::ref(&btck_TransactionOutPoint::get(out_point).hash);
900}
901
906
908{
909 return btck_Txid::copy(txid);
910}
911
912void btck_txid_to_bytes(const btck_Txid* txid, unsigned char output[32])
913{
914 std::memcpy(output, btck_Txid::get(txid).begin(), 32);
915}
916
918{
919 return btck_Txid::get(txid1) == btck_Txid::get(txid2);
920}
921
923{
924 delete txid;
925}
926
928{
929 return btck_Wtxid::copy(wtxid);
930}
931
932void btck_wtxid_to_bytes(const btck_Wtxid* wtxid, unsigned char output[32])
933{
934 std::memcpy(output, btck_Wtxid::get(wtxid).begin(), 32);
935}
936
938{
939 return btck_Wtxid::get(wtxid1) == btck_Wtxid::get(wtxid2);
940}
941
943{
944 delete wtxid;
945}
946
947namespace {
950KernelLogger& GetKernelLogger()
951{
952 static KernelLogger* logger{new KernelLogger};
953 return *logger;
954}
955} // namespace
956
957namespace util::log {
958// Kernel filters on level only. The category is delivered as part of the entry, so consumers can
959// filter on it in their callback.
960bool ShouldDebugLog(Category /*category*/)
961{
962 return GetKernelLogger().ShouldLog(Level::Debug);
963}
964
965bool ShouldTraceLog(Category /*category*/)
966{
967 return GetKernelLogger().ShouldLog(Level::Trace);
968}
969
970void Log(Entry entry)
971{
972 // Conditional logging, because the util::log framework doesn't allow us to check if the
973 // minimum level exceeds Info.
974 GetKernelLogger().MaybeLog(entry);
975}
976} // namespace util::log
977
978
980{
981 GetKernelLogger().SetMinLevel(level);
982}
983
985{
986 assert(callback);
987 try {
988 // Take ownership before anything can throw, so that user_data is always freed on error.
990 auto handle{GetKernelLogger().RegisterCallback(callback, std::move(data))};
991 LogDebug(BCLog::KERNEL, "Logger connected.");
992 return btck_LoggingConnection::create(std::move(handle));
993 } catch (...) {
994 return nullptr;
995 }
996}
997
999{
1000 if (!connection) return;
1001 LogDebug(BCLog::KERNEL, "Logger disconnecting.");
1002 delete connection;
1003}
1004
1006{
1007 // Some log statements are manually suffixed with a newline.
1008 return to_btck(util::RemoveSuffixView(btck_LogEntry::get(entry).message, "\n"));
1009}
1010
1012{
1013 return to_btck(btck_LogEntry::get(entry).thread_name);
1014}
1015
1017{
1018 return TicksSinceEpoch<std::chrono::nanoseconds>(btck_LogEntry::get(entry).timestamp);
1019}
1020
1022{
1023 return btck_LogEntry::get(entry).mocktime.count();
1024}
1025
1027{
1028 return to_btck(btck_LogEntry::get(entry).source_loc.file_name());
1029}
1030
1032{
1033 return to_btck(btck_LogEntry::get(entry).source_loc.function_name_short());
1034}
1035
1037{
1038 return btck_LogEntry::get(entry).source_loc.line();
1039}
1040
1042{
1043 return to_btck(btck_LogEntry::get(entry).level);
1044}
1045
1047{
1048 return to_btck(static_cast<BCLog::LogFlags>(btck_LogEntry::get(entry).category));
1049}
1050
1052{
1053 switch (chain_type) {
1055 return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::Main().release()));
1056 }
1058 return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::TestNet().release()));
1059 }
1061 return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::TestNet4().release()));
1062 }
1063 case btck_ChainType_SIGNET: {
1064 return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::SigNet().release()));
1065 }
1067 return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::RegTest().release()));
1068 }
1069 }
1070 assert(false);
1071}
1072
1074{
1075 assert(challenge != nullptr || challenge_len == 0);
1076 const uint8_t* p = static_cast<const uint8_t*>(challenge);
1078 .challenge = std::vector<uint8_t>{p, p + challenge_len},
1079 };
1080 return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::SigNet(options).release()));
1081}
1082
1087
1089{
1090 return btck_ConsensusParams::ref(&btck_ChainParameters::get(chain_parameters).GetConsensus());
1091}
1092
1097
1099{
1100 return btck_ContextOptions::create();
1101}
1102
1104{
1105 // Copy the chainparams, so the caller can free it again
1106 LOCK(btck_ContextOptions::get(options).m_mutex);
1107 btck_ContextOptions::get(options).m_chainparams = std::make_unique<const CChainParams>(btck_ChainParameters::get(chain_parameters));
1108}
1109
1111{
1112 // The KernelNotifications are copy-initialized, so the caller can free them again.
1113 LOCK(btck_ContextOptions::get(options).m_mutex);
1114 btck_ContextOptions::get(options).m_notifications = std::make_shared<KernelNotifications>(notifications);
1115}
1116
1118{
1119 LOCK(btck_ContextOptions::get(options).m_mutex);
1120 btck_ContextOptions::get(options).m_validation_interface = std::make_shared<KernelValidationInterface>(vi_cbs);
1121}
1122
1124{
1125 delete options;
1126}
1127
1129{
1130 bool sane{true};
1131 const ContextOptions* opts = options ? &btck_ContextOptions::get(options) : nullptr;
1132 auto context{std::make_shared<const Context>(opts, sane)};
1133 if (!sane) {
1134 LogError("Kernel context sanity check failed.");
1135 return nullptr;
1136 }
1137 return btck_Context::create(context);
1138}
1139
1141{
1142 return btck_Context::copy(context);
1143}
1144
1146{
1147 return (*btck_Context::get(context)->m_interrupt)() ? 0 : -1;
1148}
1149
1151{
1152 delete context;
1153}
1154
1156{
1157 if (!btck_BlockTreeEntry::get(entry).pprev) {
1158 LogInfo("Genesis block has no previous.");
1159 return nullptr;
1160 }
1161
1162 return btck_BlockTreeEntry::ref(btck_BlockTreeEntry::get(entry).pprev);
1163}
1164
1166{
1167 const auto* ancestor{btck_BlockTreeEntry::get(block_tree_entry).GetAncestor(height)};
1169 return btck_BlockTreeEntry::ref(ancestor);
1170}
1171
1173{
1174 return btck_BlockValidationState::create();
1175}
1176
1178{
1179 return btck_BlockValidationState::copy(state);
1180}
1181
1183{
1184 delete state;
1185}
1186
1194
1220
1222{
1223 assert(data_dir != nullptr || data_dir_len == 0);
1224 assert(blocks_dir != nullptr || blocks_dir_len == 0);
1225 if (data_dir_len == 0 || blocks_dir_len == 0) {
1226 LogError("Failed to create chainstate manager options: dir must be non-null and non-empty");
1227 return nullptr;
1228 }
1229 try {
1231 fs::create_directories(abs_data_dir);
1233 fs::create_directories(abs_blocks_dir);
1234 return btck_ChainstateManagerOptions::create(btck_Context::get(context), abs_data_dir, abs_blocks_dir);
1235 } catch (const std::exception& e) {
1236 LogError("Failed to create chainstate manager options: %s", e.what());
1237 return nullptr;
1238 }
1239}
1240
1242{
1243 LOCK(btck_ChainstateManagerOptions::get(opts).m_mutex);
1244 btck_ChainstateManagerOptions::get(opts).m_chainman_options.worker_threads_num = worker_threads;
1245}
1246
1248{
1250 LogError("Failed to set database cache: size is outside the supported range.");
1251 return -1;
1252 }
1253
1254 auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1255 LOCK(opts.m_mutex);
1256 opts.m_db_cache_bytes = database_cache_bytes;
1257 opts.m_blockman_options.block_tree_db_params.cache_bytes = kernel::CacheSizes{database_cache_bytes}.block_tree_db;
1258 return 0;
1259}
1260
1262{
1263 delete options;
1264}
1265
1267{
1268 if (wipe_block_tree_db == 1 && wipe_chainstate_db != 1) {
1269 LogError("Wiping the block tree db without also wiping the chainstate db is currently unsupported.");
1270 return -1;
1271 }
1272 auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1273 LOCK(opts.m_mutex);
1274 opts.m_blockman_options.block_tree_db_params.wipe_data = wipe_block_tree_db == 1;
1275 opts.m_chainstate_load_options.wipe_chainstate_db = wipe_chainstate_db == 1;
1276 return 0;
1277}
1278
1281 int block_tree_db_in_memory)
1282{
1283 auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1284 LOCK(opts.m_mutex);
1285 opts.m_blockman_options.block_tree_db_params.memory_only = block_tree_db_in_memory == 1;
1286}
1287
1291{
1292 auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1293 LOCK(opts.m_mutex);
1294 opts.m_chainstate_load_options.coins_db_in_memory = chainstate_db_in_memory == 1;
1295}
1296
1299{
1300 auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1301 std::unique_ptr<ChainstateManager> chainman;
1302 try {
1303 LOCK(opts.m_mutex);
1304 chainman = std::make_unique<ChainstateManager>(*opts.m_context->m_interrupt, opts.m_chainman_options, opts.m_blockman_options);
1305 } catch (const std::exception& e) {
1306 LogError("Failed to create chainstate manager: %s", e.what());
1307 return nullptr;
1308 }
1309
1310 try {
1311 const auto chainstate_load_opts{WITH_LOCK(opts.m_mutex, return opts.m_chainstate_load_options)};
1312
1313 const kernel::CacheSizes cache_sizes{WITH_LOCK(opts.m_mutex, return opts.m_db_cache_bytes)};
1316 LogError("Failed to load chain state from your data directory: %s", chainstate_err.original);
1317 return nullptr;
1318 }
1321 LogError("Failed to verify loaded chain state from your datadir: %s", chainstate_err.original);
1322 return nullptr;
1323 }
1324 if (auto result = chainman->ActivateBestChains(); !result) {
1325 LogError("%s", util::ErrorString(result).original);
1326 return nullptr;
1327 }
1328 } catch (const std::exception& e) {
1329 LogError("Failed to load chainstate: %s", e.what());
1330 return nullptr;
1331 }
1332
1333 return btck_ChainstateManager::create(std::move(chainman), opts.m_context);
1334}
1335
1337{
1338 auto block_index = WITH_LOCK(btck_ChainstateManager::get(chainman).m_chainman->GetMutex(),
1339 return btck_ChainstateManager::get(chainman).m_chainman->m_blockman.LookupBlockIndex(btck_BlockHash::get(block_hash)));
1340 if (!block_index) {
1341 LogDebug(BCLog::KERNEL, "A block with the given hash is not indexed.");
1342 return nullptr;
1343 }
1344 return btck_BlockTreeEntry::ref(block_index);
1345}
1346
1348{
1349 auto& chainman = *btck_ChainstateManager::get(chainstate_manager).m_chainman;
1350 return btck_BlockTreeEntry::ref(WITH_LOCK(chainman.GetMutex(), return chainman.m_best_header));
1351}
1352
1354{
1355 {
1356 LOCK(btck_ChainstateManager::get(chainman).m_chainman->GetMutex());
1357 for (const auto& chainstate : btck_ChainstateManager::get(chainman).m_chainman->m_chainstates) {
1358 if (chainstate->CanFlushToDisk()) {
1359 chainstate->ForceFlushStateToDisk();
1360 chainstate->ResetCoinsViews();
1361 }
1362 }
1363 }
1364
1365 delete chainman;
1366}
1367
1369{
1370 try {
1371 std::vector<fs::path> import_files;
1373 for (uint32_t i = 0; i < block_file_paths_data_len; i++) {
1374 if (block_file_paths_data[i] != nullptr) {
1375 import_files.emplace_back(std::string{block_file_paths_data[i], block_file_paths_lens[i]}.c_str());
1376 }
1377 }
1378 auto& chainman_ref{*btck_ChainstateManager::get(chainman).m_chainman};
1380 WITH_LOCK(::cs_main, chainman_ref.UpdateIBDStatus());
1381 } catch (const std::exception& e) {
1382 LogError("Failed to import blocks: %s", e.what());
1383 return -1;
1384 }
1385 return 0;
1386}
1387
1389{
1390 assert(raw_block != nullptr || raw_block_length == 0);
1391 auto block{std::make_shared<CBlock>()};
1392
1393 SpanReader stream{std::span{reinterpret_cast<const std::byte*>(raw_block), raw_block_length}};
1394
1395 try {
1396 stream >> TX_WITH_WITNESS(*block);
1397 } catch (...) {
1398 LogDebug(BCLog::KERNEL, "Block decode failed.");
1399 return nullptr;
1400 }
1401
1402 return btck_Block::create(block);
1403}
1404
1406{
1407 return btck_Block::copy(block);
1408}
1409
1411{
1412 auto& state = btck_BlockValidationState::get(validation_state);
1413 state = BlockValidationState{};
1414
1415 const bool check_pow = (flags & btck_BlockCheckFlags_POW) != 0;
1416 const bool check_merkle = (flags & btck_BlockCheckFlags_MERKLE) != 0;
1417
1418 const bool result = CheckBlock(*btck_Block::get(block), state, btck_ConsensusParams::get(consensus_params), /*fCheckPOW=*/check_pow, /*fCheckMerkleRoot=*/check_merkle);
1419
1420 return result ? 1 : 0;
1421}
1422
1424{
1425 return btck_Block::get(block)->vtx.size();
1426}
1427
1429{
1430 assert(index < btck_Block::get(block)->vtx.size());
1431 return btck_Transaction::ref(&btck_Block::get(block)->vtx[index]);
1432}
1433
1435{
1436 const auto& block_ptr = btck_Block::get(block);
1437 return btck_BlockHeader::create(static_cast<const CBlockHeader&>(*block_ptr));
1438}
1439
1440int btck_block_to_bytes(const btck_Block* block, btck_WriteBytes writer, void* user_data)
1441{
1442 try {
1443 WriterStream ws{writer, user_data};
1444 ws << TX_WITH_WITNESS(*btck_Block::get(block));
1445 return 0;
1446 } catch (...) {
1447 return -1;
1448 }
1449}
1450
1452{
1453 return btck_BlockHash::create(btck_Block::get(block)->GetHash());
1454}
1455
1457{
1458 delete block;
1459}
1460
1462{
1463 auto block{std::make_shared<CBlock>()};
1464 if (!btck_ChainstateManager::get(chainman).m_chainman->m_blockman.ReadBlock(*block, btck_BlockTreeEntry::get(entry))) {
1465 LogError("Failed to read block.");
1466 return nullptr;
1467 }
1468 return btck_Block::create(block);
1469}
1470
1472{
1473 return btck_BlockHeader::create(btck_BlockTreeEntry::get(entry).GetBlockHeader());
1474}
1475
1477{
1478 return btck_BlockTreeEntry::get(entry).nHeight;
1479}
1480
1482{
1483 return btck_BlockHash::ref(btck_BlockTreeEntry::get(entry).phashBlock);
1484}
1485
1487{
1488 return &btck_BlockTreeEntry::get(entry1) == &btck_BlockTreeEntry::get(entry2);
1489}
1490
1491btck_BlockHash* btck_block_hash_create(const unsigned char block_hash[32])
1492{
1493 return btck_BlockHash::create(std::span<const unsigned char>{block_hash, 32});
1494}
1495
1497{
1498 return btck_BlockHash::copy(block_hash);
1499}
1500
1501void btck_block_hash_to_bytes(const btck_BlockHash* block_hash, unsigned char output[32])
1502{
1503 std::memcpy(output, btck_BlockHash::get(block_hash).begin(), 32);
1504}
1505
1507{
1508 return btck_BlockHash::get(hash1) == btck_BlockHash::get(hash2);
1509}
1510
1512{
1513 delete hash;
1514}
1515
1517{
1518 auto block_undo{std::make_shared<CBlockUndo>()};
1519 if (btck_BlockTreeEntry::get(entry).nHeight < 1) {
1520 LogDebug(BCLog::KERNEL, "The genesis block does not have any spent outputs.");
1521 return btck_BlockSpentOutputs::create(block_undo);
1522 }
1523 if (!btck_ChainstateManager::get(chainman).m_chainman->m_blockman.ReadBlockUndo(*block_undo, btck_BlockTreeEntry::get(entry))) {
1524 LogError("Failed to read block spent outputs data.");
1525 return nullptr;
1526 }
1527 return btck_BlockSpentOutputs::create(block_undo);
1528}
1529
1534
1536{
1537 return btck_BlockSpentOutputs::get(block_spent_outputs)->vtxundo.size();
1538}
1539
1541{
1542 assert(transaction_index < btck_BlockSpentOutputs::get(block_spent_outputs)->vtxundo.size());
1543 const auto* tx_undo{&btck_BlockSpentOutputs::get(block_spent_outputs)->vtxundo.at(transaction_index)};
1544 return btck_TransactionSpentOutputs::ref(tx_undo);
1545}
1546
1551
1556
1558{
1559 return btck_TransactionSpentOutputs::get(transaction_spent_outputs).vprevout.size();
1560}
1561
1566
1568{
1569 assert(coin_index < btck_TransactionSpentOutputs::get(transaction_spent_outputs).vprevout.size());
1570 const Coin* coin{&btck_TransactionSpentOutputs::get(transaction_spent_outputs).vprevout.at(coin_index)};
1571 return btck_Coin::ref(coin);
1572}
1573
1575{
1576 return btck_Coin::copy(coin);
1577}
1578
1580{
1581 return btck_Coin::get(coin).nHeight;
1582}
1583
1585{
1586 return btck_Coin::get(coin).IsCoinBase() ? 1 : 0;
1587}
1588
1590{
1591 return btck_TransactionOutput::ref(&btck_Coin::get(coin).out);
1592}
1593
1595{
1596 delete coin;
1597}
1598
1600 btck_ChainstateManager* chainman,
1601 const btck_Block* block,
1602 int* _new_block)
1603{
1604 bool new_block;
1605 auto result = btck_ChainstateManager::get(chainman).m_chainman->ProcessNewBlock(btck_Block::get(block), /*force_processing=*/true, /*min_pow_checked=*/true, /*new_block=*/&new_block);
1606 if (_new_block) {
1607 *_new_block = new_block ? 1 : 0;
1608 }
1609 return result ? 0 : -1;
1610}
1611
1614 const btck_BlockHeader* header)
1615{
1616 try {
1617 auto& chainman = btck_ChainstateManager::get(chainstate_manager).m_chainman;
1618
1619 auto state = btck_BlockValidationState::create();
1620 bool result{chainman->ProcessNewBlockHeaders({&btck_BlockHeader::get(header), 1}, /*min_pow_checked=*/true, btck_BlockValidationState::get(state))};
1621 assert(result == btck_BlockValidationState::get(state).IsValid());
1622 return state;
1623 } catch (const std::exception& e) {
1624 LogError("Failed to process block header: %s", e.what());
1625 return nullptr;
1626 }
1627}
1628
1630{
1631 return btck_Chain::ref(&WITH_LOCK(btck_ChainstateManager::get(chainman).m_chainman->GetMutex(), return btck_ChainstateManager::get(chainman).m_chainman->ActiveChain()));
1632}
1633
1635{
1636 LOCK(::cs_main);
1637 return btck_Chain::get(chain).Height();
1638}
1639
1641{
1642 LOCK(::cs_main);
1643 return btck_BlockTreeEntry::ref(btck_Chain::get(chain)[height]);
1644}
1645
1647{
1648 LOCK(::cs_main);
1649 return btck_Chain::get(chain).Contains(btck_BlockTreeEntry::get(entry)) ? 1 : 0;
1650}
1651
1653{
1654 assert(raw_block_header != nullptr && raw_block_header_len == 80);
1655 auto header{std::make_unique<CBlockHeader>()};
1656 SpanReader stream{std::span{reinterpret_cast<const std::byte*>(raw_block_header), raw_block_header_len}};
1657
1658 try {
1659 stream >> *header;
1660 } catch (...) {
1661 LogError("Block header decode failed.");
1662 return nullptr;
1663 }
1664
1665 return btck_BlockHeader::ref(header.release());
1666}
1667
1669{
1670 return btck_BlockHeader::copy(header);
1671}
1672
1674{
1675 return btck_BlockHash::create(btck_BlockHeader::get(header).GetHash());
1676}
1677
1679{
1680 return btck_BlockHash::ref(&btck_BlockHeader::get(header).hashPrevBlock);
1681}
1682
1683void btck_block_header_get_merkle_root(const btck_BlockHeader* header, unsigned char output[32])
1684{
1685 std::memcpy(output, btck_BlockHeader::get(header).hashMerkleRoot.begin(), 32);
1686}
1687
1689{
1690 return btck_BlockHeader::get(header).nTime;
1691}
1692
1694{
1695 return btck_BlockHeader::get(header).nBits;
1696}
1697
1699{
1700 return btck_BlockHeader::get(header).nVersion;
1701}
1702
1704{
1705 return btck_BlockHeader::get(header).nNonce;
1706}
1707
1708int btck_block_header_to_bytes(const btck_BlockHeader* header, unsigned char output[80])
1709{
1710 try {
1711 SpanWriter{std::as_writable_bytes(std::span{output, 80})} << btck_BlockHeader::get(header);
1712 return 0;
1713 } catch (...) {
1714 return -1;
1715 }
1716}
1717
1719{
1720 delete header;
1721}
1722
1724{
1725 const auto& state = btck_TxValidationState::get(state_);
1726 if (state.IsValid()) return btck_ValidationMode_VALID;
1727 if (state.IsInvalid()) return btck_ValidationMode_INVALID;
1729}
1730
1732{
1733 return btck_TxValidationState::create();
1734}
1735
1755
1757{
1758 delete state;
1759}
1760
1762{
1763 auto& state = btck_TxValidationState::get(validation_state);
1764 state = TxValidationState{};
1765 const bool ok = CheckTransaction(*btck_Transaction::get(tx), state);
1766 return ok ? 1 : 0;
1767}
1768
1770{
1771 constexpr int64_t max_time{std::numeric_limits<uint32_t>::max()};
1773 return -1;
1774 }
1775 SetMockTime(std::chrono::seconds{timestamp});
1776 return 0;
1777}
#define LIFETIMEBOUND
Definition attributes.h:12
int flags
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.
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_StringView btck_log_entry_get_function_name(const btck_LogEntry *entry)
Get the name of the function that produced the log statement.
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.
btck_LogCategory btck_log_entry_get_category(const btck_LogEntry *entry)
Get the category of the log entry.
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.
int64_t btck_log_entry_get_timestamp_ns(const btck_LogEntry *entry)
Get the wall-clock time when the entry was logged.
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)
uint32_t btck_log_entry_get_line(const btck_LogEntry *entry)
Get the line number of the source code that produced the log statement.
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])
int64_t btck_log_entry_get_mocktime_s(const btck_LogEntry *entry)
Get the mock time in effect when the entry was logged.
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.
btck_LogLevel btck_log_entry_get_level(const btck_LogEntry *entry)
Get the severity level of the log entry.
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_StringView btck_log_entry_get_message(const btck_LogEntry *entry)
Get the message text from a btck_LogEntry.
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_StringView btck_log_entry_get_file_name(const btck_LogEntry *entry)
Get the name of the source file that produced the log statement.
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.
btck_StringView btck_log_entry_get_thread_name(const btck_LogEntry *entry)
Get the name of the thread that produced the log message.
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
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
#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.
Definition check.h:131
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()
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...
Definition validation.h:950
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)
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.
Definition cs_main.cpp:8
static path absolute(const path &p)
Definition fs.h:87
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition fs.h:183
static OutputStream & operator<<(OutputStream &os, const Array &array)
Definition gen.cpp:95
#define T(expected, seed, data)
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:148
constexpr uint64_t MAX_DBCACHE_BYTES
Maximum total database cache on current architecture (bytes)
Definition caches.h:17
constexpr uint64_t DEFAULT_KERNEL_CACHE
Suggested default amount of cache reserved for the kernel (bytes)
Definition caches.h:19
#define LogInfo(...)
Definition log.h:136
#define LogError(...)
Definition log.h:138
#define LogDebug(category,...)
Definition log.h:154
unsigned int nHeight
@ BLOCKSTORAGE
Definition categories.h:42
@ COINDB
Definition categories.h:33
@ REINDEX
Definition categories.h:27
@ TXPACKAGES
Definition categories.h:45
@ 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::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
Log
Log flags. Update stringify function if changed!
Definition proxy-io.h:133
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.
Level
Definition log.h:53
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).
Definition log.h:45
bilingual_str ErrorString(const Result< T > &result)
Definition result.h:93
std::string_view RemoveSuffixView(std::string_view str LIFETIMEBOUND, std::string_view suffix)
Definition string.h:178
ValidationSignals & m_signals
std::shared_ptr< Chain::Notifications > m_notifications
constexpr TransactionSerParams TX_WITH_WITNESS
void Serialize(Stream &, V)=delete
constexpr deserialize_type deserialize
Definition serialize.h:52
#define STDLOCK(cs)
Definition stdmutex.h:41
SigNetOptions holds configurations for creating a signet CChainParams.
Application-specific storage settings.
Definition dbwrapper.h:43
Bilingual messages:
Definition translation.h:24
std::string original
Definition translation.h:25
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.
A non-owning view of a string.
const char * data
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...
uint64_t block_tree_db
Definition caches.h:30
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
Information about chainstate that notifications are sent from.
Definition types.h:20
Context struct holding the kernel library's logically global state, and passed to external libbitcoin...
Definition context.h:16
Definition log.h:61
#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 EXCLUSIVE_LOCKS_REQUIRED(...)
#define GUARDED_BY(x)
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:19
void SetMockTime(std::chrono::time_point< NodeClock, std::chrono::seconds > mock)
Definition time.cpp:52
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82
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
WalletContext context