Bitcoin Core 32.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 <chrono>
12#include <exception>
13#include <functional>
14#include <memory>
15#include <optional>
16#include <span>
17#include <stdexcept>
18#include <string>
19#include <string_view>
20#include <type_traits>
21#include <utility>
22#include <vector>
23
24namespace btck {
25
29 BLOCKSTORAGE = btck_LogCategory_BLOCKSTORAGE,
36 VALIDATION = btck_LogCategory_VALIDATION,
38};
39
40enum class LogLevel : btck_LogLevel {
44};
45
52};
53
58};
59
60enum class Warning : btck_Warning {
63};
64
69};
70
81};
82
97};
98
103};
104
115};
116
122};
123
124template <typename T>
125struct is_bitmask_enum : std::false_type {
126};
127
128template <>
129struct is_bitmask_enum<ScriptVerificationFlags> : std::true_type {
130};
131
132template <>
133struct is_bitmask_enum<BlockCheckFlags> : std::true_type {
134};
135
136template <typename T>
137concept BitmaskEnum = is_bitmask_enum<T>::value;
138
139template <BitmaskEnum T>
140constexpr T operator|(T lhs, T rhs)
141{
142 return static_cast<T>(
143 static_cast<std::underlying_type_t<T>>(lhs) | static_cast<std::underlying_type_t<T>>(rhs));
144}
145
146template <BitmaskEnum T>
147constexpr T operator&(T lhs, T rhs)
148{
149 return static_cast<T>(
150 static_cast<std::underlying_type_t<T>>(lhs) & static_cast<std::underlying_type_t<T>>(rhs));
151}
152
153template <BitmaskEnum T>
154constexpr T operator^(T lhs, T rhs)
155{
156 return static_cast<T>(
157 static_cast<std::underlying_type_t<T>>(lhs) ^ static_cast<std::underlying_type_t<T>>(rhs));
158}
159
160template <BitmaskEnum T>
161constexpr T operator~(T value)
162{
163 return static_cast<T>(~static_cast<std::underlying_type_t<T>>(value));
164}
165
166template <BitmaskEnum T>
167constexpr T& operator|=(T& lhs, T rhs)
168{
169 return lhs = lhs | rhs;
170}
171
172template <BitmaskEnum T>
173constexpr T& operator&=(T& lhs, T rhs)
174{
175 return lhs = lhs & rhs;
176}
177
178template <BitmaskEnum T>
179constexpr T& operator^=(T& lhs, T rhs)
180{
181 return lhs = lhs ^ rhs;
182}
183
184template <typename T>
185T check(T ptr)
186{
187 if (ptr == nullptr) {
188 throw std::runtime_error("failed to instantiate btck object");
189 }
190 return ptr;
191}
192
193template <typename Collection, typename ValueType, auto GetFunc>
195{
196public:
197 using iterator_category = std::random_access_iterator_tag;
198 using iterator_concept = std::random_access_iterator_tag;
199 using difference_type = std::ptrdiff_t;
200 using value_type = ValueType;
201
202private:
203 const Collection* m_collection;
204 size_t m_idx;
205
206public:
207 Iterator() = default;
208 Iterator(const Collection* ptr) : m_collection{ptr}, m_idx{0} {}
209 Iterator(const Collection* ptr, size_t idx) : m_collection{ptr}, m_idx{idx} {}
210
211 // This is just a view, so return a copy.
212 auto operator*() const { return std::invoke(GetFunc, *m_collection, m_idx); }
213
214 auto& operator++() { m_idx++; return *this; }
215 auto operator++(int) { Iterator tmp = *this; ++(*this); return tmp; }
216
217 auto& operator--() { m_idx--; return *this; }
218 auto operator--(int) { auto temp = *this; --m_idx; return temp; }
219
220 auto& operator+=(difference_type n) { m_idx += n; return *this; }
221 auto& operator-=(difference_type n) { m_idx -= n; return *this; }
222
223 auto operator+(difference_type n) const { return Iterator(m_collection, m_idx + n); }
224 auto operator-(difference_type n) const { return Iterator(m_collection, m_idx - n); }
225
226 auto operator-(const Iterator& other) const { return static_cast<difference_type>(m_idx) - static_cast<difference_type>(other.m_idx); }
227
228 ValueType operator[](difference_type n) const { return *(*this + n); }
229
230 auto operator<=>(const Iterator& other) const { return m_idx <=> other.m_idx; }
231
232 bool operator==(const Iterator& other) const { return m_collection == other.m_collection && m_idx == other.m_idx; }
233
234private:
235 friend Iterator operator+(difference_type n, const Iterator& it) { return it + n; }
236};
237
238template <typename Container, typename SizeFunc, typename GetFunc>
239concept IndexedContainer = requires(const Container& c, SizeFunc size_func, GetFunc get_func, std::size_t i) {
240 { std::invoke(size_func, c) } -> std::convertible_to<std::size_t>;
241 { std::invoke(get_func, c, i) }; // Return type is deduced
242};
243
244template <typename Container, auto SizeFunc, auto GetFunc>
245 requires IndexedContainer<Container, decltype(SizeFunc), decltype(GetFunc)>
246class Range
247{
248public:
249 using value_type = std::invoke_result_t<decltype(GetFunc), const Container&, size_t>;
250 using difference_type = std::ptrdiff_t;
253
254private:
255 const Container* m_container;
256
257public:
258 explicit Range(const Container& container) : m_container(&container)
259 {
260 static_assert(std::ranges::random_access_range<Range>);
261 }
262
263 iterator begin() const { return iterator(m_container, 0); }
264 iterator end() const { return iterator(m_container, size()); }
265
266 const_iterator cbegin() const { return begin(); }
267 const_iterator cend() const { return end(); }
268
269 size_t size() const { return std::invoke(SizeFunc, *m_container); }
270
271 bool empty() const { return size() == 0; }
272
273 value_type operator[](size_t index) const { return std::invoke(GetFunc, *m_container, index); }
274
275 value_type at(size_t index) const
276 {
277 if (index >= size()) {
278 throw std::out_of_range("Index out of range");
279 }
280 return (*this)[index];
281 }
282
283 value_type front() const { return (*this)[0]; }
284 value_type back() const { return (*this)[size() - 1]; }
285};
286
287#define MAKE_RANGE_METHOD(method_name, ContainerType, SizeFunc, GetFunc, container_expr) \
288 auto method_name() const & { \
289 return Range<ContainerType, SizeFunc, GetFunc>{container_expr}; \
290 } \
291 auto method_name() const && = delete;
292
293template <typename T>
294std::vector<std::byte> write_bytes(const T* object, int (*to_bytes)(const T*, btck_WriteBytes, void*))
295{
296 std::vector<std::byte> bytes;
297 struct UserData {
298 std::vector<std::byte>* bytes;
299 std::exception_ptr exception;
300 };
301 UserData user_data = UserData{.bytes = &bytes, .exception = nullptr};
302
303 constexpr auto const write = +[](const void* buffer, size_t len, void* user_data) -> int {
304 auto& data = *reinterpret_cast<UserData*>(user_data);
305 auto& bytes = *data.bytes;
306 try {
307 auto const* first = static_cast<const std::byte*>(buffer);
308 auto const* last = first + len;
309 bytes.insert(bytes.end(), first, last);
310 return 0;
311 } catch (...) {
312 data.exception = std::current_exception();
313 return -1;
314 }
315 };
316
317 if (to_bytes(object, write, &user_data) != 0) {
318 std::rethrow_exception(user_data.exception);
319 }
320 return bytes;
321}
322
323template <typename CType>
324class View
325{
326protected:
327 const CType* m_ptr;
328
329public:
330 explicit View(const CType* ptr) : m_ptr{check(ptr)} {}
331
332 const CType* get() const { return m_ptr; }
333};
334
335template <typename CType, CType* (*CopyFunc)(const CType*), void (*DestroyFunc)(CType*)>
337{
338protected:
339 CType* m_ptr;
340
341public:
342 explicit Handle(CType* ptr) : m_ptr{check(ptr)} {}
343
344 // Copy constructors
345 Handle(const Handle& other)
346 : m_ptr{check(CopyFunc(other.m_ptr))} {}
347 Handle& operator=(const Handle& other)
348 {
349 if (this != &other) {
350 Handle temp(other);
351 std::swap(m_ptr, temp.m_ptr);
352 }
353 return *this;
354 }
355
356 // Move constructors
357 Handle(Handle&& other) noexcept : m_ptr(other.m_ptr) { other.m_ptr = nullptr; }
358 Handle& operator=(Handle&& other) noexcept
359 {
360 if (this != &other) {
361 DestroyFunc(m_ptr);
362 m_ptr = std::exchange(other.m_ptr, nullptr);
363 }
364 return *this;
365 }
366
367 template <typename ViewType>
368 requires std::derived_from<ViewType, View<CType>>
369 Handle(const ViewType& view)
370 : Handle{CopyFunc(view.get())}
371 {
372 }
373
374 ~Handle() { DestroyFunc(m_ptr); }
375
376 CType* get() { return m_ptr; }
377 const CType* get() const { return m_ptr; }
378};
379
380template <typename CType, void (*DestroyFunc)(CType*)>
382{
383protected:
384 struct Deleter {
385 void operator()(CType* ptr) const noexcept
386 {
387 if (ptr) DestroyFunc(ptr);
388 }
389 };
390 std::unique_ptr<CType, Deleter> m_ptr;
391
392public:
393 explicit UniqueHandle(CType* ptr) : m_ptr{check(ptr)} {}
394
395 CType* get() { return m_ptr.get(); }
396 const CType* get() const { return m_ptr.get(); }
397};
398
400class Transaction;
401class TransactionOutput;
403
404template <typename Derived>
406{
407private:
408 auto impl() const
409 {
410 return static_cast<const Derived*>(this)->get();
411 }
412
413 friend Derived;
414 ScriptPubkeyApi() = default;
415
416public:
417 bool Verify(int64_t amount,
418 const Transaction& tx_to,
419 const PrecomputedTransactionData* precomputed_txdata,
420 unsigned int input_index,
422 ScriptVerifyStatus& status) const;
423
424 std::vector<std::byte> ToBytes() const
425 {
427 }
428};
429
430class ScriptPubkeyView : public View<btck_ScriptPubkey>, public ScriptPubkeyApi<ScriptPubkeyView>
431{
432public:
433 explicit ScriptPubkeyView(const btck_ScriptPubkey* ptr) : View{ptr} {}
434};
435
436class ScriptPubkey : public Handle<btck_ScriptPubkey, btck_script_pubkey_copy, btck_script_pubkey_destroy>, public ScriptPubkeyApi<ScriptPubkey>
437{
438public:
439 explicit ScriptPubkey(std::span<const std::byte> raw)
440 : Handle{btck_script_pubkey_create(raw.data(), raw.size())} {}
441
443 : Handle(view) {}
444};
445
446template <typename Derived>
448{
449private:
450 auto impl() const
451 {
452 return static_cast<const Derived*>(this)->get();
453 }
454
455 friend Derived;
457
458public:
459 int64_t Amount() const
460 {
462 }
463
465 {
467 }
468};
469
470class TransactionOutputView : public View<btck_TransactionOutput>, public TransactionOutputApi<TransactionOutputView>
471{
472public:
473 explicit TransactionOutputView(const btck_TransactionOutput* ptr) : View{ptr} {}
474};
475
476class TransactionOutput : public Handle<btck_TransactionOutput, btck_transaction_output_copy, btck_transaction_output_destroy>, public TransactionOutputApi<TransactionOutput>
477{
478public:
479 explicit TransactionOutput(const ScriptPubkey& script_pubkey, int64_t amount)
480 : Handle{btck_transaction_output_create(script_pubkey.get(), amount)} {}
481
483 : Handle(view) {}
484};
485
486template <typename Derived>
488{
489private:
490 auto impl() const
491 {
492 return static_cast<const Derived*>(this)->get();
493 }
494
495 friend Derived;
496 TxidApi() = default;
497
498public:
499 bool operator==(const TxidApi& other) const
500 {
501 return btck_txid_equals(impl(), other.impl()) != 0;
502 }
503
504 bool operator!=(const TxidApi& other) const
505 {
506 return btck_txid_equals(impl(), other.impl()) == 0;
507 }
508
509 std::array<std::byte, 32> ToBytes() const
510 {
511 std::array<std::byte, 32> hash;
512 btck_txid_to_bytes(impl(), reinterpret_cast<unsigned char*>(hash.data()));
513 return hash;
514 }
515};
516
517class TxidView : public View<btck_Txid>, public TxidApi<TxidView>
518{
519public:
520 explicit TxidView(const btck_Txid* ptr) : View{ptr} {}
521};
522
523class Txid : public Handle<btck_Txid, btck_txid_copy, btck_txid_destroy>, public TxidApi<Txid>
524{
525public:
526 Txid(const TxidView& view)
527 : Handle(view) {}
528};
529
530template <typename Derived>
532{
533private:
534 auto impl() const
535 {
536 return static_cast<const Derived*>(this)->get();
537 }
538
539 friend Derived;
540 WtxidApi() = default;
541
542public:
543 bool operator==(const WtxidApi& other) const
544 {
545 return btck_wtxid_equals(impl(), other.impl()) != 0;
546 }
547
548 bool operator!=(const WtxidApi& other) const
549 {
550 return btck_wtxid_equals(impl(), other.impl()) == 0;
551 }
552
553 std::array<std::byte, 32> ToBytes() const
554 {
555 std::array<std::byte, 32> hash;
556 btck_wtxid_to_bytes(impl(), reinterpret_cast<unsigned char*>(hash.data()));
557 return hash;
558 }
559};
560
561class WtxidView : public View<btck_Wtxid>, public WtxidApi<WtxidView>
562{
563public:
564 explicit WtxidView(const btck_Wtxid* ptr) : View{ptr} {}
565};
566
567class Wtxid : public Handle<btck_Wtxid, btck_wtxid_copy, btck_wtxid_destroy>, public WtxidApi<Wtxid>
568{
569public:
570 Wtxid(const WtxidView& view)
571 : Handle(view) {}
572};
573
574template <typename Derived>
576{
577private:
578 auto impl() const
579 {
580 return static_cast<const Derived*>(this)->get();
581 }
582
583 friend Derived;
584 OutPointApi() = default;
585
586public:
587 uint32_t index() const
588 {
590 }
591
593 {
595 }
596};
597
598class OutPointView : public View<btck_TransactionOutPoint>, public OutPointApi<OutPointView>
599{
600public:
601 explicit OutPointView(const btck_TransactionOutPoint* ptr) : View{ptr} {}
602};
603
604class OutPoint : public Handle<btck_TransactionOutPoint, btck_transaction_out_point_copy, btck_transaction_out_point_destroy>, public OutPointApi<OutPoint>
605{
606public:
608 : Handle(view) {}
609};
610
611template <typename Derived>
613{
614private:
615 auto impl() const
616 {
617 return static_cast<const Derived*>(this)->get();
618 }
619
620 friend Derived;
621 WitnessStackApi() = default;
622
623public:
624 size_t CountItems() const
625 {
627 }
628
629 std::vector<std::byte> GetItem(size_t index) const
630 {
631 struct Item { const btck_WitnessStack* stack; size_t index; };
632 Item item{impl(), index};
633 return write_bytes(&item, +[](const Item* c, btck_WriteBytes w, void* ud) {
634 return btck_witness_stack_get_item_at(c->stack, c->index, w, ud);
635 });
636 }
637
639};
640
641class WitnessStackView : public View<btck_WitnessStack>, public WitnessStackApi<WitnessStackView>
642{
643public:
644 explicit WitnessStackView(const btck_WitnessStack* ptr) : View{ptr} {}
645};
646
647class WitnessStack : public Handle<btck_WitnessStack, btck_witness_stack_copy, btck_witness_stack_destroy>, public WitnessStackApi<WitnessStack>
648{
649public:
651 : Handle(view) {}
652};
653
654template <typename Derived>
656{
657private:
658 auto impl() const
659 {
660 return static_cast<const Derived*>(this)->get();
661 }
662
663 friend Derived;
665
666public:
668 {
670 }
671
672 uint32_t GetSequence() const
673 {
675 }
676
678 {
680 }
681
682 std::vector<std::byte> GetScriptSig() const
683 {
685 }
686};
687
688class TransactionInputView : public View<btck_TransactionInput>, public TransactionInputApi<TransactionInputView>
689{
690public:
691 explicit TransactionInputView(const btck_TransactionInput* ptr) : View{ptr} {}
692};
693
694class TransactionInput : public Handle<btck_TransactionInput, btck_transaction_input_copy, btck_transaction_input_destroy>, public TransactionInputApi<TransactionInput>
695{
696public:
698 : Handle(view) {}
699};
700
701template <typename Derived>
703{
704private:
705 auto impl() const
706 {
707 return static_cast<const Derived*>(this)->get();
708 }
709
710public:
711 size_t CountOutputs() const
712 {
714 }
715
716 size_t CountInputs() const
717 {
719 }
720
722 {
724 }
725
726 TransactionInputView GetInput(size_t index) const
727 {
729 }
730
731 uint32_t GetVersion() const
732 {
734 }
735
736 uint32_t GetLocktime() const
737 {
739 }
740
741 bool HasWitness() const
742 {
743 return btck_transaction_has_witness(impl()) != 0;
744 }
745
747 {
749 }
750
752 {
754 }
755
757
759
760 std::vector<std::byte> ToBytes() const
761 {
763 }
764};
765
766class TransactionView : public View<btck_Transaction>, public TransactionApi<TransactionView>
767{
768public:
769 explicit TransactionView(const btck_Transaction* ptr) : View{ptr} {}
770};
771
772class Transaction : public Handle<btck_Transaction, btck_transaction_copy, btck_transaction_destroy>, public TransactionApi<Transaction>
773{
774public:
775 explicit Transaction(std::span<const std::byte> raw_transaction)
776 : Handle{btck_transaction_create(raw_transaction.data(), raw_transaction.size())} {}
777
779 : Handle{view} {}
780};
781
782class PrecomputedTransactionData : public Handle<btck_PrecomputedTransactionData, btck_precomputed_transaction_data_copy, btck_precomputed_transaction_data_destroy>
783{
784public:
785 explicit PrecomputedTransactionData(const Transaction& tx_to, std::span<const TransactionOutput> spent_outputs)
787 tx_to.get(),
788 reinterpret_cast<const btck_TransactionOutput**>(
789 const_cast<TransactionOutput*>(spent_outputs.data())),
790 spent_outputs.size())} {}
791};
792
793template <typename Derived>
795 const Transaction& tx_to,
796 const PrecomputedTransactionData* precomputed_txdata,
797 unsigned int input_index,
799 ScriptVerifyStatus& status) const
800{
801 auto result = btck_script_pubkey_verify(
802 impl(),
803 amount,
804 tx_to.get(),
805 precomputed_txdata ? precomputed_txdata->get() : nullptr,
806 input_index,
808 reinterpret_cast<btck_ScriptVerifyStatus*>(&status));
809 return result == 1;
810}
811
812template <typename Derived>
814{
815private:
816 auto impl() const
817 {
818 return static_cast<const Derived*>(this)->get();
819 }
820
821public:
822 bool operator==(const Derived& other) const
823 {
824 return btck_block_hash_equals(impl(), other.get()) != 0;
825 }
826
827 bool operator!=(const Derived& other) const
828 {
829 return btck_block_hash_equals(impl(), other.get()) == 0;
830 }
831
832 std::array<std::byte, 32> ToBytes() const
833 {
834 std::array<std::byte, 32> hash;
835 btck_block_hash_to_bytes(impl(), reinterpret_cast<unsigned char*>(hash.data()));
836 return hash;
837 }
838};
839
840class BlockHashView : public View<btck_BlockHash>, public BlockHashApi<BlockHashView>
841{
842public:
843 explicit BlockHashView(const btck_BlockHash* ptr) : View{ptr} {}
844};
845
846class BlockHash : public Handle<btck_BlockHash, btck_block_hash_copy, btck_block_hash_destroy>, public BlockHashApi<BlockHash>
847{
848public:
849 explicit BlockHash(const std::array<std::byte, 32>& hash)
850 : Handle{btck_block_hash_create(reinterpret_cast<const unsigned char*>(hash.data()))} {}
851
852 explicit BlockHash(btck_BlockHash* hash)
853 : Handle{hash} {}
854
856 : Handle{view} {}
857};
858
859template <typename Derived>
861{
862private:
863 auto impl() const
864 {
865 return static_cast<const Derived*>(this)->get();
866 }
867
868 friend Derived;
869 BlockHeaderApi() = default;
870
871public:
873 {
875 }
876
878 {
880 }
881
882 std::array<std::byte, 32> MerkleRoot() const
883 {
884 std::array<std::byte, 32> merkle_root;
885 btck_block_header_get_merkle_root(impl(), reinterpret_cast<unsigned char*>(merkle_root.data()));
886 return merkle_root;
887 }
888
889 uint32_t Timestamp() const
890 {
892 }
893
894 uint32_t Bits() const
895 {
897 }
898
899 int32_t Version() const
900 {
902 }
903
904 uint32_t Nonce() const
905 {
907 }
908
909 std::array<std::byte, 80> ToBytes() const
910 {
911 std::array<std::byte, 80> header;
912 int res{btck_block_header_to_bytes(impl(), reinterpret_cast<unsigned char*>(header.data()))};
913 if (res != 0) {
914 throw std::runtime_error("Failed to serialize block header");
915 }
916 return header;
917 }
918};
919
920class BlockHeaderView : public View<btck_BlockHeader>, public BlockHeaderApi<BlockHeaderView>
921{
922public:
923 explicit BlockHeaderView(const btck_BlockHeader* ptr) : View{ptr} {}
924};
925
926class BlockHeader : public Handle<btck_BlockHeader, btck_block_header_copy, btck_block_header_destroy>, public BlockHeaderApi<BlockHeader>
927{
928public:
929 explicit BlockHeader(std::span<const std::byte> raw_header)
930 : Handle{btck_block_header_create(reinterpret_cast<const unsigned char*>(raw_header.data()), raw_header.size())} {}
931
933 : Handle{view} {}
934
936 : Handle{header} {}
937};
938
939class ConsensusParamsView : public View<btck_ConsensusParams>
940{
941public:
942 explicit ConsensusParamsView(const btck_ConsensusParams* ptr) : View{ptr} {}
943};
944
945class Block : public Handle<btck_Block, btck_block_copy, btck_block_destroy>
946{
947public:
948 Block(const std::span<const std::byte> raw_block)
949 : Handle{btck_block_create(raw_block.data(), raw_block.size())}
950 {
951 }
952
953 Block(btck_Block* block) : Handle{block} {}
954
955 size_t CountTransactions() const
956 {
958 }
959
960 TransactionView GetTransaction(size_t index) const
961 {
963 }
964
965 bool Check(const ConsensusParamsView& consensus_params,
967 BlockValidationState& state) const;
968
970
972 {
974 }
975
977 {
979 }
980
981 std::vector<std::byte> ToBytes() const
982 {
984 }
985};
986
987inline void logging_disable()
988{
990}
991
992inline void logging_set_options(const btck_LoggingOptions& logging_options)
993{
994 btck_logging_set_options(logging_options);
995}
996
998{
999 btck_logging_set_level_category(static_cast<btck_LogCategory>(category), static_cast<btck_LogLevel>(level));
1000}
1001
1003{
1004 btck_logging_enable_category(static_cast<btck_LogCategory>(category));
1005}
1006
1008{
1009 btck_logging_disable_category(static_cast<btck_LogCategory>(category));
1010}
1011
1012template <typename T>
1013concept Log = requires(T a, std::string_view message) {
1014 { a.LogMessage(message) } -> std::same_as<void>;
1015};
1016
1017template <Log T>
1018class Logger : UniqueHandle<btck_LoggingConnection, btck_logging_connection_destroy>
1019{
1020public:
1021 Logger(std::unique_ptr<T> log)
1023 +[](void* user_data, const char* message, size_t message_len) { static_cast<T*>(user_data)->LogMessage({message, message_len}); },
1024 log.release(),
1025 +[](void* user_data) { delete static_cast<T*>(user_data); })}
1026 {
1027 }
1028};
1029
1030class BlockTreeEntry : public View<btck_BlockTreeEntry>
1031{
1032public:
1034 : View{entry}
1035 {
1036 }
1037
1038 bool operator==(const BlockTreeEntry& other) const
1039 {
1040 return btck_block_tree_entry_equals(get(), other.get()) != 0;
1041 }
1042
1043 std::optional<BlockTreeEntry> GetPrevious() const
1044 {
1045 auto entry{btck_block_tree_entry_get_previous(get())};
1046 if (!entry) return std::nullopt;
1047 return entry;
1048 }
1049
1050 int32_t GetHeight() const
1051 {
1053 }
1054
1056 {
1058 }
1059
1061 {
1063 }
1064
1065 BlockTreeEntry GetAncestor(int32_t height) const
1066 {
1068 }
1069
1070};
1071
1073{
1074public:
1075 virtual ~KernelNotifications() = default;
1076
1077 virtual void BlockTipHandler(SynchronizationState state, BlockTreeEntry entry, double verification_progress) {}
1078
1079 virtual void HeaderTipHandler(SynchronizationState state, int64_t height, int64_t timestamp, bool presync) {}
1080
1081 virtual void ProgressHandler(std::string_view title, int progress_percent, bool resume_possible) {}
1082
1083 virtual void WarningSetHandler(Warning warning, std::string_view message) {}
1084
1085 virtual void WarningUnsetHandler(Warning warning) {}
1086
1087 virtual void FlushErrorHandler(std::string_view error) {}
1088
1089 virtual void FatalErrorHandler(std::string_view error) {}
1090};
1091
1092template <typename Derived>
1094{
1095private:
1096 auto impl() const
1097 {
1098 return static_cast<const Derived*>(this)->get();
1099 }
1100
1101 friend Derived;
1103
1104public:
1106 {
1108 }
1109
1111 {
1113 }
1114};
1115
1116class BlockValidationStateView : public View<btck_BlockValidationState>, public BlockValidationStateApi<BlockValidationStateView>
1117{
1118public:
1120};
1121
1122class BlockValidationState : public Handle<btck_BlockValidationState, btck_block_validation_state_copy, btck_block_validation_state_destroy>, public BlockValidationStateApi<BlockValidationState>
1123{
1124public:
1126
1128
1130};
1131
1132inline bool Block::Check(const ConsensusParamsView& consensus_params,
1134 BlockValidationState& state) const
1135{
1136 return btck_block_check(get(), consensus_params.get(), static_cast<btck_BlockCheckFlags>(flags), state.get()) == 1;
1137}
1138
1139class TxValidationState : public UniqueHandle<btck_TxValidationState, btck_tx_validation_state_destroy>
1140{
1141public:
1142 using UniqueHandle::UniqueHandle; // inherit ctor
1144
1146 {
1148 }
1149
1151 {
1153 }
1154};
1155
1156inline bool CheckTransaction(const Transaction& tx, TxValidationState& state)
1157{
1158 return btck_transaction_check(tx.get(), state.get()) == 1;
1159}
1160
1162{
1163public:
1164 virtual ~ValidationInterface() = default;
1165
1166 virtual void BlockChecked(Block block, BlockValidationStateView state) {}
1167
1168 virtual void PowValidBlock(BlockTreeEntry entry, Block block) {}
1169
1170 virtual void BlockConnected(Block block, BlockTreeEntry entry) {}
1171
1172 virtual void BlockDisconnected(Block block, BlockTreeEntry entry) {}
1173};
1174
1175class ChainParams : public Handle<btck_ChainParameters, btck_chain_parameters_copy, btck_chain_parameters_destroy>
1176{
1177public:
1178 explicit ChainParams(ChainType chain_type)
1179 : Handle{btck_chain_parameters_create(static_cast<btck_ChainType>(chain_type))} {}
1180
1181 explicit ChainParams(std::span<const std::byte> signet_challenge)
1182 : Handle{btck_chain_parameters_create_signet(signet_challenge.data(), signet_challenge.size())} {}
1183
1185 {
1187 }
1188};
1189
1190class ContextOptions : public UniqueHandle<btck_ContextOptions, btck_context_options_destroy>
1191{
1192public:
1194
1195 void SetChainParams(ChainParams& chain_params)
1196 {
1197 btck_context_options_set_chainparams(get(), chain_params.get());
1198 }
1199
1200 template <typename T>
1201 void SetNotifications(std::shared_ptr<T> notifications)
1202 {
1203 static_assert(std::is_base_of_v<KernelNotifications, T>);
1204 auto heap_notifications = std::make_unique<std::shared_ptr<T>>(std::move(notifications));
1205 using user_type = std::shared_ptr<T>*;
1207 get(),
1209 .user_data = heap_notifications.release(),
1210 .user_data_destroy = +[](void* user_data) { delete static_cast<user_type>(user_data); },
1211 .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); },
1212 .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); },
1213 .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); },
1214 .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}); },
1215 .warning_unset = +[](void* user_data, btck_Warning warning) { (*static_cast<user_type>(user_data))->WarningUnsetHandler(static_cast<Warning>(warning)); },
1216 .flush_error = +[](void* user_data, const char* error, size_t error_len) { (*static_cast<user_type>(user_data))->FlushErrorHandler({error, error_len}); },
1217 .fatal_error = +[](void* user_data, const char* error, size_t error_len) { (*static_cast<user_type>(user_data))->FatalErrorHandler({error, error_len}); },
1218 });
1219 }
1220
1221 template <typename T>
1222 void SetValidationInterface(std::shared_ptr<T> validation_interface)
1223 {
1224 static_assert(std::is_base_of_v<ValidationInterface, T>);
1225 auto heap_vi = std::make_unique<std::shared_ptr<T>>(std::move(validation_interface));
1226 using user_type = std::shared_ptr<T>*;
1228 get(),
1230 .user_data = heap_vi.release(),
1231 .user_data_destroy = +[](void* user_data) { delete static_cast<user_type>(user_data); },
1232 .block_checked = +[](void* user_data, btck_Block* block, const btck_BlockValidationState* state) { (*static_cast<user_type>(user_data))->BlockChecked(Block{block}, BlockValidationStateView{state}); },
1233 .pow_valid_block = +[](void* user_data, btck_Block* block, const btck_BlockTreeEntry* entry) { (*static_cast<user_type>(user_data))->PowValidBlock(BlockTreeEntry{entry}, Block{block}); },
1234 .block_connected = +[](void* user_data, btck_Block* block, const btck_BlockTreeEntry* entry) { (*static_cast<user_type>(user_data))->BlockConnected(Block{block}, BlockTreeEntry{entry}); },
1235 .block_disconnected = +[](void* user_data, btck_Block* block, const btck_BlockTreeEntry* entry) { (*static_cast<user_type>(user_data))->BlockDisconnected(Block{block}, BlockTreeEntry{entry}); },
1236 });
1237 }
1238};
1239
1240class Context : public Handle<btck_Context, btck_context_copy, btck_context_destroy>
1241{
1242public:
1244 : Handle{btck_context_create(opts.get())} {}
1245
1248
1250 {
1251 return btck_context_interrupt(get()) == 0;
1252 }
1253};
1254
1255class ChainstateManagerOptions : public UniqueHandle<btck_ChainstateManagerOptions, btck_chainstate_manager_options_destroy>
1256{
1257public:
1258 ChainstateManagerOptions(const Context& context, std::string_view data_dir, std::string_view blocks_dir)
1260 context.get(), data_dir.data(), data_dir.length(), blocks_dir.data(), blocks_dir.length())}
1261 {
1262 }
1263
1264 void SetWorkerThreads(int worker_threads)
1265 {
1267 }
1268
1269 bool SetDatabaseCacheBytes(uint64_t database_cache_bytes)
1270 {
1271 return btck_chainstate_manager_options_set_database_cache_bytes(get(), database_cache_bytes) == 0;
1272 }
1273
1274 bool SetWipeDbs(bool wipe_block_tree, bool wipe_chainstate)
1275 {
1276 return btck_chainstate_manager_options_set_wipe_dbs(get(), wipe_block_tree, wipe_chainstate) == 0;
1277 }
1278
1279 void UpdateBlockTreeDbInMemory(bool block_tree_db_in_memory)
1280 {
1282 }
1283
1284 void UpdateChainstateDbInMemory(bool chainstate_db_in_memory)
1285 {
1287 }
1288};
1289
1290class ChainView : public View<btck_Chain>
1291{
1292public:
1293 explicit ChainView(const btck_Chain* ptr) : View{ptr} {}
1294
1295 int32_t Height() const
1296 {
1297 return btck_chain_get_height(get());
1298 }
1299
1300 int32_t CountEntries() const
1301 {
1302 return btck_chain_get_height(get()) + 1;
1303 }
1304
1305 BlockTreeEntry GetByHeight(int32_t height) const
1306 {
1307 auto index{btck_chain_get_by_height(get(), height)};
1308 if (!index) throw std::runtime_error("No entry in the chain at the provided height");
1309 return index;
1310 }
1311
1312 bool Contains(BlockTreeEntry& entry) const
1313 {
1314 return btck_chain_contains(get(), entry.get());
1315 }
1316
1317 MAKE_RANGE_METHOD(Entries, ChainView, &ChainView::CountEntries, &ChainView::GetByHeight, *this)
1318};
1319
1320template <typename Derived>
1322{
1323private:
1324 auto impl() const
1325 {
1326 return static_cast<const Derived*>(this)->get();
1327 }
1328
1329 friend Derived;
1330 CoinApi() = default;
1331
1332public:
1333 uint32_t GetConfirmationHeight() const { return btck_coin_confirmation_height(impl()); }
1334
1335 bool IsCoinbase() const { return btck_coin_is_coinbase(impl()) == 1; }
1336
1338 {
1340 }
1341};
1342
1343class CoinView : public View<btck_Coin>, public CoinApi<CoinView>
1344{
1345public:
1346 explicit CoinView(const btck_Coin* ptr) : View{ptr} {}
1347};
1348
1349class Coin : public Handle<btck_Coin, btck_coin_copy, btck_coin_destroy>, public CoinApi<Coin>
1350{
1351public:
1352 Coin(btck_Coin* coin) : Handle{coin} {}
1353
1354 Coin(const CoinView& view) : Handle{view} {}
1355};
1356
1357template <typename Derived>
1359{
1360private:
1361 auto impl() const
1362 {
1363 return static_cast<const Derived*>(this)->get();
1364 }
1365
1366 friend Derived;
1368
1369public:
1370 size_t Count() const
1371 {
1373 }
1374
1375 CoinView GetCoin(size_t index) const
1376 {
1378 }
1379
1381};
1382
1383class TransactionSpentOutputsView : public View<btck_TransactionSpentOutputs>, public TransactionSpentOutputsApi<TransactionSpentOutputsView>
1384{
1385public:
1387};
1388
1389class TransactionSpentOutputs : public Handle<btck_TransactionSpentOutputs, btck_transaction_spent_outputs_copy, btck_transaction_spent_outputs_destroy>,
1390 public TransactionSpentOutputsApi<TransactionSpentOutputs>
1391{
1392public:
1393 TransactionSpentOutputs(btck_TransactionSpentOutputs* transaction_spent_outputs) : Handle{transaction_spent_outputs} {}
1394
1396};
1397
1398class BlockSpentOutputs : public Handle<btck_BlockSpentOutputs, btck_block_spent_outputs_copy, btck_block_spent_outputs_destroy>
1399{
1400public:
1402 : Handle{block_spent_outputs}
1403 {
1404 }
1405
1406 size_t Count() const
1407 {
1408 return btck_block_spent_outputs_count(get());
1409 }
1410
1412 {
1414 }
1415
1416 MAKE_RANGE_METHOD(TxsSpentOutputs, BlockSpentOutputs, &BlockSpentOutputs::Count, &BlockSpentOutputs::GetTxSpentOutputs, *this)
1417};
1418
1419class ChainMan : UniqueHandle<btck_ChainstateManager, btck_chainstate_manager_destroy>
1420{
1421public:
1422 ChainMan(const Context& context, const ChainstateManagerOptions& chainman_opts)
1423 : UniqueHandle{btck_chainstate_manager_create(chainman_opts.get())}
1424 {
1425 }
1426
1427 bool ImportBlocks(const std::span<const std::string> paths)
1428 {
1429 std::vector<const char*> c_paths;
1430 std::vector<size_t> c_paths_lens;
1431 c_paths.reserve(paths.size());
1432 c_paths_lens.reserve(paths.size());
1433 for (const auto& path : paths) {
1434 c_paths.push_back(path.c_str());
1435 c_paths_lens.push_back(path.length());
1436 }
1437
1438 return btck_chainstate_manager_import_blocks(get(), c_paths.data(), c_paths_lens.data(), c_paths.size()) == 0;
1439 }
1440
1441 bool ProcessBlock(const Block& block, bool* new_block)
1442 {
1443 int _new_block;
1444 int res = btck_chainstate_manager_process_block(get(), block.get(), &_new_block);
1445 if (new_block) *new_block = _new_block == 1;
1446 return res == 0;
1447 }
1448
1450 {
1451 auto state = btck_chainstate_manager_process_block_header(get(), header.get());
1452 return BlockValidationState{state};
1453 }
1454
1456 {
1458 }
1459
1460 std::optional<BlockTreeEntry> GetBlockTreeEntry(const BlockHash& block_hash) const
1461 {
1462 auto entry{btck_chainstate_manager_get_block_tree_entry_by_hash(get(), block_hash.get())};
1463 if (!entry) return std::nullopt;
1464 return entry;
1465 }
1466
1468 {
1470 }
1471
1472 std::optional<Block> ReadBlock(const BlockTreeEntry& entry) const
1473 {
1474 auto block{btck_block_read(get(), entry.get())};
1475 if (!block) return std::nullopt;
1476 return block;
1477 }
1478
1480 {
1481 return btck_block_spent_outputs_read(get(), entry.get());
1482 }
1483};
1484
1485inline void set_mock_time(std::chrono::seconds timestamp)
1486{
1487 if (btck_set_mock_time(timestamp.count()) != 0) {
1488 throw std::runtime_error("timestamp out of range");
1489 }
1490}
1491
1492} // namespace btck
1493
1494#endif // BITCOIN_KERNEL_BITCOINKERNEL_WRAPPER_H
int flags
Definition: bitcoin-tx.cpp:531
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)
btck_TxValidationResult btck_tx_validation_state_get_tx_validation_result(const btck_TxValidationState *state_)
Returns the validation result from an opaque btck_TxValidationState pointer.
int btck_chainstate_manager_import_blocks(btck_ChainstateManager *chainman, const char **block_file_paths_data, size_t *block_file_paths_lens, size_t block_file_paths_data_len)
Triggers the start of a reindex if the wipe options were previously set for the chainstate manager.
const btck_Coin * btck_transaction_spent_outputs_get_coin_at(const btck_TransactionSpentOutputs *transaction_spent_outputs, size_t coin_index)
Returns a coin contained in the transaction spent outputs at a certain index.
const btck_TransactionInput * btck_transaction_get_input_at(const btck_Transaction *transaction, size_t input_index)
Get the transaction input at the provided index.
void btck_logging_enable_category(btck_LogCategory category)
Enable a specific log category for the global internal logger.
uint32_t btck_coin_confirmation_height(const btck_Coin *coin)
Returns the block height where the transaction that created this coin was included in.
void btck_context_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.
const btck_BlockTreeEntry * btck_block_tree_entry_get_ancestor(const btck_BlockTreeEntry *block_tree_entry, int32_t height)
Return the ancestor of a btck_BlockTreeEntry at the given height.
int64_t btck_transaction_output_get_amount(const btck_TransactionOutput *output)
Get the amount in the output.
void btck_chainstate_manager_options_update_chainstate_db_in_memory(btck_ChainstateManagerOptions *chainman_opts, int chainstate_db_in_memory)
Sets chainstate db in memory in the options.
uint32_t btck_block_header_get_nonce(const btck_BlockHeader *header)
Get the nonce from btck_BlockHeader.
const btck_Txid * btck_transaction_out_point_get_txid(const btck_TransactionOutPoint *out_point)
Get the txid from the transaction out point.
void btck_logging_disable_category(btck_LogCategory category)
Disable a specific log category for the global internal logger.
btck_BlockValidationState * btck_block_validation_state_create()
Create a new btck_BlockValidationState.
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.
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.
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.
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.
int btck_block_tree_entry_equals(const btck_BlockTreeEntry *entry1, const btck_BlockTreeEntry *entry2)
uint32_t btck_block_header_get_bits(const btck_BlockHeader *header)
Get the nBits difficulty target from btck_BlockHeader.
const btck_Wtxid * btck_transaction_get_wtxid(const btck_Transaction *transaction)
Get the wtxid of a transaction.
int32_t btck_chain_get_height(const btck_Chain *chain)
Return the height of the tip of the chain.
btck_BlockHeader * btck_block_get_header(const btck_Block *block)
Get the btck_BlockHeader from the block.
size_t btck_block_count_transactions(const btck_Block *block)
Count the number of transactions contained in a block.
void btck_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.
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.
int btck_transaction_check(const btck_Transaction *tx, btck_TxValidationState *validation_state)
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.
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])
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.
const btck_TransactionOutput * btck_transaction_get_output_at(const btck_Transaction *transaction, size_t output_index)
Get the transaction outputs at the provided index.
const btck_BlockTreeEntry * btck_chain_get_by_height(const btck_Chain *chain, int32_t height)
Retrieve a block tree entry by its height in the currently active chain.
void btck_logging_set_level_category(btck_LogCategory category, btck_LogLevel level)
Set the log level of the global internal logger.
void btck_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])
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.
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_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_BlockValidationState * btck_chainstate_manager_process_block_header(btck_ChainstateManager *chainstate_manager, const btck_BlockHeader *header)
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.
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_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.
btck_TxValidationState * btck_tx_validation_state_create()
Create a new btck_TxValidationState.
const btck_Transaction * btck_block_get_transaction_at(const btck_Block *block, size_t index)
Get the transaction at the provided index.
const btck_Chain * btck_chainstate_manager_get_active_chain(const btck_ChainstateManager *chainman)
Returns the best known currently active chain.
btck_ChainstateManagerOptions * btck_chainstate_manager_options_create(const btck_Context *context, const char *data_dir, size_t data_dir_len, const char *blocks_dir, size_t blocks_dir_len)
Create options for the chainstate manager.
btck_BlockValidationResult btck_block_validation_state_get_block_validation_result(const btck_BlockValidationState *block_validation_state_)
Returns the validation result from an opaque btck_BlockValidationState pointer.
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_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_ScriptVerificationFlags_CHECKLOCKTIMEVERIFY
enable CHECKLOCKTIMEVERIFY (BIP65)
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_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_TxValidationResult_NO_MEMPOOL
this node does not have a mempool so can't validate the transaction
#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_TxValidationResult_WITNESS_STRIPPED
transaction is missing a witness
#define btck_ScriptVerificationFlags_NONE
#define btck_LogCategory_RAND
#define btck_TxValidationResult_INPUTS_NOT_STANDARD
inputs (covered by txid) failed policy rules
#define btck_BlockValidationResult_CONSENSUS
invalid by consensus rules (excluding any below reasons)
#define btck_BlockValidationResult_UNSET
initial value. Block has not yet been rejected
#define btck_TxValidationResult_UNSET
initial value. Tx has not yet been rejected
#define btck_SynchronizationState_POST_INIT
#define btck_BlockValidationResult_MISSING_PREV
We don't have the previous block the checked one is built on.
#define btck_LogCategory_ALL
uint8_t btck_ScriptVerifyStatus
A collection of status codes that may be issued by the script verify function.
#define btck_ValidationMode_INTERNAL_ERROR
#define btck_TxValidationResult_WITNESS_MUTATED
witness may have been malleated or is prior to SegWit activation
uint8_t btck_LogCategory
A collection of logging categories that may be encountered by kernel code.
#define btck_ValidationMode_INVALID
#define btck_ChainType_SIGNET
#define btck_TxValidationResult_CONSENSUS
invalid by consensus rules
uint32_t btck_BlockCheckFlags
Bitflags to control context-free block checks (optional).
#define btck_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_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_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_TxValidationResult_MEMPOOL_POLICY
violated mempool's fee/size/descendant/RBF/etc limits
#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, 32 > MerkleRoot() 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
BlockTreeEntry GetAncestor(int32_t height) const
BlockHashView GetHash() const
BlockHeader GetHeader() const
ValidationMode GetValidationMode() const
BlockValidationResult GetBlockValidationResult() const
BlockValidationState(const BlockValidationStateView &view)
BlockValidationState(btck_BlockValidationState *state)
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
BlockValidationState ProcessBlockHeader(const BlockHeader &header)
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(std::span< const std::byte > signet_challenge)
ChainParams(ChainType chain_type)
ConsensusParamsView GetConsensusParams() const
ChainView(const btck_Chain *ptr)
int32_t Height() const
BlockTreeEntry GetByHeight(int32_t height) const
bool Contains(BlockTreeEntry &entry) const
int32_t CountEntries() 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 SetDatabaseCacheBytes(uint64_t database_cache_bytes)
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)
Iterator(const Collection *ptr)
Iterator()=default
auto operator+(difference_type n) const
auto operator-(difference_type n) const
std::random_access_iterator_tag iterator_category
std::random_access_iterator_tag iterator_concept
auto operator<=>(const Iterator &other) const
auto & operator+=(difference_type n)
friend Iterator operator+(difference_type n, const Iterator &it)
const Collection * m_collection
bool operator==(const Iterator &other) const
std::ptrdiff_t difference_type
auto & operator-=(difference_type n)
ValueType operator[](difference_type n) const
auto operator-(const Iterator &other) const
Iterator(const Collection *ptr, size_t idx)
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)
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< Container, value_type, GetFunc > iterator
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)
WitnessStackView GetWitnessStack() const
std::vector< std::byte > GetScriptSig() const
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)
TxValidationResult GetTxValidationResult() const
ValidationMode GetValidationMode() const
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)
std::vector< std::byte > GetItem(size_t index) const
WitnessStack(const WitnessStackView &view)
WitnessStackView(const btck_WitnessStack *ptr)
bool operator==(const WtxidApi &other) const
WtxidApi()=default
bool operator!=(const WtxidApi &other) const
std::array< std::byte, 32 > ToBytes() const
Wtxid(const WtxidView &view)
WtxidView(const btck_Wtxid *ptr)
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
#define T(expected, seed, data)
constexpr T & operator|=(T &lhs, T rhs)
void set_mock_time(std::chrono::seconds timestamp)
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 *))
bool CheckTransaction(const Transaction &tx, TxValidationState &state)
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)
@ 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.
WalletContext context