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 TXPACKAGES = btck_LogCategory_TXPACKAGES,
40};
41
42enum class LogLevel : btck_LogLevel {
48};
49
50constexpr std::string_view Name(LogLevel level) noexcept
51{
52 switch (level) {
53 case LogLevel::TRACE_LEVEL: return "trace";
54 case LogLevel::DEBUG_LEVEL: return "debug";
55 case LogLevel::INFO_LEVEL: return "info";
56 case LogLevel::WARNING_LEVEL: return "warning";
57 case LogLevel::ERROR_LEVEL: return "error";
58 } // no default case, so the compiler can warn about missing cases
59 return "unknown";
60}
61
62constexpr std::string_view Name(LogCategory category) noexcept
63{
64 switch (category) {
65 case LogCategory::NONE: return "none";
66 case LogCategory::BENCH: return "bench";
67 case LogCategory::BLOCKSTORAGE: return "blockstorage";
68 case LogCategory::COINDB: return "coindb";
69 case LogCategory::LEVELDB: return "leveldb";
70 case LogCategory::MEMPOOL: return "mempool";
71 case LogCategory::PRUNE: return "prune";
72 case LogCategory::RAND: return "rand";
73 case LogCategory::REINDEX: return "reindex";
74 case LogCategory::TXPACKAGES: return "txpackages";
75 case LogCategory::VALIDATION: return "validation";
76 case LogCategory::KERNEL: return "kernel";
77 case LogCategory::LOCK: return "lock";
78 } // no default case, so the compiler can warn about missing cases
79 return "unknown";
80}
81
88};
89
94};
95
96enum class Warning : btck_Warning {
99};
100
105};
106
117};
118
133};
134
139};
140
151};
152
158};
159
160template <typename T>
161struct is_bitmask_enum : std::false_type {
162};
163
164template <>
165struct is_bitmask_enum<ScriptVerificationFlags> : std::true_type {
166};
167
168template <>
169struct is_bitmask_enum<BlockCheckFlags> : std::true_type {
170};
171
172template <typename T>
173concept BitmaskEnum = is_bitmask_enum<T>::value;
174
175template <BitmaskEnum T>
176constexpr T operator|(T lhs, T rhs)
177{
178 return static_cast<T>(
179 static_cast<std::underlying_type_t<T>>(lhs) | static_cast<std::underlying_type_t<T>>(rhs));
180}
181
182template <BitmaskEnum T>
183constexpr T operator&(T lhs, T rhs)
184{
185 return static_cast<T>(
186 static_cast<std::underlying_type_t<T>>(lhs) & static_cast<std::underlying_type_t<T>>(rhs));
187}
188
189template <BitmaskEnum T>
190constexpr T operator^(T lhs, T rhs)
191{
192 return static_cast<T>(
193 static_cast<std::underlying_type_t<T>>(lhs) ^ static_cast<std::underlying_type_t<T>>(rhs));
194}
195
196template <BitmaskEnum T>
197constexpr T operator~(T value)
198{
199 return static_cast<T>(~static_cast<std::underlying_type_t<T>>(value));
200}
201
202template <BitmaskEnum T>
203constexpr T& operator|=(T& lhs, T rhs)
204{
205 return lhs = lhs | rhs;
206}
207
208template <BitmaskEnum T>
209constexpr T& operator&=(T& lhs, T rhs)
210{
211 return lhs = lhs & rhs;
212}
213
214template <BitmaskEnum T>
215constexpr T& operator^=(T& lhs, T rhs)
216{
217 return lhs = lhs ^ rhs;
218}
219
220template <typename T>
221T check(T ptr)
222{
223 if (ptr == nullptr) {
224 throw std::runtime_error("failed to instantiate btck object");
225 }
226 return ptr;
227}
228
229template <typename Collection, typename ValueType, auto GetFunc>
231{
232public:
233 using iterator_category = std::random_access_iterator_tag;
234 using iterator_concept = std::random_access_iterator_tag;
235 using difference_type = std::ptrdiff_t;
236 using value_type = ValueType;
237
238private:
239 const Collection* m_collection;
240 size_t m_idx;
241
242public:
243 Iterator() = default;
244 Iterator(const Collection* ptr) : m_collection{ptr}, m_idx{0} {}
245 Iterator(const Collection* ptr, size_t idx) : m_collection{ptr}, m_idx{idx} {}
246
247 // This is just a view, so return a copy.
248 auto operator*() const { return std::invoke(GetFunc, *m_collection, m_idx); }
249
250 auto& operator++() { m_idx++; return *this; }
251 auto operator++(int) { Iterator tmp = *this; ++(*this); return tmp; }
252
253 auto& operator--() { m_idx--; return *this; }
254 auto operator--(int) { auto temp = *this; --m_idx; return temp; }
255
256 auto& operator+=(difference_type n) { m_idx += n; return *this; }
257 auto& operator-=(difference_type n) { m_idx -= n; return *this; }
258
259 auto operator+(difference_type n) const { return Iterator(m_collection, m_idx + n); }
260 auto operator-(difference_type n) const { return Iterator(m_collection, m_idx - n); }
261
262 auto operator-(const Iterator& other) const { return static_cast<difference_type>(m_idx) - static_cast<difference_type>(other.m_idx); }
263
264 ValueType operator[](difference_type n) const { return *(*this + n); }
265
266 auto operator<=>(const Iterator& other) const { return m_idx <=> other.m_idx; }
267
268 bool operator==(const Iterator& other) const { return m_collection == other.m_collection && m_idx == other.m_idx; }
269
270private:
271 friend Iterator operator+(difference_type n, const Iterator& it) { return it + n; }
272};
273
274template <typename Container, typename SizeFunc, typename GetFunc>
275concept IndexedContainer = requires(const Container& c, SizeFunc size_func, GetFunc get_func, std::size_t i) {
276 { std::invoke(size_func, c) } -> std::convertible_to<std::size_t>;
277 { std::invoke(get_func, c, i) }; // Return type is deduced
278};
279
280template <typename Container, auto SizeFunc, auto GetFunc>
281 requires IndexedContainer<Container, decltype(SizeFunc), decltype(GetFunc)>
282class Range
283{
284public:
285 using value_type = std::invoke_result_t<decltype(GetFunc), const Container&, size_t>;
286 using difference_type = std::ptrdiff_t;
289
290private:
291 const Container* m_container;
292
293public:
294 explicit Range(const Container& container) : m_container(&container)
295 {
296 static_assert(std::ranges::random_access_range<Range>);
297 }
298
299 iterator begin() const { return iterator(m_container, 0); }
300 iterator end() const { return iterator(m_container, size()); }
301
302 const_iterator cbegin() const { return begin(); }
303 const_iterator cend() const { return end(); }
304
305 size_t size() const { return std::invoke(SizeFunc, *m_container); }
306
307 bool empty() const { return size() == 0; }
308
309 value_type operator[](size_t index) const { return std::invoke(GetFunc, *m_container, index); }
310
311 value_type at(size_t index) const
312 {
313 if (index >= size()) {
314 throw std::out_of_range("Index out of range");
315 }
316 return (*this)[index];
317 }
318
319 value_type front() const { return (*this)[0]; }
320 value_type back() const { return (*this)[size() - 1]; }
321};
322
323#define MAKE_RANGE_METHOD(method_name, ContainerType, SizeFunc, GetFunc, container_expr) \
324 auto method_name() const & { \
325 return Range<ContainerType, SizeFunc, GetFunc>{container_expr}; \
326 } \
327 auto method_name() const && = delete;
328
329template <typename T>
330std::vector<std::byte> write_bytes(const T* object, int (*to_bytes)(const T*, btck_WriteBytes, void*))
331{
332 std::vector<std::byte> bytes;
333 struct UserData {
334 std::vector<std::byte>* bytes;
335 std::exception_ptr exception;
336 };
337 UserData user_data = UserData{.bytes = &bytes, .exception = nullptr};
338
339 constexpr auto const write = +[](const void* buffer, size_t len, void* user_data) -> int {
340 auto& data = *reinterpret_cast<UserData*>(user_data);
341 auto& bytes = *data.bytes;
342 try {
343 auto const* first = static_cast<const std::byte*>(buffer);
344 auto const* last = first + len;
345 bytes.insert(bytes.end(), first, last);
346 return 0;
347 } catch (...) {
348 data.exception = std::current_exception();
349 return -1;
350 }
351 };
352
353 if (to_bytes(object, write, &user_data) != 0) {
354 std::rethrow_exception(user_data.exception);
355 }
356 return bytes;
357}
358
359template <typename CType>
360class View
361{
362protected:
363 const CType* m_ptr;
364
365public:
366 explicit View(const CType* ptr) : m_ptr{check(ptr)} {}
367
368 const CType* get() const { return m_ptr; }
369};
370
371template <typename CType, CType* (*CopyFunc)(const CType*), void (*DestroyFunc)(CType*)>
373{
374protected:
375 CType* m_ptr;
376
377public:
378 explicit Handle(CType* ptr) : m_ptr{check(ptr)} {}
379
380 // Copy constructors
381 Handle(const Handle& other)
382 : m_ptr{check(CopyFunc(other.m_ptr))} {}
383 Handle& operator=(const Handle& other)
384 {
385 if (this != &other) {
386 Handle temp(other);
387 std::swap(m_ptr, temp.m_ptr);
388 }
389 return *this;
390 }
391
392 // Move constructors
393 Handle(Handle&& other) noexcept : m_ptr(other.m_ptr) { other.m_ptr = nullptr; }
394 Handle& operator=(Handle&& other) noexcept
395 {
396 if (this != &other) {
397 DestroyFunc(m_ptr);
398 m_ptr = std::exchange(other.m_ptr, nullptr);
399 }
400 return *this;
401 }
402
403 template <typename ViewType>
404 requires std::derived_from<ViewType, View<CType>>
405 Handle(const ViewType& view)
406 : Handle{CopyFunc(view.get())}
407 {
408 }
409
410 ~Handle() { DestroyFunc(m_ptr); }
411
412 CType* get() { return m_ptr; }
413 const CType* get() const { return m_ptr; }
414};
415
416template <typename CType, void (*DestroyFunc)(CType*)>
418{
419protected:
420 struct Deleter {
421 void operator()(CType* ptr) const noexcept
422 {
423 if (ptr) DestroyFunc(ptr);
424 }
425 };
426 std::unique_ptr<CType, Deleter> m_ptr;
427
428public:
429 explicit UniqueHandle(CType* ptr) : m_ptr{check(ptr)} {}
430
431 CType* get() { return m_ptr.get(); }
432 const CType* get() const { return m_ptr.get(); }
433};
434
436class Transaction;
437class TransactionOutput;
439
440template <typename Derived>
442{
443private:
444 auto impl() const
445 {
446 return static_cast<const Derived*>(this)->get();
447 }
448
449 friend Derived;
450 ScriptPubkeyApi() = default;
451
452public:
453 bool Verify(int64_t amount,
454 const Transaction& tx_to,
455 const PrecomputedTransactionData* precomputed_txdata,
456 unsigned int input_index,
458 ScriptVerifyStatus& status) const;
459
460 std::vector<std::byte> ToBytes() const
461 {
463 }
464};
465
466class ScriptPubkeyView : public View<btck_ScriptPubkey>, public ScriptPubkeyApi<ScriptPubkeyView>
467{
468public:
469 explicit ScriptPubkeyView(const btck_ScriptPubkey* ptr) : View{ptr} {}
470};
471
472class ScriptPubkey : public Handle<btck_ScriptPubkey, btck_script_pubkey_copy, btck_script_pubkey_destroy>, public ScriptPubkeyApi<ScriptPubkey>
473{
474public:
475 explicit ScriptPubkey(std::span<const std::byte> raw)
476 : Handle{btck_script_pubkey_create(raw.data(), raw.size())} {}
477
479 : Handle(view) {}
480};
481
482template <typename Derived>
484{
485private:
486 auto impl() const
487 {
488 return static_cast<const Derived*>(this)->get();
489 }
490
491 friend Derived;
493
494public:
495 int64_t Amount() const
496 {
498 }
499
501 {
503 }
504};
505
506class TransactionOutputView : public View<btck_TransactionOutput>, public TransactionOutputApi<TransactionOutputView>
507{
508public:
509 explicit TransactionOutputView(const btck_TransactionOutput* ptr) : View{ptr} {}
510};
511
512class TransactionOutput : public Handle<btck_TransactionOutput, btck_transaction_output_copy, btck_transaction_output_destroy>, public TransactionOutputApi<TransactionOutput>
513{
514public:
515 explicit TransactionOutput(const ScriptPubkey& script_pubkey, int64_t amount)
516 : Handle{btck_transaction_output_create(script_pubkey.get(), amount)} {}
517
519 : Handle(view) {}
520};
521
522template <typename Derived>
524{
525private:
526 auto impl() const
527 {
528 return static_cast<const Derived*>(this)->get();
529 }
530
531 friend Derived;
532 TxidApi() = default;
533
534public:
535 bool operator==(const TxidApi& other) const
536 {
537 return btck_txid_equals(impl(), other.impl()) != 0;
538 }
539
540 bool operator!=(const TxidApi& other) const
541 {
542 return btck_txid_equals(impl(), other.impl()) == 0;
543 }
544
545 std::array<std::byte, 32> ToBytes() const
546 {
547 std::array<std::byte, 32> hash;
548 btck_txid_to_bytes(impl(), reinterpret_cast<unsigned char*>(hash.data()));
549 return hash;
550 }
551};
552
553class TxidView : public View<btck_Txid>, public TxidApi<TxidView>
554{
555public:
556 explicit TxidView(const btck_Txid* ptr) : View{ptr} {}
557};
558
559class Txid : public Handle<btck_Txid, btck_txid_copy, btck_txid_destroy>, public TxidApi<Txid>
560{
561public:
562 Txid(const TxidView& view)
563 : Handle(view) {}
564};
565
566template <typename Derived>
568{
569private:
570 auto impl() const
571 {
572 return static_cast<const Derived*>(this)->get();
573 }
574
575 friend Derived;
576 WtxidApi() = default;
577
578public:
579 bool operator==(const WtxidApi& other) const
580 {
581 return btck_wtxid_equals(impl(), other.impl()) != 0;
582 }
583
584 bool operator!=(const WtxidApi& other) const
585 {
586 return btck_wtxid_equals(impl(), other.impl()) == 0;
587 }
588
589 std::array<std::byte, 32> ToBytes() const
590 {
591 std::array<std::byte, 32> hash;
592 btck_wtxid_to_bytes(impl(), reinterpret_cast<unsigned char*>(hash.data()));
593 return hash;
594 }
595};
596
597class WtxidView : public View<btck_Wtxid>, public WtxidApi<WtxidView>
598{
599public:
600 explicit WtxidView(const btck_Wtxid* ptr) : View{ptr} {}
601};
602
603class Wtxid : public Handle<btck_Wtxid, btck_wtxid_copy, btck_wtxid_destroy>, public WtxidApi<Wtxid>
604{
605public:
606 Wtxid(const WtxidView& view)
607 : Handle(view) {}
608};
609
610template <typename Derived>
612{
613private:
614 auto impl() const
615 {
616 return static_cast<const Derived*>(this)->get();
617 }
618
619 friend Derived;
620 OutPointApi() = default;
621
622public:
623 uint32_t index() const
624 {
626 }
627
629 {
631 }
632};
633
634class OutPointView : public View<btck_TransactionOutPoint>, public OutPointApi<OutPointView>
635{
636public:
637 explicit OutPointView(const btck_TransactionOutPoint* ptr) : View{ptr} {}
638};
639
640class OutPoint : public Handle<btck_TransactionOutPoint, btck_transaction_out_point_copy, btck_transaction_out_point_destroy>, public OutPointApi<OutPoint>
641{
642public:
644 : Handle(view) {}
645};
646
647template <typename Derived>
649{
650private:
651 auto impl() const
652 {
653 return static_cast<const Derived*>(this)->get();
654 }
655
656 friend Derived;
657 WitnessStackApi() = default;
658
659public:
660 size_t CountItems() const
661 {
663 }
664
665 std::vector<std::byte> GetItem(size_t index) const
666 {
667 struct Item { const btck_WitnessStack* stack; size_t index; };
668 Item item{impl(), index};
669 return write_bytes(&item, +[](const Item* c, btck_WriteBytes w, void* ud) {
670 return btck_witness_stack_get_item_at(c->stack, c->index, w, ud);
671 });
672 }
673
675};
676
677class WitnessStackView : public View<btck_WitnessStack>, public WitnessStackApi<WitnessStackView>
678{
679public:
680 explicit WitnessStackView(const btck_WitnessStack* ptr) : View{ptr} {}
681};
682
683class WitnessStack : public Handle<btck_WitnessStack, btck_witness_stack_copy, btck_witness_stack_destroy>, public WitnessStackApi<WitnessStack>
684{
685public:
687 : Handle(view) {}
688};
689
690template <typename Derived>
692{
693private:
694 auto impl() const
695 {
696 return static_cast<const Derived*>(this)->get();
697 }
698
699 friend Derived;
701
702public:
704 {
706 }
707
708 uint32_t GetSequence() const
709 {
711 }
712
714 {
716 }
717
718 std::vector<std::byte> GetScriptSig() const
719 {
721 }
722};
723
724class TransactionInputView : public View<btck_TransactionInput>, public TransactionInputApi<TransactionInputView>
725{
726public:
727 explicit TransactionInputView(const btck_TransactionInput* ptr) : View{ptr} {}
728};
729
730class TransactionInput : public Handle<btck_TransactionInput, btck_transaction_input_copy, btck_transaction_input_destroy>, public TransactionInputApi<TransactionInput>
731{
732public:
734 : Handle(view) {}
735};
736
737template <typename Derived>
739{
740private:
741 auto impl() const
742 {
743 return static_cast<const Derived*>(this)->get();
744 }
745
746public:
747 size_t CountOutputs() const
748 {
750 }
751
752 size_t CountInputs() const
753 {
755 }
756
758 {
760 }
761
762 TransactionInputView GetInput(size_t index) const
763 {
765 }
766
767 uint32_t GetVersion() const
768 {
770 }
771
772 uint32_t GetLocktime() const
773 {
775 }
776
777 bool HasWitness() const
778 {
779 return btck_transaction_has_witness(impl()) != 0;
780 }
781
783 {
785 }
786
788 {
790 }
791
793
795
796 std::vector<std::byte> ToBytes() const
797 {
799 }
800};
801
802class TransactionView : public View<btck_Transaction>, public TransactionApi<TransactionView>
803{
804public:
805 explicit TransactionView(const btck_Transaction* ptr) : View{ptr} {}
806};
807
808class Transaction : public Handle<btck_Transaction, btck_transaction_copy, btck_transaction_destroy>, public TransactionApi<Transaction>
809{
810public:
811 explicit Transaction(std::span<const std::byte> raw_transaction)
812 : Handle{btck_transaction_create(raw_transaction.data(), raw_transaction.size())} {}
813
815 : Handle{view} {}
816};
817
818class PrecomputedTransactionData : public Handle<btck_PrecomputedTransactionData, btck_precomputed_transaction_data_copy, btck_precomputed_transaction_data_destroy>
819{
820public:
821 explicit PrecomputedTransactionData(const Transaction& tx_to, std::span<const TransactionOutput> spent_outputs)
823 tx_to.get(),
824 reinterpret_cast<const btck_TransactionOutput**>(
825 const_cast<TransactionOutput*>(spent_outputs.data())),
826 spent_outputs.size())} {}
827};
828
829template <typename Derived>
831 const Transaction& tx_to,
832 const PrecomputedTransactionData* precomputed_txdata,
833 unsigned int input_index,
835 ScriptVerifyStatus& status) const
836{
837 auto result = btck_script_pubkey_verify(
838 impl(),
839 amount,
840 tx_to.get(),
841 precomputed_txdata ? precomputed_txdata->get() : nullptr,
842 input_index,
844 reinterpret_cast<btck_ScriptVerifyStatus*>(&status));
845 return result == 1;
846}
847
848template <typename Derived>
850{
851private:
852 auto impl() const
853 {
854 return static_cast<const Derived*>(this)->get();
855 }
856
857public:
858 bool operator==(const Derived& other) const
859 {
860 return btck_block_hash_equals(impl(), other.get()) != 0;
861 }
862
863 bool operator!=(const Derived& other) const
864 {
865 return btck_block_hash_equals(impl(), other.get()) == 0;
866 }
867
868 std::array<std::byte, 32> ToBytes() const
869 {
870 std::array<std::byte, 32> hash;
871 btck_block_hash_to_bytes(impl(), reinterpret_cast<unsigned char*>(hash.data()));
872 return hash;
873 }
874};
875
876class BlockHashView : public View<btck_BlockHash>, public BlockHashApi<BlockHashView>
877{
878public:
879 explicit BlockHashView(const btck_BlockHash* ptr) : View{ptr} {}
880};
881
882class BlockHash : public Handle<btck_BlockHash, btck_block_hash_copy, btck_block_hash_destroy>, public BlockHashApi<BlockHash>
883{
884public:
885 explicit BlockHash(const std::array<std::byte, 32>& hash)
886 : Handle{btck_block_hash_create(reinterpret_cast<const unsigned char*>(hash.data()))} {}
887
888 explicit BlockHash(btck_BlockHash* hash)
889 : Handle{hash} {}
890
892 : Handle{view} {}
893};
894
895template <typename Derived>
897{
898private:
899 auto impl() const
900 {
901 return static_cast<const Derived*>(this)->get();
902 }
903
904 friend Derived;
905 BlockHeaderApi() = default;
906
907public:
909 {
911 }
912
914 {
916 }
917
918 std::array<std::byte, 32> MerkleRoot() const
919 {
920 std::array<std::byte, 32> merkle_root;
921 btck_block_header_get_merkle_root(impl(), reinterpret_cast<unsigned char*>(merkle_root.data()));
922 return merkle_root;
923 }
924
925 uint32_t Timestamp() const
926 {
928 }
929
930 uint32_t Bits() const
931 {
933 }
934
935 int32_t Version() const
936 {
938 }
939
940 uint32_t Nonce() const
941 {
943 }
944
945 std::array<std::byte, 80> ToBytes() const
946 {
947 std::array<std::byte, 80> header;
948 int res{btck_block_header_to_bytes(impl(), reinterpret_cast<unsigned char*>(header.data()))};
949 if (res != 0) {
950 throw std::runtime_error("Failed to serialize block header");
951 }
952 return header;
953 }
954};
955
956class BlockHeaderView : public View<btck_BlockHeader>, public BlockHeaderApi<BlockHeaderView>
957{
958public:
959 explicit BlockHeaderView(const btck_BlockHeader* ptr) : View{ptr} {}
960};
961
962class BlockHeader : public Handle<btck_BlockHeader, btck_block_header_copy, btck_block_header_destroy>, public BlockHeaderApi<BlockHeader>
963{
964public:
965 explicit BlockHeader(std::span<const std::byte> raw_header)
966 : Handle{btck_block_header_create(reinterpret_cast<const unsigned char*>(raw_header.data()), raw_header.size())} {}
967
969 : Handle{view} {}
970
972 : Handle{header} {}
973};
974
975class ConsensusParamsView : public View<btck_ConsensusParams>
976{
977public:
978 explicit ConsensusParamsView(const btck_ConsensusParams* ptr) : View{ptr} {}
979};
980
981class Block : public Handle<btck_Block, btck_block_copy, btck_block_destroy>
982{
983public:
984 Block(const std::span<const std::byte> raw_block)
985 : Handle{btck_block_create(raw_block.data(), raw_block.size())}
986 {
987 }
988
989 Block(btck_Block* block) : Handle{block} {}
990
991 size_t CountTransactions() const
992 {
994 }
995
996 TransactionView GetTransaction(size_t index) const
997 {
999 }
1000
1001 bool Check(const ConsensusParamsView& consensus_params,
1003 BlockValidationState& state) const;
1004
1006
1008 {
1010 }
1011
1013 {
1015 }
1016
1017 std::vector<std::byte> ToBytes() const
1018 {
1020 }
1021};
1022
1024{
1025 btck_logging_set_min_level(static_cast<btck_LogLevel>(level));
1026}
1027
1032{
1033private:
1035
1036public:
1037 explicit LogEntry(const btck_LogEntry& entry) : m_entry{&entry} {}
1038
1039 std::string_view Message() const { return {m_entry->message, m_entry->message_len}; }
1040 std::string_view ThreadName() const { return {m_entry->thread_name, m_entry->thread_name_len}; }
1041 std::chrono::sys_time<std::chrono::nanoseconds> Timestamp() const
1042 {
1043 return std::chrono::sys_time<std::chrono::nanoseconds>{std::chrono::nanoseconds{m_entry->timestamp_ns}};
1044 }
1045 std::optional<std::chrono::sys_seconds> MockTime() const
1046 {
1047 if (m_entry->mocktime_s == 0) return std::nullopt;
1048 return std::chrono::sys_seconds{std::chrono::seconds{m_entry->mocktime_s}};
1049 }
1050 std::string_view FileName() const { return {m_entry->file_name, m_entry->file_name_len}; }
1051 std::string_view FunctionName() const { return {m_entry->function_name, m_entry->function_name_len}; }
1052 uint32_t Line() const { return m_entry->line; }
1053 LogLevel Level() const { return static_cast<LogLevel>(m_entry->level); }
1054 LogCategory Category() const { return static_cast<LogCategory>(m_entry->category); }
1055};
1056
1057template <typename T>
1058concept Log = requires(T a, const LogEntry& entry) {
1059 { a.LogMessage(entry) } -> std::same_as<void>;
1060};
1061
1062template <Log T>
1063class Logger : UniqueHandle<btck_LoggingConnection, btck_logging_connection_destroy>
1064{
1065public:
1066 Logger(std::unique_ptr<T> log)
1068 +[](void* user_data, const btck_LogEntry* entry) { static_cast<T*>(user_data)->LogMessage(LogEntry{*entry}); },
1069 log.release(),
1070 +[](void* user_data) { delete static_cast<T*>(user_data); })}
1071 {
1072 }
1073};
1074
1075class BlockTreeEntry : public View<btck_BlockTreeEntry>
1076{
1077public:
1079 : View{entry}
1080 {
1081 }
1082
1083 bool operator==(const BlockTreeEntry& other) const
1084 {
1085 return btck_block_tree_entry_equals(get(), other.get()) != 0;
1086 }
1087
1088 std::optional<BlockTreeEntry> GetPrevious() const
1089 {
1090 auto entry{btck_block_tree_entry_get_previous(get())};
1091 if (!entry) return std::nullopt;
1092 return entry;
1093 }
1094
1095 int32_t GetHeight() const
1096 {
1098 }
1099
1101 {
1103 }
1104
1106 {
1108 }
1109
1110 BlockTreeEntry GetAncestor(int32_t height) const
1111 {
1113 }
1114
1115};
1116
1118{
1119public:
1120 virtual ~KernelNotifications() = default;
1121
1122 virtual void BlockTipHandler(SynchronizationState state, BlockTreeEntry entry, double verification_progress) {}
1123
1124 virtual void HeaderTipHandler(SynchronizationState state, int64_t height, int64_t timestamp, bool presync) {}
1125
1126 virtual void ProgressHandler(std::string_view title, int progress_percent, bool resume_possible) {}
1127
1128 virtual void WarningSetHandler(Warning warning, std::string_view message) {}
1129
1130 virtual void WarningUnsetHandler(Warning warning) {}
1131
1132 virtual void FlushErrorHandler(std::string_view error) {}
1133
1134 virtual void FatalErrorHandler(std::string_view error) {}
1135};
1136
1137template <typename Derived>
1139{
1140private:
1141 auto impl() const
1142 {
1143 return static_cast<const Derived*>(this)->get();
1144 }
1145
1146 friend Derived;
1148
1149public:
1151 {
1153 }
1154
1156 {
1158 }
1159};
1160
1161class BlockValidationStateView : public View<btck_BlockValidationState>, public BlockValidationStateApi<BlockValidationStateView>
1162{
1163public:
1165};
1166
1167class BlockValidationState : public Handle<btck_BlockValidationState, btck_block_validation_state_copy, btck_block_validation_state_destroy>, public BlockValidationStateApi<BlockValidationState>
1168{
1169public:
1171
1173
1175};
1176
1177inline bool Block::Check(const ConsensusParamsView& consensus_params,
1179 BlockValidationState& state) const
1180{
1181 return btck_block_check(get(), consensus_params.get(), static_cast<btck_BlockCheckFlags>(flags), state.get()) == 1;
1182}
1183
1184class TxValidationState : public UniqueHandle<btck_TxValidationState, btck_tx_validation_state_destroy>
1185{
1186public:
1187 using UniqueHandle::UniqueHandle; // inherit ctor
1189
1191 {
1193 }
1194
1196 {
1198 }
1199};
1200
1201inline bool CheckTransaction(const Transaction& tx, TxValidationState& state)
1202{
1203 return btck_transaction_check(tx.get(), state.get()) == 1;
1204}
1205
1207{
1208public:
1209 virtual ~ValidationInterface() = default;
1210
1211 virtual void BlockChecked(Block block, BlockValidationStateView state) {}
1212
1213 virtual void PowValidBlock(BlockTreeEntry entry, Block block) {}
1214
1215 virtual void BlockConnected(Block block, BlockTreeEntry entry) {}
1216
1217 virtual void BlockDisconnected(Block block, BlockTreeEntry entry) {}
1218};
1219
1220class ChainParams : public Handle<btck_ChainParameters, btck_chain_parameters_copy, btck_chain_parameters_destroy>
1221{
1222public:
1223 explicit ChainParams(ChainType chain_type)
1224 : Handle{btck_chain_parameters_create(static_cast<btck_ChainType>(chain_type))} {}
1225
1226 explicit ChainParams(std::span<const std::byte> signet_challenge)
1227 : Handle{btck_chain_parameters_create_signet(signet_challenge.data(), signet_challenge.size())} {}
1228
1230 {
1232 }
1233};
1234
1235class ContextOptions : public UniqueHandle<btck_ContextOptions, btck_context_options_destroy>
1236{
1237public:
1239
1240 void SetChainParams(ChainParams& chain_params)
1241 {
1242 btck_context_options_set_chainparams(get(), chain_params.get());
1243 }
1244
1245 template <typename T>
1246 void SetNotifications(std::shared_ptr<T> notifications)
1247 {
1248 static_assert(std::is_base_of_v<KernelNotifications, T>);
1249 auto heap_notifications = std::make_unique<std::shared_ptr<T>>(std::move(notifications));
1250 using user_type = std::shared_ptr<T>*;
1252 get(),
1254 .user_data = heap_notifications.release(),
1255 .user_data_destroy = +[](void* user_data) { delete static_cast<user_type>(user_data); },
1256 .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); },
1257 .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); },
1258 .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); },
1259 .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}); },
1260 .warning_unset = +[](void* user_data, btck_Warning warning) { (*static_cast<user_type>(user_data))->WarningUnsetHandler(static_cast<Warning>(warning)); },
1261 .flush_error = +[](void* user_data, const char* error, size_t error_len) { (*static_cast<user_type>(user_data))->FlushErrorHandler({error, error_len}); },
1262 .fatal_error = +[](void* user_data, const char* error, size_t error_len) { (*static_cast<user_type>(user_data))->FatalErrorHandler({error, error_len}); },
1263 });
1264 }
1265
1266 template <typename T>
1267 void SetValidationInterface(std::shared_ptr<T> validation_interface)
1268 {
1269 static_assert(std::is_base_of_v<ValidationInterface, T>);
1270 auto heap_vi = std::make_unique<std::shared_ptr<T>>(std::move(validation_interface));
1271 using user_type = std::shared_ptr<T>*;
1273 get(),
1275 .user_data = heap_vi.release(),
1276 .user_data_destroy = +[](void* user_data) { delete static_cast<user_type>(user_data); },
1277 .block_checked = +[](void* user_data, btck_Block* block, const btck_BlockValidationState* state) { (*static_cast<user_type>(user_data))->BlockChecked(Block{block}, BlockValidationStateView{state}); },
1278 .pow_valid_block = +[](void* user_data, btck_Block* block, const btck_BlockTreeEntry* entry) { (*static_cast<user_type>(user_data))->PowValidBlock(BlockTreeEntry{entry}, Block{block}); },
1279 .block_connected = +[](void* user_data, btck_Block* block, const btck_BlockTreeEntry* entry) { (*static_cast<user_type>(user_data))->BlockConnected(Block{block}, BlockTreeEntry{entry}); },
1280 .block_disconnected = +[](void* user_data, btck_Block* block, const btck_BlockTreeEntry* entry) { (*static_cast<user_type>(user_data))->BlockDisconnected(Block{block}, BlockTreeEntry{entry}); },
1281 });
1282 }
1283};
1284
1285class Context : public Handle<btck_Context, btck_context_copy, btck_context_destroy>
1286{
1287public:
1289 : Handle{btck_context_create(opts.get())} {}
1290
1293
1295 {
1296 return btck_context_interrupt(get()) == 0;
1297 }
1298};
1299
1300class ChainstateManagerOptions : public UniqueHandle<btck_ChainstateManagerOptions, btck_chainstate_manager_options_destroy>
1301{
1302public:
1303 ChainstateManagerOptions(const Context& context, std::string_view data_dir, std::string_view blocks_dir)
1305 context.get(), data_dir.data(), data_dir.length(), blocks_dir.data(), blocks_dir.length())}
1306 {
1307 }
1308
1309 void SetWorkerThreads(int worker_threads)
1310 {
1312 }
1313
1314 bool SetDatabaseCacheBytes(uint64_t database_cache_bytes)
1315 {
1316 return btck_chainstate_manager_options_set_database_cache_bytes(get(), database_cache_bytes) == 0;
1317 }
1318
1319 bool SetWipeDbs(bool wipe_block_tree, bool wipe_chainstate)
1320 {
1321 return btck_chainstate_manager_options_set_wipe_dbs(get(), wipe_block_tree, wipe_chainstate) == 0;
1322 }
1323
1324 void UpdateBlockTreeDbInMemory(bool block_tree_db_in_memory)
1325 {
1327 }
1328
1329 void UpdateChainstateDbInMemory(bool chainstate_db_in_memory)
1330 {
1332 }
1333};
1334
1335class ChainView : public View<btck_Chain>
1336{
1337public:
1338 explicit ChainView(const btck_Chain* ptr) : View{ptr} {}
1339
1340 int32_t Height() const
1341 {
1342 return btck_chain_get_height(get());
1343 }
1344
1345 int32_t CountEntries() const
1346 {
1347 return btck_chain_get_height(get()) + 1;
1348 }
1349
1350 BlockTreeEntry GetByHeight(int32_t height) const
1351 {
1352 auto index{btck_chain_get_by_height(get(), height)};
1353 if (!index) throw std::runtime_error("No entry in the chain at the provided height");
1354 return index;
1355 }
1356
1357 bool Contains(BlockTreeEntry& entry) const
1358 {
1359 return btck_chain_contains(get(), entry.get());
1360 }
1361
1362 MAKE_RANGE_METHOD(Entries, ChainView, &ChainView::CountEntries, &ChainView::GetByHeight, *this)
1363};
1364
1365template <typename Derived>
1367{
1368private:
1369 auto impl() const
1370 {
1371 return static_cast<const Derived*>(this)->get();
1372 }
1373
1374 friend Derived;
1375 CoinApi() = default;
1376
1377public:
1378 uint32_t GetConfirmationHeight() const { return btck_coin_confirmation_height(impl()); }
1379
1380 bool IsCoinbase() const { return btck_coin_is_coinbase(impl()) == 1; }
1381
1383 {
1385 }
1386};
1387
1388class CoinView : public View<btck_Coin>, public CoinApi<CoinView>
1389{
1390public:
1391 explicit CoinView(const btck_Coin* ptr) : View{ptr} {}
1392};
1393
1394class Coin : public Handle<btck_Coin, btck_coin_copy, btck_coin_destroy>, public CoinApi<Coin>
1395{
1396public:
1397 Coin(btck_Coin* coin) : Handle{coin} {}
1398
1399 Coin(const CoinView& view) : Handle{view} {}
1400};
1401
1402template <typename Derived>
1404{
1405private:
1406 auto impl() const
1407 {
1408 return static_cast<const Derived*>(this)->get();
1409 }
1410
1411 friend Derived;
1413
1414public:
1415 size_t Count() const
1416 {
1418 }
1419
1420 CoinView GetCoin(size_t index) const
1421 {
1423 }
1424
1426};
1427
1428class TransactionSpentOutputsView : public View<btck_TransactionSpentOutputs>, public TransactionSpentOutputsApi<TransactionSpentOutputsView>
1429{
1430public:
1432};
1433
1434class TransactionSpentOutputs : public Handle<btck_TransactionSpentOutputs, btck_transaction_spent_outputs_copy, btck_transaction_spent_outputs_destroy>,
1435 public TransactionSpentOutputsApi<TransactionSpentOutputs>
1436{
1437public:
1438 TransactionSpentOutputs(btck_TransactionSpentOutputs* transaction_spent_outputs) : Handle{transaction_spent_outputs} {}
1439
1441};
1442
1443class BlockSpentOutputs : public Handle<btck_BlockSpentOutputs, btck_block_spent_outputs_copy, btck_block_spent_outputs_destroy>
1444{
1445public:
1447 : Handle{block_spent_outputs}
1448 {
1449 }
1450
1451 size_t Count() const
1452 {
1453 return btck_block_spent_outputs_count(get());
1454 }
1455
1457 {
1459 }
1460
1461 MAKE_RANGE_METHOD(TxsSpentOutputs, BlockSpentOutputs, &BlockSpentOutputs::Count, &BlockSpentOutputs::GetTxSpentOutputs, *this)
1462};
1463
1464class ChainMan : UniqueHandle<btck_ChainstateManager, btck_chainstate_manager_destroy>
1465{
1466public:
1467 ChainMan(const Context& context, const ChainstateManagerOptions& chainman_opts)
1468 : UniqueHandle{btck_chainstate_manager_create(chainman_opts.get())}
1469 {
1470 }
1471
1472 bool ImportBlocks(const std::span<const std::string> paths)
1473 {
1474 std::vector<const char*> c_paths;
1475 std::vector<size_t> c_paths_lens;
1476 c_paths.reserve(paths.size());
1477 c_paths_lens.reserve(paths.size());
1478 for (const auto& path : paths) {
1479 c_paths.push_back(path.c_str());
1480 c_paths_lens.push_back(path.length());
1481 }
1482
1483 return btck_chainstate_manager_import_blocks(get(), c_paths.data(), c_paths_lens.data(), c_paths.size()) == 0;
1484 }
1485
1486 bool ProcessBlock(const Block& block, bool* new_block)
1487 {
1488 int _new_block;
1489 int res = btck_chainstate_manager_process_block(get(), block.get(), &_new_block);
1490 if (new_block) *new_block = _new_block == 1;
1491 return res == 0;
1492 }
1493
1495 {
1496 auto state = btck_chainstate_manager_process_block_header(get(), header.get());
1497 return BlockValidationState{state};
1498 }
1499
1501 {
1503 }
1504
1505 std::optional<BlockTreeEntry> GetBlockTreeEntry(const BlockHash& block_hash) const
1506 {
1507 auto entry{btck_chainstate_manager_get_block_tree_entry_by_hash(get(), block_hash.get())};
1508 if (!entry) return std::nullopt;
1509 return entry;
1510 }
1511
1513 {
1515 }
1516
1517 std::optional<Block> ReadBlock(const BlockTreeEntry& entry) const
1518 {
1519 auto block{btck_block_read(get(), entry.get())};
1520 if (!block) return std::nullopt;
1521 return block;
1522 }
1523
1525 {
1526 return btck_block_spent_outputs_read(get(), entry.get());
1527 }
1528};
1529
1530inline void set_mock_time(std::chrono::seconds timestamp)
1531{
1532 if (btck_set_mock_time(timestamp.count()) != 0) {
1533 throw std::runtime_error("timestamp out of range");
1534 }
1535}
1536
1537} // namespace btck
1538
1539#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)
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.
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.
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_logging_set_min_level(btck_LogLevel level)
Set the minimum log level.
void btck_block_header_get_merkle_root(const btck_BlockHeader *header, unsigned char output[32])
btck_LoggingConnection * btck_logging_connection_create(btck_LogCallback callback, void *user_data, btck_DestroyCallback user_data_destroy_callback)
Start logging messages through the provided callback.
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_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_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 severity of a log statement.
#define btck_TxValidationResult_NOT_STANDARD
otherwise didn't meet local policy rules
#define btck_TxValidationResult_CONFLICT
tx already in mempool or conflicts with a tx in the chain
#define btck_LogLevel_WARNING
#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_LOCK
#define btck_LogCategory_PRUNE
uint8_t btck_SynchronizationState
Current sync state passed to tip changed callbacks.
#define btck_ChainType_TESTNET_4
#define btck_LogCategory_COINDB
#define btck_TxValidationResult_NO_MEMPOOL
this node does not have a mempool so can't validate the transaction
#define btck_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.
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_LogCategory_NONE
Not tied to a specific category, e.g. most INFO, WARNING and ERROR entries.
#define btck_BlockValidationResult_TIME_FUTURE
block timestamp was > 2 hours in the future (or our clock is bad)
#define btck_LogCategory_LEVELDB
#define btck_LogLevel_ERROR
#define btck_BlockValidationResult_CACHED_INVALID
this block was cached as being invalid and we didn't store the reason why
#define btck_Warning_LARGE_WORK_INVALID_CHAIN
#define btck_LogLevel_INFO
#define btck_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_LogCategory_TXPACKAGES
#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)
Non-owning view over a btck_LogEntry.
std::optional< std::chrono::sys_seconds > MockTime() const
std::string_view FunctionName() const
LogLevel Level() const
std::string_view FileName() const
uint32_t Line() const
LogEntry(const btck_LogEntry &entry)
LogCategory Category() const
const btck_LogEntry * m_entry
std::string_view ThreadName() const
std::string_view Message() const
std::chrono::sys_time< std::chrono::nanoseconds > Timestamp() const
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_min_level(LogLevel level)
constexpr T operator&(T lhs, T rhs)
constexpr std::string_view Name(LogLevel level) noexcept
constexpr T operator|(T lhs, T rhs)
@ UNKNOWN_NEW_RULES_ACTIVATED
@ LARGE_WORK_INVALID_CHAIN
constexpr T operator^(T lhs, T rhs)
T check(T ptr)
constexpr T & operator^=(T &lhs, T rhs)
@ OK
The message verification was successful.
void operator()(CType *ptr) const noexcept
A log entry passed to the logging callback.
const char * thread_name
Name of the thread that produced the log message.
size_t function_name_len
Length of function_name.
int64_t timestamp_ns
Wall-clock time when the entry was logged, in nanoseconds since the Unix epoch.
const char * function_name
Name of the function that produced the log message.
size_t file_name_len
Length of file_name.
uint32_t line
Line number of the source code that produced the log statement.
const char * message
Log message text.
const char * file_name
Name of the source file that produced the log statement.
int64_t mocktime_s
Mock time in effect when the entry was logged, in seconds since the Unix epoch, or 0 if no mock time ...
btck_LogCategory category
Log category.
size_t message_len
Length of message.
size_t thread_name_len
Length of thread_name.
btck_LogLevel level
Log severity level.
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.
#define LOCK(cs)
Definition: sync.h:268
WalletContext context