Bitcoin Core 31.99.0
P2P Digital Currency
bitcoinkernel_wrapper.h
Go to the documentation of this file.
1// Copyright (c) 2024-present The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#ifndef BITCOIN_KERNEL_BITCOINKERNEL_WRAPPER_H
6#define BITCOIN_KERNEL_BITCOINKERNEL_WRAPPER_H
7
9
10#include <array>
11#include <exception>
12#include <functional>
13#include <memory>
14#include <optional>
15#include <span>
16#include <stdexcept>
17#include <string>
18#include <string_view>
19#include <type_traits>
20#include <utility>
21#include <vector>
22
23namespace btck {
24
28 BLOCKSTORAGE = btck_LogCategory_BLOCKSTORAGE,
35 VALIDATION = btck_LogCategory_VALIDATION,
37};
38
39enum class LogLevel : btck_LogLevel {
43};
44
51};
52
57};
58
59enum class Warning : btck_Warning {
62};
63
68};
69
80};
81
86};
87
98};
99
105};
106
107template <typename T>
108struct is_bitmask_enum : std::false_type {
109};
110
111template <>
112struct is_bitmask_enum<ScriptVerificationFlags> : std::true_type {
113};
114
115template <>
116struct is_bitmask_enum<BlockCheckFlags> : std::true_type {
117};
118
119template <typename T>
120concept BitmaskEnum = is_bitmask_enum<T>::value;
121
122template <BitmaskEnum T>
123constexpr T operator|(T lhs, T rhs)
124{
125 return static_cast<T>(
126 static_cast<std::underlying_type_t<T>>(lhs) | static_cast<std::underlying_type_t<T>>(rhs));
127}
128
129template <BitmaskEnum T>
130constexpr T operator&(T lhs, T rhs)
131{
132 return static_cast<T>(
133 static_cast<std::underlying_type_t<T>>(lhs) & static_cast<std::underlying_type_t<T>>(rhs));
134}
135
136template <BitmaskEnum T>
137constexpr T operator^(T lhs, T rhs)
138{
139 return static_cast<T>(
140 static_cast<std::underlying_type_t<T>>(lhs) ^ static_cast<std::underlying_type_t<T>>(rhs));
141}
142
143template <BitmaskEnum T>
144constexpr T operator~(T value)
145{
146 return static_cast<T>(~static_cast<std::underlying_type_t<T>>(value));
147}
148
149template <BitmaskEnum T>
150constexpr T& operator|=(T& lhs, T rhs)
151{
152 return lhs = lhs | rhs;
153}
154
155template <BitmaskEnum T>
156constexpr T& operator&=(T& lhs, T rhs)
157{
158 return lhs = lhs & rhs;
159}
160
161template <BitmaskEnum T>
162constexpr T& operator^=(T& lhs, T rhs)
163{
164 return lhs = lhs ^ rhs;
165}
166
167template <typename T>
168T check(T ptr)
169{
170 if (ptr == nullptr) {
171 throw std::runtime_error("failed to instantiate btck object");
172 }
173 return ptr;
174}
175
176template <typename Collection, typename ValueType>
178{
179public:
180 using iterator_category = std::random_access_iterator_tag;
181 using iterator_concept = std::random_access_iterator_tag;
182 using difference_type = std::ptrdiff_t;
183 using value_type = ValueType;
184
185private:
186 const Collection* m_collection;
187 size_t m_idx;
188
189public:
190 Iterator() = default;
191 Iterator(const Collection* ptr) : m_collection{ptr}, m_idx{0} {}
192 Iterator(const Collection* ptr, size_t idx) : m_collection{ptr}, m_idx{idx} {}
193
194 // This is just a view, so return a copy.
195 auto operator*() const { return (*m_collection)[m_idx]; }
196 auto operator->() const { return (*m_collection)[m_idx]; }
197
198 auto& operator++() { m_idx++; return *this; }
199 auto operator++(int) { Iterator tmp = *this; ++(*this); return tmp; }
200
201 auto& operator--() { m_idx--; return *this; }
202 auto operator--(int) { auto temp = *this; --m_idx; return temp; }
203
204 auto& operator+=(difference_type n) { m_idx += n; return *this; }
205 auto& operator-=(difference_type n) { m_idx -= n; return *this; }
206
207 auto operator+(difference_type n) const { return Iterator(m_collection, m_idx + n); }
208 auto operator-(difference_type n) const { return Iterator(m_collection, m_idx - n); }
209
210 auto operator-(const Iterator& other) const { return static_cast<difference_type>(m_idx) - static_cast<difference_type>(other.m_idx); }
211
212 ValueType operator[](difference_type n) const { return (*m_collection)[m_idx + n]; }
213
214 auto operator<=>(const Iterator& other) const { return m_idx <=> other.m_idx; }
215
216 bool operator==(const Iterator& other) const { return m_collection == other.m_collection && m_idx == other.m_idx; }
217
218private:
219 friend Iterator operator+(difference_type n, const Iterator& it) { return it + n; }
220};
221
222template <typename Container, typename SizeFunc, typename GetFunc>
223concept IndexedContainer = requires(const Container& c, SizeFunc size_func, GetFunc get_func, std::size_t i) {
224 { std::invoke(size_func, c) } -> std::convertible_to<std::size_t>;
225 { std::invoke(get_func, c, i) }; // Return type is deduced
226};
227
228template <typename Container, auto SizeFunc, auto GetFunc>
229 requires IndexedContainer<Container, decltype(SizeFunc), decltype(GetFunc)>
230class Range
231{
232public:
233 using value_type = std::invoke_result_t<decltype(GetFunc), const Container&, size_t>;
234 using difference_type = std::ptrdiff_t;
237
238private:
239 const Container* m_container;
240
241public:
242 explicit Range(const Container& container) : m_container(&container)
243 {
244 static_assert(std::ranges::random_access_range<Range>);
245 }
246
247 iterator begin() const { return iterator(this, 0); }
248 iterator end() const { return iterator(this, size()); }
249
250 const_iterator cbegin() const { return begin(); }
251 const_iterator cend() const { return end(); }
252
253 size_t size() const { return std::invoke(SizeFunc, *m_container); }
254
255 bool empty() const { return size() == 0; }
256
257 value_type operator[](size_t index) const { return std::invoke(GetFunc, *m_container, index); }
258
259 value_type at(size_t index) const
260 {
261 if (index >= size()) {
262 throw std::out_of_range("Index out of range");
263 }
264 return (*this)[index];
265 }
266
267 value_type front() const { return (*this)[0]; }
268 value_type back() const { return (*this)[size() - 1]; }
269};
270
271#define MAKE_RANGE_METHOD(method_name, ContainerType, SizeFunc, GetFunc, container_expr) \
272 auto method_name() const & { \
273 return Range<ContainerType, SizeFunc, GetFunc>{container_expr}; \
274 } \
275 auto method_name() const && = delete;
276
277template <typename T>
278std::vector<std::byte> write_bytes(const T* object, int (*to_bytes)(const T*, btck_WriteBytes, void*))
279{
280 std::vector<std::byte> bytes;
281 struct UserData {
282 std::vector<std::byte>* bytes;
283 std::exception_ptr exception;
284 };
285 UserData user_data = UserData{.bytes = &bytes, .exception = nullptr};
286
287 constexpr auto const write = +[](const void* buffer, size_t len, void* user_data) -> int {
288 auto& data = *reinterpret_cast<UserData*>(user_data);
289 auto& bytes = *data.bytes;
290 try {
291 auto const* first = static_cast<const std::byte*>(buffer);
292 auto const* last = first + len;
293 bytes.insert(bytes.end(), first, last);
294 return 0;
295 } catch (...) {
296 data.exception = std::current_exception();
297 return -1;
298 }
299 };
300
301 if (to_bytes(object, write, &user_data) != 0) {
302 std::rethrow_exception(user_data.exception);
303 }
304 return bytes;
305}
306
307template <typename CType>
308class View
309{
310protected:
311 const CType* m_ptr;
312
313public:
314 explicit View(const CType* ptr) : m_ptr{check(ptr)} {}
315
316 const CType* get() const { return m_ptr; }
317};
318
319template <typename CType, CType* (*CopyFunc)(const CType*), void (*DestroyFunc)(CType*)>
321{
322protected:
323 CType* m_ptr;
324
325public:
326 explicit Handle(CType* ptr) : m_ptr{check(ptr)} {}
327
328 // Copy constructors
329 Handle(const Handle& other)
330 : m_ptr{check(CopyFunc(other.m_ptr))} {}
331 Handle& operator=(const Handle& other)
332 {
333 if (this != &other) {
334 Handle temp(other);
335 std::swap(m_ptr, temp.m_ptr);
336 }
337 return *this;
338 }
339
340 // Move constructors
341 Handle(Handle&& other) noexcept : m_ptr(other.m_ptr) { other.m_ptr = nullptr; }
342 Handle& operator=(Handle&& other) noexcept
343 {
344 DestroyFunc(m_ptr);
345 m_ptr = std::exchange(other.m_ptr, nullptr);
346 return *this;
347 }
348
349 template <typename ViewType>
350 requires std::derived_from<ViewType, View<CType>>
351 Handle(const ViewType& view)
352 : Handle{CopyFunc(view.get())}
353 {
354 }
355
356 ~Handle() { DestroyFunc(m_ptr); }
357
358 CType* get() { return m_ptr; }
359 const CType* get() const { return m_ptr; }
360};
361
362template <typename CType, void (*DestroyFunc)(CType*)>
364{
365protected:
366 struct Deleter {
367 void operator()(CType* ptr) const noexcept
368 {
369 if (ptr) DestroyFunc(ptr);
370 }
371 };
372 std::unique_ptr<CType, Deleter> m_ptr;
373
374public:
375 explicit UniqueHandle(CType* ptr) : m_ptr{check(ptr)} {}
376
377 CType* get() { return m_ptr.get(); }
378 const CType* get() const { return m_ptr.get(); }
379};
380
382class Transaction;
383class TransactionOutput;
385
386template <typename Derived>
388{
389private:
390 auto impl() const
391 {
392 return static_cast<const Derived*>(this)->get();
393 }
394
395 friend Derived;
396 ScriptPubkeyApi() = default;
397
398public:
399 bool Verify(int64_t amount,
400 const Transaction& tx_to,
401 const PrecomputedTransactionData* precomputed_txdata,
402 unsigned int input_index,
404 ScriptVerifyStatus& status) const;
405
406 std::vector<std::byte> ToBytes() const
407 {
409 }
410};
411
412class ScriptPubkeyView : public View<btck_ScriptPubkey>, public ScriptPubkeyApi<ScriptPubkeyView>
413{
414public:
415 explicit ScriptPubkeyView(const btck_ScriptPubkey* ptr) : View{ptr} {}
416};
417
418class ScriptPubkey : public Handle<btck_ScriptPubkey, btck_script_pubkey_copy, btck_script_pubkey_destroy>, public ScriptPubkeyApi<ScriptPubkey>
419{
420public:
421 explicit ScriptPubkey(std::span<const std::byte> raw)
422 : Handle{btck_script_pubkey_create(raw.data(), raw.size())} {}
423
425 : Handle(view) {}
426};
427
428template <typename Derived>
430{
431private:
432 auto impl() const
433 {
434 return static_cast<const Derived*>(this)->get();
435 }
436
437 friend Derived;
439
440public:
441 int64_t Amount() const
442 {
444 }
445
447 {
449 }
450};
451
452class TransactionOutputView : public View<btck_TransactionOutput>, public TransactionOutputApi<TransactionOutputView>
453{
454public:
455 explicit TransactionOutputView(const btck_TransactionOutput* ptr) : View{ptr} {}
456};
457
458class TransactionOutput : public Handle<btck_TransactionOutput, btck_transaction_output_copy, btck_transaction_output_destroy>, public TransactionOutputApi<TransactionOutput>
459{
460public:
461 explicit TransactionOutput(const ScriptPubkey& script_pubkey, int64_t amount)
462 : Handle{btck_transaction_output_create(script_pubkey.get(), amount)} {}
463
465 : Handle(view) {}
466};
467
468template <typename Derived>
470{
471private:
472 auto impl() const
473 {
474 return static_cast<const Derived*>(this)->get();
475 }
476
477 friend Derived;
478 TxidApi() = default;
479
480public:
481 bool operator==(const TxidApi& other) const
482 {
483 return btck_txid_equals(impl(), other.impl()) != 0;
484 }
485
486 bool operator!=(const TxidApi& other) const
487 {
488 return btck_txid_equals(impl(), other.impl()) == 0;
489 }
490
491 std::array<std::byte, 32> ToBytes() const
492 {
493 std::array<std::byte, 32> hash;
494 btck_txid_to_bytes(impl(), reinterpret_cast<unsigned char*>(hash.data()));
495 return hash;
496 }
497};
498
499class TxidView : public View<btck_Txid>, public TxidApi<TxidView>
500{
501public:
502 explicit TxidView(const btck_Txid* ptr) : View{ptr} {}
503};
504
505class Txid : public Handle<btck_Txid, btck_txid_copy, btck_txid_destroy>, public TxidApi<Txid>
506{
507public:
508 Txid(const TxidView& view)
509 : Handle(view) {}
510};
511
512template <typename Derived>
514{
515private:
516 auto impl() const
517 {
518 return static_cast<const Derived*>(this)->get();
519 }
520
521 friend Derived;
522 OutPointApi() = default;
523
524public:
525 uint32_t index() const
526 {
528 }
529
531 {
533 }
534};
535
536class OutPointView : public View<btck_TransactionOutPoint>, public OutPointApi<OutPointView>
537{
538public:
539 explicit OutPointView(const btck_TransactionOutPoint* ptr) : View{ptr} {}
540};
541
542class OutPoint : public Handle<btck_TransactionOutPoint, btck_transaction_out_point_copy, btck_transaction_out_point_destroy>, public OutPointApi<OutPoint>
543{
544public:
546 : Handle(view) {}
547};
548
549template <typename Derived>
551{
552private:
553 auto impl() const
554 {
555 return static_cast<const Derived*>(this)->get();
556 }
557
558 friend Derived;
560
561public:
563 {
565 }
566
567 uint32_t GetSequence() const
568 {
570 }
571};
572
573class TransactionInputView : public View<btck_TransactionInput>, public TransactionInputApi<TransactionInputView>
574{
575public:
576 explicit TransactionInputView(const btck_TransactionInput* ptr) : View{ptr} {}
577};
578
579class TransactionInput : public Handle<btck_TransactionInput, btck_transaction_input_copy, btck_transaction_input_destroy>, public TransactionInputApi<TransactionInput>
580{
581public:
583 : Handle(view) {}
584};
585
586template <typename Derived>
588{
589private:
590 auto impl() const
591 {
592 return static_cast<const Derived*>(this)->get();
593 }
594
595public:
596 size_t CountOutputs() const
597 {
599 }
600
601 size_t CountInputs() const
602 {
604 }
605
607 {
609 }
610
611 TransactionInputView GetInput(size_t index) const
612 {
614 }
615
616 uint32_t GetLocktime() const
617 {
619 }
620
622 {
624 }
625
627
629
630 std::vector<std::byte> ToBytes() const
631 {
633 }
634};
635
636class TransactionView : public View<btck_Transaction>, public TransactionApi<TransactionView>
637{
638public:
639 explicit TransactionView(const btck_Transaction* ptr) : View{ptr} {}
640};
641
642class Transaction : public Handle<btck_Transaction, btck_transaction_copy, btck_transaction_destroy>, public TransactionApi<Transaction>
643{
644public:
645 explicit Transaction(std::span<const std::byte> raw_transaction)
646 : Handle{btck_transaction_create(raw_transaction.data(), raw_transaction.size())} {}
647
649 : Handle{view} {}
650};
651
652class PrecomputedTransactionData : public Handle<btck_PrecomputedTransactionData, btck_precomputed_transaction_data_copy, btck_precomputed_transaction_data_destroy>
653{
654public:
655 explicit PrecomputedTransactionData(const Transaction& tx_to, std::span<const TransactionOutput> spent_outputs)
657 tx_to.get(),
658 reinterpret_cast<const btck_TransactionOutput**>(
659 const_cast<TransactionOutput*>(spent_outputs.data())),
660 spent_outputs.size())} {}
661};
662
663template <typename Derived>
665 const Transaction& tx_to,
666 const PrecomputedTransactionData* precomputed_txdata,
667 unsigned int input_index,
669 ScriptVerifyStatus& status) const
670{
671 auto result = btck_script_pubkey_verify(
672 impl(),
673 amount,
674 tx_to.get(),
675 precomputed_txdata ? precomputed_txdata->get() : nullptr,
676 input_index,
678 reinterpret_cast<btck_ScriptVerifyStatus*>(&status));
679 return result == 1;
680}
681
682template <typename Derived>
684{
685private:
686 auto impl() const
687 {
688 return static_cast<const Derived*>(this)->get();
689 }
690
691public:
692 bool operator==(const Derived& other) const
693 {
694 return btck_block_hash_equals(impl(), other.get()) != 0;
695 }
696
697 bool operator!=(const Derived& other) const
698 {
699 return btck_block_hash_equals(impl(), other.get()) == 0;
700 }
701
702 std::array<std::byte, 32> ToBytes() const
703 {
704 std::array<std::byte, 32> hash;
705 btck_block_hash_to_bytes(impl(), reinterpret_cast<unsigned char*>(hash.data()));
706 return hash;
707 }
708};
709
710class BlockHashView : public View<btck_BlockHash>, public BlockHashApi<BlockHashView>
711{
712public:
713 explicit BlockHashView(const btck_BlockHash* ptr) : View{ptr} {}
714};
715
716class BlockHash : public Handle<btck_BlockHash, btck_block_hash_copy, btck_block_hash_destroy>, public BlockHashApi<BlockHash>
717{
718public:
719 explicit BlockHash(const std::array<std::byte, 32>& hash)
720 : Handle{btck_block_hash_create(reinterpret_cast<const unsigned char*>(hash.data()))} {}
721
722 explicit BlockHash(btck_BlockHash* hash)
723 : Handle{hash} {}
724
726 : Handle{view} {}
727};
728
729template <typename Derived>
731{
732private:
733 auto impl() const
734 {
735 return static_cast<const Derived*>(this)->get();
736 }
737
738 friend Derived;
739 BlockHeaderApi() = default;
740
741public:
743 {
745 }
746
748 {
750 }
751
752 uint32_t Timestamp() const
753 {
755 }
756
757 uint32_t Bits() const
758 {
760 }
761
762 int32_t Version() const
763 {
765 }
766
767 uint32_t Nonce() const
768 {
770 }
771
772 std::array<std::byte, 80> ToBytes() const
773 {
774 std::array<std::byte, 80> header;
775 int res{btck_block_header_to_bytes(impl(), reinterpret_cast<unsigned char*>(header.data()))};
776 if (res != 0) {
777 throw std::runtime_error("Failed to serialize block header");
778 }
779 return header;
780 }
781};
782
783class BlockHeaderView : public View<btck_BlockHeader>, public BlockHeaderApi<BlockHeaderView>
784{
785public:
786 explicit BlockHeaderView(const btck_BlockHeader* ptr) : View{ptr} {}
787};
788
789class BlockHeader : public Handle<btck_BlockHeader, btck_block_header_copy, btck_block_header_destroy>, public BlockHeaderApi<BlockHeader>
790{
791public:
792 explicit BlockHeader(std::span<const std::byte> raw_header)
793 : Handle{btck_block_header_create(reinterpret_cast<const unsigned char*>(raw_header.data()), raw_header.size())} {}
794
796 : Handle{view} {}
797
799 : Handle{header} {}
800};
801
802class ConsensusParamsView : public View<btck_ConsensusParams>
803{
804public:
805 explicit ConsensusParamsView(const btck_ConsensusParams* ptr) : View{ptr} {}
806};
807
808class Block : public Handle<btck_Block, btck_block_copy, btck_block_destroy>
809{
810public:
811 Block(const std::span<const std::byte> raw_block)
812 : Handle{btck_block_create(raw_block.data(), raw_block.size())}
813 {
814 }
815
816 Block(btck_Block* block) : Handle{block} {}
817
818 size_t CountTransactions() const
819 {
821 }
822
823 TransactionView GetTransaction(size_t index) const
824 {
826 }
827
828 bool Check(const ConsensusParamsView& consensus_params,
830 BlockValidationState& state) const;
831
833
835 {
837 }
838
840 {
842 }
843
844 std::vector<std::byte> ToBytes() const
845 {
847 }
848};
849
850inline void logging_disable()
851{
853}
854
855inline void logging_set_options(const btck_LoggingOptions& logging_options)
856{
857 btck_logging_set_options(logging_options);
858}
859
861{
862 btck_logging_set_level_category(static_cast<btck_LogCategory>(category), static_cast<btck_LogLevel>(level));
863}
864
866{
867 btck_logging_enable_category(static_cast<btck_LogCategory>(category));
868}
869
871{
872 btck_logging_disable_category(static_cast<btck_LogCategory>(category));
873}
874
875template <typename T>
876concept Log = requires(T a, std::string_view message) {
877 { a.LogMessage(message) } -> std::same_as<void>;
878};
879
880template <Log T>
881class Logger : UniqueHandle<btck_LoggingConnection, btck_logging_connection_destroy>
882{
883public:
884 Logger(std::unique_ptr<T> log)
886 +[](void* user_data, const char* message, size_t message_len) { static_cast<T*>(user_data)->LogMessage({message, message_len}); },
887 log.release(),
888 +[](void* user_data) { delete static_cast<T*>(user_data); })}
889 {
890 }
891};
892
893class BlockTreeEntry : public View<btck_BlockTreeEntry>
894{
895public:
897 : View{entry}
898 {
899 }
900
901 bool operator==(const BlockTreeEntry& other) const
902 {
903 return btck_block_tree_entry_equals(get(), other.get()) != 0;
904 }
905
906 std::optional<BlockTreeEntry> GetPrevious() const
907 {
908 auto entry{btck_block_tree_entry_get_previous(get())};
909 if (!entry) return std::nullopt;
910 return entry;
911 }
912
913 int32_t GetHeight() const
914 {
916 }
917
919 {
921 }
922
924 {
926 }
927};
928
930{
931public:
932 virtual ~KernelNotifications() = default;
933
934 virtual void BlockTipHandler(SynchronizationState state, BlockTreeEntry entry, double verification_progress) {}
935
936 virtual void HeaderTipHandler(SynchronizationState state, int64_t height, int64_t timestamp, bool presync) {}
937
938 virtual void ProgressHandler(std::string_view title, int progress_percent, bool resume_possible) {}
939
940 virtual void WarningSetHandler(Warning warning, std::string_view message) {}
941
942 virtual void WarningUnsetHandler(Warning warning) {}
943
944 virtual void FlushErrorHandler(std::string_view error) {}
945
946 virtual void FatalErrorHandler(std::string_view error) {}
947};
948
949template <typename Derived>
951{
952private:
953 auto impl() const
954 {
955 return static_cast<const Derived*>(this)->get();
956 }
957
958 friend Derived;
960
961public:
963 {
965 }
966
968 {
970 }
971};
972
973class BlockValidationStateView : public View<btck_BlockValidationState>, public BlockValidationStateApi<BlockValidationStateView>
974{
975public:
977};
978
979class BlockValidationState : public Handle<btck_BlockValidationState, btck_block_validation_state_copy, btck_block_validation_state_destroy>, public BlockValidationStateApi<BlockValidationState>
980{
981public:
983
985};
986
987inline bool Block::Check(const ConsensusParamsView& consensus_params,
989 BlockValidationState& state) const
990{
991 return btck_block_check(get(), consensus_params.get(), static_cast<btck_BlockCheckFlags>(flags), state.get()) == 1;
992}
993
995{
996public:
997 virtual ~ValidationInterface() = default;
998
999 virtual void BlockChecked(Block block, BlockValidationStateView state) {}
1000
1001 virtual void PowValidBlock(BlockTreeEntry entry, Block block) {}
1002
1003 virtual void BlockConnected(Block block, BlockTreeEntry entry) {}
1004
1005 virtual void BlockDisconnected(Block block, BlockTreeEntry entry) {}
1006};
1007
1008class ChainParams : public Handle<btck_ChainParameters, btck_chain_parameters_copy, btck_chain_parameters_destroy>
1009{
1010public:
1012 : Handle{btck_chain_parameters_create(static_cast<btck_ChainType>(chain_type))} {}
1013
1015 {
1017 }
1018};
1019
1020class ContextOptions : public UniqueHandle<btck_ContextOptions, btck_context_options_destroy>
1021{
1022public:
1024
1025 void SetChainParams(ChainParams& chain_params)
1026 {
1027 btck_context_options_set_chainparams(get(), chain_params.get());
1028 }
1029
1030 template <typename T>
1031 void SetNotifications(std::shared_ptr<T> notifications)
1032 {
1033 static_assert(std::is_base_of_v<KernelNotifications, T>);
1034 auto heap_notifications = std::make_unique<std::shared_ptr<T>>(std::move(notifications));
1035 using user_type = std::shared_ptr<T>*;
1037 get(),
1039 .user_data = heap_notifications.release(),
1040 .user_data_destroy = +[](void* user_data) { delete static_cast<user_type>(user_data); },
1041 .block_tip = +[](void* user_data, btck_SynchronizationState state, const btck_BlockTreeEntry* entry, double verification_progress) { (*static_cast<user_type>(user_data))->BlockTipHandler(static_cast<SynchronizationState>(state), BlockTreeEntry{entry}, verification_progress); },
1042 .header_tip = +[](void* user_data, btck_SynchronizationState state, int64_t height, int64_t timestamp, int presync) { (*static_cast<user_type>(user_data))->HeaderTipHandler(static_cast<SynchronizationState>(state), height, timestamp, presync == 1); },
1043 .progress = +[](void* user_data, const char* title, size_t title_len, int progress_percent, int resume_possible) { (*static_cast<user_type>(user_data))->ProgressHandler({title, title_len}, progress_percent, resume_possible == 1); },
1044 .warning_set = +[](void* user_data, btck_Warning warning, const char* message, size_t message_len) { (*static_cast<user_type>(user_data))->WarningSetHandler(static_cast<Warning>(warning), {message, message_len}); },
1045 .warning_unset = +[](void* user_data, btck_Warning warning) { (*static_cast<user_type>(user_data))->WarningUnsetHandler(static_cast<Warning>(warning)); },
1046 .flush_error = +[](void* user_data, const char* error, size_t error_len) { (*static_cast<user_type>(user_data))->FlushErrorHandler({error, error_len}); },
1047 .fatal_error = +[](void* user_data, const char* error, size_t error_len) { (*static_cast<user_type>(user_data))->FatalErrorHandler({error, error_len}); },
1048 });
1049 }
1050
1051 template <typename T>
1052 void SetValidationInterface(std::shared_ptr<T> validation_interface)
1053 {
1054 static_assert(std::is_base_of_v<ValidationInterface, T>);
1055 auto heap_vi = std::make_unique<std::shared_ptr<T>>(std::move(validation_interface));
1056 using user_type = std::shared_ptr<T>*;
1058 get(),
1060 .user_data = heap_vi.release(),
1061 .user_data_destroy = +[](void* user_data) { delete static_cast<user_type>(user_data); },
1062 .block_checked = +[](void* user_data, btck_Block* block, const btck_BlockValidationState* state) { (*static_cast<user_type>(user_data))->BlockChecked(Block{block}, BlockValidationStateView{state}); },
1063 .pow_valid_block = +[](void* user_data, btck_Block* block, const btck_BlockTreeEntry* entry) { (*static_cast<user_type>(user_data))->PowValidBlock(BlockTreeEntry{entry}, Block{block}); },
1064 .block_connected = +[](void* user_data, btck_Block* block, const btck_BlockTreeEntry* entry) { (*static_cast<user_type>(user_data))->BlockConnected(Block{block}, BlockTreeEntry{entry}); },
1065 .block_disconnected = +[](void* user_data, btck_Block* block, const btck_BlockTreeEntry* entry) { (*static_cast<user_type>(user_data))->BlockDisconnected(Block{block}, BlockTreeEntry{entry}); },
1066 });
1067 }
1068};
1069
1070class Context : public Handle<btck_Context, btck_context_copy, btck_context_destroy>
1071{
1072public:
1074 : Handle{btck_context_create(opts.get())} {}
1075
1078
1080 {
1081 return btck_context_interrupt(get()) == 0;
1082 }
1083};
1084
1085class ChainstateManagerOptions : public UniqueHandle<btck_ChainstateManagerOptions, btck_chainstate_manager_options_destroy>
1086{
1087public:
1088 ChainstateManagerOptions(const Context& context, std::string_view data_dir, std::string_view blocks_dir)
1090 context.get(), data_dir.data(), data_dir.length(), blocks_dir.data(), blocks_dir.length())}
1091 {
1092 }
1093
1094 void SetWorkerThreads(int worker_threads)
1095 {
1097 }
1098
1099 bool SetWipeDbs(bool wipe_block_tree, bool wipe_chainstate)
1100 {
1101 return btck_chainstate_manager_options_set_wipe_dbs(get(), wipe_block_tree, wipe_chainstate) == 0;
1102 }
1103
1104 void UpdateBlockTreeDbInMemory(bool block_tree_db_in_memory)
1105 {
1107 }
1108
1109 void UpdateChainstateDbInMemory(bool chainstate_db_in_memory)
1110 {
1112 }
1113};
1114
1115class ChainView : public View<btck_Chain>
1116{
1117public:
1118 explicit ChainView(const btck_Chain* ptr) : View{ptr} {}
1119
1120 int32_t Height() const
1121 {
1122 return btck_chain_get_height(get());
1123 }
1124
1125 int CountEntries() const
1126 {
1127 return btck_chain_get_height(get()) + 1;
1128 }
1129
1130 BlockTreeEntry GetByHeight(int height) const
1131 {
1132 auto index{btck_chain_get_by_height(get(), height)};
1133 if (!index) throw std::runtime_error("No entry in the chain at the provided height");
1134 return index;
1135 }
1136
1137 bool Contains(BlockTreeEntry& entry) const
1138 {
1139 return btck_chain_contains(get(), entry.get());
1140 }
1141
1142 MAKE_RANGE_METHOD(Entries, ChainView, &ChainView::CountEntries, &ChainView::GetByHeight, *this)
1143};
1144
1145template <typename Derived>
1147{
1148private:
1149 auto impl() const
1150 {
1151 return static_cast<const Derived*>(this)->get();
1152 }
1153
1154 friend Derived;
1155 CoinApi() = default;
1156
1157public:
1158 uint32_t GetConfirmationHeight() const { return btck_coin_confirmation_height(impl()); }
1159
1160 bool IsCoinbase() const { return btck_coin_is_coinbase(impl()) == 1; }
1161
1163 {
1165 }
1166};
1167
1168class CoinView : public View<btck_Coin>, public CoinApi<CoinView>
1169{
1170public:
1171 explicit CoinView(const btck_Coin* ptr) : View{ptr} {}
1172};
1173
1174class Coin : public Handle<btck_Coin, btck_coin_copy, btck_coin_destroy>, public CoinApi<Coin>
1175{
1176public:
1177 Coin(btck_Coin* coin) : Handle{coin} {}
1178
1179 Coin(const CoinView& view) : Handle{view} {}
1180};
1181
1182template <typename Derived>
1184{
1185private:
1186 auto impl() const
1187 {
1188 return static_cast<const Derived*>(this)->get();
1189 }
1190
1191 friend Derived;
1193
1194public:
1195 size_t Count() const
1196 {
1198 }
1199
1200 CoinView GetCoin(size_t index) const
1201 {
1203 }
1204
1206};
1207
1208class TransactionSpentOutputsView : public View<btck_TransactionSpentOutputs>, public TransactionSpentOutputsApi<TransactionSpentOutputsView>
1209{
1210public:
1212};
1213
1214class TransactionSpentOutputs : public Handle<btck_TransactionSpentOutputs, btck_transaction_spent_outputs_copy, btck_transaction_spent_outputs_destroy>,
1215 public TransactionSpentOutputsApi<TransactionSpentOutputs>
1216{
1217public:
1218 TransactionSpentOutputs(btck_TransactionSpentOutputs* transaction_spent_outputs) : Handle{transaction_spent_outputs} {}
1219
1221};
1222
1223class BlockSpentOutputs : public Handle<btck_BlockSpentOutputs, btck_block_spent_outputs_copy, btck_block_spent_outputs_destroy>
1224{
1225public:
1227 : Handle{block_spent_outputs}
1228 {
1229 }
1230
1231 size_t Count() const
1232 {
1233 return btck_block_spent_outputs_count(get());
1234 }
1235
1237 {
1239 }
1240
1241 MAKE_RANGE_METHOD(TxsSpentOutputs, BlockSpentOutputs, &BlockSpentOutputs::Count, &BlockSpentOutputs::GetTxSpentOutputs, *this)
1242};
1243
1244class ChainMan : UniqueHandle<btck_ChainstateManager, btck_chainstate_manager_destroy>
1245{
1246public:
1247 ChainMan(const Context& context, const ChainstateManagerOptions& chainman_opts)
1248 : UniqueHandle{btck_chainstate_manager_create(chainman_opts.get())}
1249 {
1250 }
1251
1252 bool ImportBlocks(const std::span<const std::string> paths)
1253 {
1254 std::vector<const char*> c_paths;
1255 std::vector<size_t> c_paths_lens;
1256 c_paths.reserve(paths.size());
1257 c_paths_lens.reserve(paths.size());
1258 for (const auto& path : paths) {
1259 c_paths.push_back(path.c_str());
1260 c_paths_lens.push_back(path.length());
1261 }
1262
1263 return btck_chainstate_manager_import_blocks(get(), c_paths.data(), c_paths_lens.data(), c_paths.size()) == 0;
1264 }
1265
1266 bool ProcessBlock(const Block& block, bool* new_block)
1267 {
1268 int _new_block;
1269 int res = btck_chainstate_manager_process_block(get(), block.get(), &_new_block);
1270 if (new_block) *new_block = _new_block == 1;
1271 return res == 0;
1272 }
1273
1275 {
1276 return btck_chainstate_manager_process_block_header(get(), header.get(), state.get()) == 0;
1277 }
1278
1280 {
1282 }
1283
1284 std::optional<BlockTreeEntry> GetBlockTreeEntry(const BlockHash& block_hash) const
1285 {
1286 auto entry{btck_chainstate_manager_get_block_tree_entry_by_hash(get(), block_hash.get())};
1287 if (!entry) return std::nullopt;
1288 return entry;
1289 }
1290
1292 {
1294 }
1295
1296 std::optional<Block> ReadBlock(const BlockTreeEntry& entry) const
1297 {
1298 auto block{btck_block_read(get(), entry.get())};
1299 if (!block) return std::nullopt;
1300 return block;
1301 }
1302
1304 {
1305 return btck_block_spent_outputs_read(get(), entry.get());
1306 }
1307};
1308
1309} // namespace btck
1310
1311#endif // BITCOIN_KERNEL_BITCOINKERNEL_WRAPPER_H
int flags
Definition: bitcoin-tx.cpp:530
int btck_block_to_bytes(const btck_Block *block, btck_WriteBytes writer, void *user_data)
void btck_logging_disable()
This disables the global internal logger.
int btck_script_pubkey_to_bytes(const btck_ScriptPubkey *script_pubkey_, btck_WriteBytes writer, void *user_data)
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_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.
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.
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.
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...
size_t btck_transaction_count_outputs(const btck_Transaction *transaction)
Get the number of outputs of a transaction.
btck_ScriptPubkey * btck_script_pubkey_create(const void *script_pubkey, size_t script_pubkey_len)
Create a script pubkey from serialized data.
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.
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.
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.
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.
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)
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)
btck_ChainstateManager * btck_chainstate_manager_create(const btck_ChainstateManagerOptions *chainman_opts)
Create a chainstate manager.
btck_BlockHash * btck_block_get_hash(const btck_Block *block)
Calculate and return the hash of a block.
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.
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])
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.
const btck_TransactionOutput * btck_transaction_get_output_at(const btck_Transaction *transaction, size_t output_index)
Get the transaction outputs at the provided index.
void btck_logging_set_level_category(btck_LogCategory category, btck_LogLevel level)
Set the log level of the global internal logger.
void btck_context_options_set_chainparams(btck_ContextOptions *options, const btck_ChainParameters *chain_parameters)
int btck_block_header_to_bytes(const btck_BlockHeader *header, unsigned char output[80])
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_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.
int btck_chainstate_manager_process_block_header(btck_ChainstateManager *chainstate_manager, const btck_BlockHeader *header, btck_BlockValidationState *state)
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.
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.
const btck_BlockTreeEntry * btck_chain_get_by_height(const btck_Chain *chain, int height)
Retrieve a block tree entry by its height in the currently active chain.
int btck_block_hash_equals(const btck_BlockHash *hash1, const btck_BlockHash *hash2)
int32_t btck_block_tree_entry_get_height(const btck_BlockTreeEntry *entry)
Return the height of a certain block tree entry.
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_chain_get_height(const btck_Chain *chain)
Return the height of the tip of the chain.
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_Transaction * btck_transaction_create(const void *raw_transaction, size_t raw_transaction_len)
Create a new transaction from the serialized data.
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.
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.
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.
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
#define btck_ScriptVerificationFlags_P2SH
evaluate P2SH (BIP16) subscripts
uint8_t btck_LogLevel
The level at which logs should be produced.
#define btck_ScriptVerificationFlags_CHECKLOCKTIMEVERIFY
enable CHECKLOCKTIMEVERIFY (BIP65)
int(* btck_WriteBytes)(const void *bytes, size_t size, void *userdata)
Function signature for serializing data.
#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
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_LogLevel_TRACE
#define btck_ChainType_TESTNET
#define btck_SynchronizationState_INIT_REINDEX
#define btck_BlockCheckFlags_BASE
run the base context-free block checks only
#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_BlockCheckFlags_ALL
enable all optional context-free block checks
#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_ScriptVerificationFlags_WITNESS
enable WITNESS (BIP141)
#define btck_BlockCheckFlags_POW
run CheckProofOfWork via CheckBlockHeader
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_ScriptVerificationFlags_NONE
#define btck_LogCategory_RAND
#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_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
uint8_t btck_LogCategory
A collection of logging categories that may be encountered by kernel code.
#define btck_ValidationMode_INVALID
#define btck_ChainType_SIGNET
uint32_t btck_BlockCheckFlags
Bitflags to control context-free block checks (optional).
#define btck_ScriptVerificationFlags_NULLDUMMY
enforce NULLDUMMY (BIP147)
#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_ScriptVerificationFlags_CHECKSEQUENCEVERIFY
enable CHECKSEQUENCEVERIFY (BIP112)
#define btck_LogCategory_BLOCKSTORAGE
#define btck_ValidationMode_VALID
#define btck_LogCategory_KERNEL
#define btck_ScriptVerificationFlags_DERSIG
enforce strict DER (BIP66) compliance
#define btck_BlockValidationResult_MUTATED
the block's data didn't match the data committed to by the PoW
#define btck_SynchronizationState_INIT_DOWNLOAD
#define MAKE_RANGE_METHOD(method_name, ContainerType, SizeFunc, GetFunc, container_expr)
bool operator==(const Derived &other) const
std::array< std::byte, 32 > ToBytes() const
bool operator!=(const Derived &other) const
BlockHash(const std::array< std::byte, 32 > &hash)
BlockHash(btck_BlockHash *hash)
BlockHash(const BlockHashView &view)
BlockHashView(const btck_BlockHash *ptr)
BlockHashView PrevHash() const
std::array< std::byte, 80 > ToBytes() const
BlockHeaderApi()=default
BlockHeader(btck_BlockHeader *header)
BlockHeader(std::span< const std::byte > raw_header)
BlockHeader(const BlockHeaderView &view)
BlockHeaderView(const btck_BlockHeader *ptr)
BlockHash GetHash() const
std::vector< std::byte > ToBytes() const
bool Check(const ConsensusParamsView &consensus_params, BlockCheckFlags flags, BlockValidationState &state) const
TransactionView GetTransaction(size_t index) const
BlockHeader GetHeader() const
Block(btck_Block *block)
size_t CountTransactions() const
Block(const std::span< const std::byte > raw_block)
TransactionSpentOutputsView GetTxSpentOutputs(size_t tx_undo_index) const
BlockSpentOutputs(btck_BlockSpentOutputs *block_spent_outputs)
int32_t GetHeight() const
BlockTreeEntry(const btck_BlockTreeEntry *entry)
std::optional< BlockTreeEntry > GetPrevious() const
bool operator==(const BlockTreeEntry &other) const
BlockHashView GetHash() const
BlockHeader GetHeader() const
ValidationMode GetValidationMode() const
BlockValidationResult GetBlockValidationResult() const
BlockValidationState(const BlockValidationStateView &view)
BlockValidationStateView(const btck_BlockValidationState *ptr)
std::optional< BlockTreeEntry > GetBlockTreeEntry(const BlockHash &block_hash) const
std::optional< Block > ReadBlock(const BlockTreeEntry &entry) const
BlockSpentOutputs ReadBlockSpentOutputs(const BlockTreeEntry &entry) const
bool ProcessBlockHeader(const BlockHeader &header, BlockValidationState &state)
ChainView GetChain() const
BlockTreeEntry GetBestEntry() const
ChainMan(const Context &context, const ChainstateManagerOptions &chainman_opts)
bool ImportBlocks(const std::span< const std::string > paths)
bool ProcessBlock(const Block &block, bool *new_block)
ChainParams(ChainType chain_type)
ConsensusParamsView GetConsensusParams() const
ChainView(const btck_Chain *ptr)
BlockTreeEntry GetByHeight(int height) const
int32_t Height() const
bool Contains(BlockTreeEntry &entry) const
void SetWorkerThreads(int worker_threads)
ChainstateManagerOptions(const Context &context, std::string_view data_dir, std::string_view blocks_dir)
void UpdateBlockTreeDbInMemory(bool block_tree_db_in_memory)
void UpdateChainstateDbInMemory(bool chainstate_db_in_memory)
bool SetWipeDbs(bool wipe_block_tree, bool wipe_chainstate)
CoinApi()=default
uint32_t GetConfirmationHeight() const
TransactionOutputView GetOutput() const
Coin(const CoinView &view)
Coin(btck_Coin *coin)
CoinView(const btck_Coin *ptr)
ConsensusParamsView(const btck_ConsensusParams *ptr)
Context(ContextOptions &opts)
void SetValidationInterface(std::shared_ptr< T > validation_interface)
void SetChainParams(ChainParams &chain_params)
void SetNotifications(std::shared_ptr< T > notifications)
Handle & operator=(const Handle &other)
Handle & operator=(Handle &&other) noexcept
Handle(const ViewType &view)
Handle(Handle &&other) noexcept
const CType * get() const
Handle(const Handle &other)
std::random_access_iterator_tag iterator_category
auto operator-(difference_type n) const
auto operator+(difference_type n) const
Iterator(const Collection *ptr)
auto & operator-=(difference_type n)
Iterator()=default
const Collection * m_collection
auto operator<=>(const Iterator &other) const
std::random_access_iterator_tag iterator_concept
friend Iterator operator+(difference_type n, const Iterator &it)
Iterator(const Collection *ptr, size_t idx)
auto & operator+=(difference_type n)
auto operator-(const Iterator &other) const
bool operator==(const Iterator &other) const
std::ptrdiff_t difference_type
ValueType operator[](difference_type n) const
virtual void FatalErrorHandler(std::string_view error)
virtual void WarningSetHandler(Warning warning, std::string_view message)
virtual void BlockTipHandler(SynchronizationState state, BlockTreeEntry entry, double verification_progress)
virtual ~KernelNotifications()=default
virtual void ProgressHandler(std::string_view title, int progress_percent, bool resume_possible)
virtual void WarningUnsetHandler(Warning warning)
virtual void FlushErrorHandler(std::string_view error)
virtual void HeaderTipHandler(SynchronizationState state, int64_t height, int64_t timestamp, bool presync)
Logger(std::unique_ptr< T > log)
OutPointApi()=default
uint32_t index() const
OutPoint(const OutPointView &view)
OutPointView(const btck_TransactionOutPoint *ptr)
PrecomputedTransactionData(const Transaction &tx_to, std::span< const TransactionOutput > spent_outputs)
Iterator< Range, value_type > iterator
bool empty() const
const Container * m_container
value_type front() const
const_iterator cbegin() const
value_type operator[](size_t index) const
Range(const Container &container)
size_t size() const
const_iterator cend() const
std::ptrdiff_t difference_type
iterator begin() const
iterator end() const
value_type back() const
value_type at(size_t index) const
std::invoke_result_t< decltype(GetFunc), const Container &, size_t > value_type
std::vector< std::byte > ToBytes() const
bool Verify(int64_t amount, const Transaction &tx_to, const PrecomputedTransactionData *precomputed_txdata, unsigned int input_index, ScriptVerificationFlags flags, ScriptVerifyStatus &status) const
ScriptPubkey(std::span< const std::byte > raw)
ScriptPubkey(const ScriptPubkeyView &view)
ScriptPubkeyView(const btck_ScriptPubkey *ptr)
uint32_t GetLocktime() const
TransactionInputView GetInput(size_t index) const
TransactionOutputView GetOutput(size_t index) const
std::vector< std::byte > ToBytes() const
Transaction(std::span< const std::byte > raw_transaction)
Transaction(const TransactionView &view)
TransactionInput(const TransactionInputView &view)
TransactionInputView(const btck_TransactionInput *ptr)
ScriptPubkeyView GetScriptPubkey() const
TransactionOutput(const TransactionOutputView &view)
TransactionOutput(const ScriptPubkey &script_pubkey, int64_t amount)
TransactionOutputView(const btck_TransactionOutput *ptr)
CoinView GetCoin(size_t index) const
TransactionSpentOutputs(btck_TransactionSpentOutputs *transaction_spent_outputs)
TransactionSpentOutputs(const TransactionSpentOutputsView &view)
TransactionSpentOutputsView(const btck_TransactionSpentOutputs *ptr)
TransactionView(const btck_Transaction *ptr)
bool operator==(const TxidApi &other) const
std::array< std::byte, 32 > ToBytes() const
TxidApi()=default
bool operator!=(const TxidApi &other) const
Txid(const TxidView &view)
TxidView(const btck_Txid *ptr)
const CType * get() const
std::unique_ptr< CType, Deleter > m_ptr
virtual void PowValidBlock(BlockTreeEntry entry, Block block)
virtual void BlockConnected(Block block, BlockTreeEntry entry)
virtual ~ValidationInterface()=default
virtual void BlockDisconnected(Block block, BlockTreeEntry entry)
virtual void BlockChecked(Block block, BlockValidationStateView state)
const CType * get() const
const CType * m_ptr
View(const CType *ptr)
#define T(expected, seed, data)
constexpr T & operator|=(T &lhs, T rhs)
constexpr T & operator&=(T &lhs, T rhs)
constexpr T operator~(T value)
std::vector< std::byte > write_bytes(const T *object, int(*to_bytes)(const T *, btck_WriteBytes, void *))
void logging_set_options(const btck_LoggingOptions &logging_options)
constexpr T operator&(T lhs, T rhs)
constexpr T operator|(T lhs, T rhs)
void logging_set_level_category(LogCategory category, LogLevel level)
@ UNKNOWN_NEW_RULES_ACTIVATED
@ LARGE_WORK_INVALID_CHAIN
void logging_enable_category(LogCategory category)
constexpr T operator^(T lhs, T rhs)
void logging_disable_category(LogCategory category)
T check(T ptr)
void logging_disable()
constexpr T & operator^=(T &lhs, T rhs)
Definition: common.h:30
@ OK
The message verification was successful.
void operator()(CType *ptr) const noexcept
Options controlling the format of log messages.
A struct for holding the kernel notification callbacks.
void * user_data
Holds a user-defined opaque structure that is passed to the notification callbacks.
Holds the validation interface callbacks.
void * user_data
Holds a user-defined opaque structure that is passed to the validation interface callbacks.