Branch data Line data Source code
1 : : // Copyright (c) 2022-present The Bitcoin Core developers
2 : : // Distributed under the MIT software license, see the accompanying
3 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 : :
5 : : #define BITCOINKERNEL_BUILD
6 : :
7 : : #include <kernel/bitcoinkernel.h>
8 : :
9 : : #include <chain.h>
10 : : #include <coins.h>
11 : : #include <consensus/tx_check.h>
12 : : #include <consensus/validation.h>
13 : : #include <dbwrapper.h>
14 : : #include <kernel/caches.h>
15 : : #include <kernel/chainparams.h>
16 : : #include <kernel/checks.h>
17 : : #include <kernel/context.h>
18 : : #include <kernel/notifications_interface.h>
19 : : #include <kernel/warning.h>
20 : : #include <logging.h>
21 : : #include <node/blockstorage.h>
22 : : #include <node/chainstate.h>
23 : : #include <primitives/block.h>
24 : : #include <primitives/transaction.h>
25 : : #include <script/interpreter.h>
26 : : #include <script/script.h>
27 : : #include <script/verify_flags.h>
28 : : #include <serialize.h>
29 : : #include <streams.h>
30 : : #include <sync.h>
31 : : #include <uint256.h>
32 : : #include <undo.h>
33 : : #include <util/check.h>
34 : : #include <util/fs.h>
35 : : #include <util/result.h>
36 : : #include <util/signalinterrupt.h>
37 : : #include <util/task_runner.h>
38 : : #include <util/translation.h>
39 : : #include <validation.h>
40 : : #include <validationinterface.h>
41 : :
42 : : #include <cstddef>
43 : : #include <cstring>
44 : : #include <exception>
45 : : #include <functional>
46 : : #include <list>
47 : : #include <memory>
48 : : #include <span>
49 : : #include <stdexcept>
50 : : #include <string>
51 : : #include <tuple>
52 : : #include <utility>
53 : : #include <vector>
54 : :
55 : : namespace Consensus {
56 : : struct Params;
57 : : } // namespace Consensus
58 : :
59 : : using kernel::ChainstateRole;
60 : : using util::ImmediateTaskRunner;
61 : :
62 : : // Define G_TRANSLATION_FUN symbol in libbitcoinkernel library so users of the
63 : : // library aren't required to export this symbol
64 : : extern const TranslateFn G_TRANSLATION_FUN{nullptr};
65 : :
66 : : static const kernel::Context btck_context_static{};
67 : :
68 : : namespace {
69 : :
70 : 80 : bool is_valid_flag_combination(script_verify_flags flags)
71 : : {
72 [ - + - - ]: 80 : if (flags & SCRIPT_VERIFY_CLEANSTACK && ~flags & (SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS)) return false;
73 [ + + - + ]: 80 : if (flags & SCRIPT_VERIFY_WITNESS && ~flags & SCRIPT_VERIFY_P2SH) return false;
74 : : return true;
75 : : }
76 : :
77 : : class WriterStream
78 : : {
79 : : private:
80 : : btck_WriteBytes m_writer;
81 : : void* m_user_data;
82 : :
83 : : public:
84 : 36 : WriterStream(btck_WriteBytes writer, void* user_data)
85 : 36 : : m_writer{writer}, m_user_data{user_data} {}
86 : :
87 : : //
88 : : // Stream subset
89 : : //
90 : 822 : void write(std::span<const std::byte> src)
91 : : {
92 [ - + ]: 822 : if (m_writer(src.data(), src.size(), m_user_data) != 0) {
93 [ # # ]: 0 : throw std::runtime_error("Failed to write serialization data");
94 : : }
95 : 822 : }
96 : :
97 : : template <typename T>
98 : 36 : WriterStream& operator<<(const T& obj)
99 : : {
100 [ + - + - ]: 36 : ::Serialize(*this, obj);
101 : 36 : return *this;
102 : : }
103 : : };
104 : :
105 : : template <typename C, typename CPP>
106 : : struct Handle {
107 : : static C* ref(CPP* cpp_type)
108 : : {
109 : : return reinterpret_cast<C*>(cpp_type);
110 : : }
111 : :
112 : : static const C* ref(const CPP* cpp_type)
113 : : {
114 : : return reinterpret_cast<const C*>(cpp_type);
115 : : }
116 : :
117 : : template <typename... Args>
118 : 8747 : static C* create(Args&&... args)
119 : : {
120 : 8747 : auto cpp_obj{std::make_unique<CPP>(std::forward<Args>(args)...)};
121 : 17494 : return ref(cpp_obj.release());
122 : 8747 : }
123 : :
124 : 807 : static C* copy(const C* ptr)
125 : : {
126 : 807 : auto cpp_obj{std::make_unique<CPP>(get(ptr))};
127 : 1614 : return ref(cpp_obj.release());
128 : 807 : }
129 : :
130 : : static const CPP& get(const C* ptr)
131 : : {
132 : : return *reinterpret_cast<const CPP*>(ptr);
133 : : }
134 : :
135 : : static CPP& get(C* ptr)
136 : : {
137 : : return *reinterpret_cast<CPP*>(ptr);
138 : : }
139 : :
140 : 9573 : static void operator delete(void* ptr)
141 : : {
142 [ + - ]: 17999 : delete reinterpret_cast<CPP*>(ptr);
143 : 9573 : }
144 : : };
145 : :
146 : : } // namespace
147 : :
148 : : struct btck_BlockTreeEntry: Handle<btck_BlockTreeEntry, CBlockIndex> {};
149 : : struct btck_Block : Handle<btck_Block, std::shared_ptr<const CBlock>> {};
150 : : struct btck_BlockValidationState : Handle<btck_BlockValidationState, BlockValidationState> {};
151 : : struct btck_TxValidationState : Handle<btck_TxValidationState, TxValidationState> {};
152 : :
153 : : namespace {
154 : :
155 : 2 : BCLog::Level get_bclog_level(btck_LogLevel level)
156 : : {
157 [ - + - - ]: 2 : switch (level) {
158 : : case btck_LogLevel_INFO: {
159 : : return BCLog::Level::Info;
160 : : }
161 : 0 : case btck_LogLevel_DEBUG: {
162 : 0 : return BCLog::Level::Debug;
163 : : }
164 : 2 : case btck_LogLevel_TRACE: {
165 : 2 : return BCLog::Level::Trace;
166 : : }
167 : : }
168 : 0 : assert(false);
169 : : }
170 : :
171 : 6 : BCLog::LogFlags get_bclog_flag(btck_LogCategory category)
172 : : {
173 [ - - - - : 6 : switch (category) {
- - - + +
- - + ]
174 : : case btck_LogCategory_BENCH: {
175 : : return BCLog::LogFlags::BENCH;
176 : : }
177 : 0 : case btck_LogCategory_BLOCKSTORAGE: {
178 : 0 : return BCLog::LogFlags::BLOCKSTORAGE;
179 : : }
180 : 0 : case btck_LogCategory_COINDB: {
181 : 0 : return BCLog::LogFlags::COINDB;
182 : : }
183 : 0 : case btck_LogCategory_LEVELDB: {
184 : 0 : return BCLog::LogFlags::LEVELDB;
185 : : }
186 : 0 : case btck_LogCategory_MEMPOOL: {
187 : 0 : return BCLog::LogFlags::MEMPOOL;
188 : : }
189 : 0 : case btck_LogCategory_PRUNE: {
190 : 0 : return BCLog::LogFlags::PRUNE;
191 : : }
192 : 0 : case btck_LogCategory_RAND: {
193 : 0 : return BCLog::LogFlags::RAND;
194 : : }
195 : 0 : case btck_LogCategory_REINDEX: {
196 : 0 : return BCLog::LogFlags::REINDEX;
197 : : }
198 : 2 : case btck_LogCategory_VALIDATION: {
199 : 2 : return BCLog::LogFlags::VALIDATION;
200 : : }
201 : 2 : case btck_LogCategory_KERNEL: {
202 : 2 : return BCLog::LogFlags::KERNEL;
203 : : }
204 : 0 : case btck_LogCategory_ALL: {
205 : 0 : return BCLog::LogFlags::ALL;
206 : : }
207 : : }
208 : 0 : assert(false);
209 : : }
210 : :
211 : 857 : btck_SynchronizationState cast_state(SynchronizationState state)
212 : : {
213 [ + - - + ]: 857 : switch (state) {
214 : : case SynchronizationState::INIT_REINDEX:
215 : : return btck_SynchronizationState_INIT_REINDEX;
216 : 854 : case SynchronizationState::INIT_DOWNLOAD:
217 : 854 : return btck_SynchronizationState_INIT_DOWNLOAD;
218 : 0 : case SynchronizationState::POST_INIT:
219 : 0 : return btck_SynchronizationState_POST_INIT;
220 : : } // no default case, so the compiler can warn about missing cases
221 : 0 : assert(false);
222 : : }
223 : :
224 : 434 : btck_Warning cast_btck_warning(kernel::Warning warning)
225 : : {
226 [ + - - ]: 434 : switch (warning) {
227 : : case kernel::Warning::UNKNOWN_NEW_RULES_ACTIVATED:
228 : : return btck_Warning_UNKNOWN_NEW_RULES_ACTIVATED;
229 : 434 : case kernel::Warning::LARGE_WORK_INVALID_CHAIN:
230 : 434 : return btck_Warning_LARGE_WORK_INVALID_CHAIN;
231 : : } // no default case, so the compiler can warn about missing cases
232 : 0 : assert(false);
233 : : }
234 : :
235 : : struct LoggingConnection {
236 : : std::unique_ptr<std::list<std::function<void(const std::string&)>>::iterator> m_connection;
237 : : void* m_user_data;
238 : : std::function<void(void* user_data)> m_deleter;
239 : :
240 : 9 : LoggingConnection(btck_LogCallback callback, void* user_data, btck_DestroyCallback user_data_destroy_callback)
241 [ + - ]: 9 : {
242 [ + - ]: 9 : LOCK(cs_main);
243 : :
244 [ - + + - : 257 : auto connection{LogInstance().PushBackCallback([callback, user_data](const std::string& str) { callback(user_data, str.c_str(), str.length()); })};
+ - ]
245 : :
246 : : // Only start logging if we just added the connection.
247 [ + - + - : 9 : if (LogInstance().NumConnections() == 1 && !LogInstance().StartLogging()) {
+ + + - +
- - + ]
248 [ # # ]: 0 : LogError("Logger start failed.");
249 [ # # # # ]: 0 : LogInstance().DeleteCallback(connection);
250 [ # # # # ]: 0 : if (user_data && user_data_destroy_callback) {
251 [ # # ]: 0 : user_data_destroy_callback(user_data);
252 : : }
253 [ # # ]: 0 : throw std::runtime_error("Failed to start logging");
254 : : }
255 : :
256 [ + - ]: 9 : m_connection = std::make_unique<std::list<std::function<void(const std::string&)>>::iterator>(connection);
257 : 9 : m_user_data = user_data;
258 : 9 : m_deleter = user_data_destroy_callback;
259 : :
260 [ + - + + : 9 : LogDebug(BCLog::KERNEL, "Logger connected.");
+ - + - ]
261 : 9 : }
262 : :
263 : 9 : ~LoggingConnection()
264 : : {
265 : 9 : LOCK(cs_main);
266 [ + + ]: 9 : LogDebug(BCLog::KERNEL, "Logger disconnecting.");
267 : :
268 : : // Switch back to buffering by calling DisconnectTestLogger if the
269 : : // connection that we are about to remove is the last one.
270 [ + + ]: 9 : if (LogInstance().NumConnections() == 1) {
271 : 8 : LogInstance().DisconnectTestLogger();
272 : : } else {
273 : 1 : LogInstance().DeleteCallback(*m_connection);
274 : : }
275 : :
276 [ + - ]: 9 : m_connection.reset();
277 [ + - + - ]: 9 : if (m_user_data && m_deleter) {
278 : 9 : m_deleter(m_user_data);
279 : : }
280 : 9 : }
281 : : };
282 : :
283 : : class KernelNotifications final : public kernel::Notifications
284 : : {
285 : : private:
286 : : btck_NotificationInterfaceCallbacks m_cbs;
287 : :
288 : : public:
289 : 19 : KernelNotifications(btck_NotificationInterfaceCallbacks cbs)
290 : 19 : : m_cbs{cbs}
291 : : {
292 : : }
293 : :
294 : 19 : ~KernelNotifications()
295 : 19 : {
296 [ + + + - ]: 19 : if (m_cbs.user_data && m_cbs.user_data_destroy) {
297 : 13 : m_cbs.user_data_destroy(m_cbs.user_data);
298 : : }
299 : 19 : m_cbs.user_data_destroy = nullptr;
300 : 19 : m_cbs.user_data = nullptr;
301 : 19 : }
302 : :
303 : 436 : kernel::InterruptResult blockTip(SynchronizationState state, const CBlockIndex& index, double verification_progress) override
304 : : {
305 [ + + ]: 436 : if (m_cbs.block_tip) m_cbs.block_tip(m_cbs.user_data, cast_state(state), btck_BlockTreeEntry::ref(&index), verification_progress);
306 : 436 : return {};
307 : : }
308 : 423 : void headerTip(SynchronizationState state, int64_t height, int64_t timestamp, bool presync) override
309 : : {
310 [ + - + - ]: 846 : if (m_cbs.header_tip) m_cbs.header_tip(m_cbs.user_data, cast_state(state), height, timestamp, presync ? 1 : 0);
311 : 423 : }
312 : 63 : void progress(const bilingual_str& title, int progress_percent, bool resume_possible) override
313 : : {
314 [ + + + - : 124 : if (m_cbs.progress) m_cbs.progress(m_cbs.user_data, title.original.c_str(), title.original.length(), progress_percent, resume_possible ? 1 : 0);
- + ]
315 : 63 : }
316 : 0 : void warningSet(kernel::Warning id, const bilingual_str& message) override
317 : : {
318 [ # # # # ]: 0 : if (m_cbs.warning_set) m_cbs.warning_set(m_cbs.user_data, cast_btck_warning(id), message.original.c_str(), message.original.length());
319 : 0 : }
320 : 436 : void warningUnset(kernel::Warning id) override
321 : : {
322 [ + + ]: 436 : if (m_cbs.warning_unset) m_cbs.warning_unset(m_cbs.user_data, cast_btck_warning(id));
323 : 436 : }
324 : 0 : void flushError(const bilingual_str& message) override
325 : : {
326 [ # # # # ]: 0 : if (m_cbs.flush_error) m_cbs.flush_error(m_cbs.user_data, message.original.c_str(), message.original.length());
327 : 0 : }
328 : 0 : void fatalError(const bilingual_str& message) override
329 : : {
330 [ # # # # ]: 0 : if (m_cbs.fatal_error) m_cbs.fatal_error(m_cbs.user_data, message.original.c_str(), message.original.length());
331 : 0 : }
332 : : };
333 : :
334 : : class KernelValidationInterface final : public CValidationInterface
335 : : {
336 : : public:
337 : : btck_ValidationInterfaceCallbacks m_cbs;
338 : :
339 : 6 : explicit KernelValidationInterface(const btck_ValidationInterfaceCallbacks vi_cbs) : m_cbs{vi_cbs} {}
340 : :
341 : 6 : ~KernelValidationInterface()
342 : 6 : {
343 [ + - + - ]: 6 : if (m_cbs.user_data && m_cbs.user_data_destroy) {
344 : 6 : m_cbs.user_data_destroy(m_cbs.user_data);
345 : : }
346 : 6 : m_cbs.user_data = nullptr;
347 : 6 : m_cbs.user_data_destroy = nullptr;
348 : 6 : }
349 : :
350 : : protected:
351 : 5 : void BlockChecked(const std::shared_ptr<const CBlock>& block, const BlockValidationState& stateIn) override
352 : : {
353 [ + - ]: 5 : if (m_cbs.block_checked) {
354 : 5 : m_cbs.block_checked(m_cbs.user_data,
355 : : btck_Block::copy(btck_Block::ref(&block)),
356 : : btck_BlockValidationState::ref(&stateIn));
357 : : }
358 : 5 : }
359 : :
360 : 0 : void NewPoWValidBlock(const CBlockIndex* pindex, const std::shared_ptr<const CBlock>& block) override
361 : : {
362 [ # # ]: 0 : if (m_cbs.pow_valid_block) {
363 : 0 : m_cbs.pow_valid_block(m_cbs.user_data,
364 : : btck_Block::copy(btck_Block::ref(&block)),
365 : : btck_BlockTreeEntry::ref(pindex));
366 : : }
367 : 0 : }
368 : :
369 : 4 : void BlockConnected(const ChainstateRole& role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) override
370 : : {
371 [ + - ]: 4 : if (m_cbs.block_connected) {
372 : 4 : m_cbs.block_connected(m_cbs.user_data,
373 : : btck_Block::copy(btck_Block::ref(&block)),
374 : : btck_BlockTreeEntry::ref(pindex));
375 : : }
376 : 4 : }
377 : :
378 : 0 : void BlockDisconnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) override
379 : : {
380 [ # # ]: 0 : if (m_cbs.block_disconnected) {
381 : 0 : m_cbs.block_disconnected(m_cbs.user_data,
382 : : btck_Block::copy(btck_Block::ref(&block)),
383 : : btck_BlockTreeEntry::ref(pindex));
384 : : }
385 : 0 : }
386 : : };
387 : :
388 : 19 : struct ContextOptions {
389 : : mutable Mutex m_mutex;
390 : : std::unique_ptr<const CChainParams> m_chainparams GUARDED_BY(m_mutex);
391 : : std::shared_ptr<KernelNotifications> m_notifications GUARDED_BY(m_mutex);
392 : : std::shared_ptr<KernelValidationInterface> m_validation_interface GUARDED_BY(m_mutex);
393 : : };
394 : :
395 : : class Context
396 : : {
397 : : public:
398 : : std::unique_ptr<kernel::Context> m_context;
399 : :
400 : : std::shared_ptr<KernelNotifications> m_notifications;
401 : :
402 : : std::unique_ptr<util::SignalInterrupt> m_interrupt;
403 : :
404 : : std::unique_ptr<ValidationSignals> m_signals;
405 : :
406 : : std::unique_ptr<const CChainParams> m_chainparams;
407 : :
408 : : std::shared_ptr<KernelValidationInterface> m_validation_interface;
409 : :
410 : 19 : Context(const ContextOptions* options, bool& sane)
411 : 19 : : m_context{std::make_unique<kernel::Context>()},
412 [ + - + - ]: 19 : m_interrupt{std::make_unique<util::SignalInterrupt>()}
413 : : {
414 [ + - ]: 19 : if (options) {
415 [ + - ]: 19 : LOCK(options->m_mutex);
416 [ + + ]: 19 : if (options->m_chainparams) {
417 [ + - ]: 13 : m_chainparams = std::make_unique<const CChainParams>(*options->m_chainparams);
418 : : }
419 [ + + ]: 19 : if (options->m_notifications) {
420 : 13 : m_notifications = options->m_notifications;
421 : : }
422 [ + + ]: 19 : if (options->m_validation_interface) {
423 [ + - + - ]: 6 : m_signals = std::make_unique<ValidationSignals>(std::make_unique<ImmediateTaskRunner>());
424 : 6 : m_validation_interface = options->m_validation_interface;
425 [ + - + - ]: 18 : m_signals->RegisterSharedValidationInterface(m_validation_interface);
426 : : }
427 : 19 : }
428 : :
429 [ + + ]: 19 : if (!m_chainparams) {
430 [ + - ]: 6 : m_chainparams = CChainParams::Main();
431 : : }
432 [ + + ]: 19 : if (!m_notifications) {
433 [ + - ]: 12 : m_notifications = std::make_shared<KernelNotifications>(btck_NotificationInterfaceCallbacks{
434 [ - + ]: 6 : nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr});
435 : : }
436 : :
437 [ + - - + ]: 19 : if (!kernel::SanityChecks(*m_context)) {
438 : 0 : sane = false;
439 : : }
440 [ - - - - ]: 19 : }
441 : :
442 : 19 : ~Context()
443 : : {
444 [ + + ]: 19 : if (m_signals) {
445 [ + - + - ]: 18 : m_signals->UnregisterSharedValidationInterface(m_validation_interface);
446 : : }
447 [ + + + - ]: 44 : }
448 : : };
449 : :
450 : : //! Helper struct to wrap the ChainstateManager-related Options
451 : : struct ChainstateManagerOptions {
452 : : mutable Mutex m_mutex;
453 : : ChainstateManager::Options m_chainman_options GUARDED_BY(m_mutex);
454 : : node::BlockManager::Options m_blockman_options GUARDED_BY(m_mutex);
455 : : std::shared_ptr<const Context> m_context;
456 : : node::ChainstateLoadOptions m_chainstate_load_options GUARDED_BY(m_mutex);
457 : :
458 : 16 : ChainstateManagerOptions(const std::shared_ptr<const Context>& context, const fs::path& data_dir, const fs::path& blocks_dir)
459 [ + - ]: 16 : : m_chainman_options{ChainstateManager::Options{
460 : 16 : .chainparams = *context->m_chainparams,
461 : : .datadir = data_dir,
462 [ + - ]: 16 : .notifications = *context->m_notifications,
463 [ + - ]: 16 : .signals = context->m_signals.get()}},
464 [ + - ]: 32 : m_blockman_options{node::BlockManager::Options{
465 [ + - ]: 16 : .chainparams = *context->m_chainparams,
466 : : .blocks_dir = blocks_dir,
467 [ + - ]: 16 : .notifications = *context->m_notifications,
468 : : .block_tree_db_params = DBParams{
469 [ + - + - ]: 48 : .path = data_dir / "blocks" / "index",
470 : 16 : .cache_bytes = kernel::CacheSizes{DEFAULT_KERNEL_CACHE}.block_tree_db,
471 : : }}},
472 [ + - ]: 48 : m_context{context}, m_chainstate_load_options{node::ChainstateLoadOptions{}}
473 : : {
474 : 16 : }
475 : : };
476 : :
477 : : struct ChainMan {
478 : : std::unique_ptr<ChainstateManager> m_chainman;
479 : : std::shared_ptr<const Context> m_context;
480 : :
481 : 16 : ChainMan(std::unique_ptr<ChainstateManager> chainman, std::shared_ptr<const Context> context)
482 : 16 : : m_chainman(std::move(chainman)), m_context(std::move(context)) {}
483 : : };
484 : :
485 : : } // namespace
486 : :
487 : : struct btck_Transaction : Handle<btck_Transaction, std::shared_ptr<const CTransaction>> {};
488 : : struct btck_TransactionOutput : Handle<btck_TransactionOutput, CTxOut> {};
489 : : struct btck_ScriptPubkey : Handle<btck_ScriptPubkey, CScript> {};
490 : : struct btck_LoggingConnection : Handle<btck_LoggingConnection, LoggingConnection> {};
491 : : struct btck_ContextOptions : Handle<btck_ContextOptions, ContextOptions> {};
492 : : struct btck_Context : Handle<btck_Context, std::shared_ptr<const Context>> {};
493 : : struct btck_ChainParameters : Handle<btck_ChainParameters, CChainParams> {};
494 : : struct btck_ChainstateManagerOptions : Handle<btck_ChainstateManagerOptions, ChainstateManagerOptions> {};
495 : : struct btck_ChainstateManager : Handle<btck_ChainstateManager, ChainMan> {};
496 : : struct btck_Chain : Handle<btck_Chain, CChain> {};
497 : : struct btck_BlockSpentOutputs : Handle<btck_BlockSpentOutputs, std::shared_ptr<CBlockUndo>> {};
498 : : struct btck_TransactionSpentOutputs : Handle<btck_TransactionSpentOutputs, CTxUndo> {};
499 : : struct btck_Coin : Handle<btck_Coin, Coin> {};
500 : : struct btck_BlockHash : Handle<btck_BlockHash, uint256> {};
501 : : struct btck_TransactionInput : Handle<btck_TransactionInput, CTxIn> {};
502 : : struct btck_TransactionOutPoint: Handle<btck_TransactionOutPoint, COutPoint> {};
503 : : struct btck_Txid: Handle<btck_Txid, Txid> {};
504 : : struct btck_PrecomputedTransactionData : Handle<btck_PrecomputedTransactionData, PrecomputedTransactionData> {};
505 : : struct btck_BlockHeader: Handle<btck_BlockHeader, CBlockHeader> {};
506 : : struct btck_ConsensusParams: Handle<btck_ConsensusParams, Consensus::Params> {};
507 : :
508 : 26 : btck_Transaction* btck_transaction_create(const void* raw_transaction, size_t raw_transaction_len)
509 : : {
510 [ - + ]: 26 : assert(raw_transaction != nullptr || raw_transaction_len == 0);
511 : 26 : try {
512 [ + + ]: 26 : SpanReader stream{std::span{reinterpret_cast<const std::byte*>(raw_transaction), raw_transaction_len}};
513 [ + + + - : 26 : return btck_Transaction::create(std::make_shared<const CTransaction>(deserialize, TX_WITH_WITNESS, stream));
- + ]
514 : 3 : } catch (...) {
515 : 3 : return nullptr;
516 : 3 : }
517 : : }
518 : :
519 : 287 : size_t btck_transaction_count_outputs(const btck_Transaction* transaction)
520 : : {
521 [ - + ]: 287 : return btck_Transaction::get(transaction)->vout.size();
522 : : }
523 : :
524 : 601 : const btck_TransactionOutput* btck_transaction_get_output_at(const btck_Transaction* transaction, size_t output_index)
525 : : {
526 [ - + ]: 601 : const CTransaction& tx = *btck_Transaction::get(transaction);
527 [ - + - + ]: 601 : assert(output_index < tx.vout.size());
528 : 601 : return btck_TransactionOutput::ref(&tx.vout[output_index]);
529 : : }
530 : :
531 : 284 : size_t btck_transaction_count_inputs(const btck_Transaction* transaction)
532 : : {
533 [ - + ]: 284 : return btck_Transaction::get(transaction)->vin.size();
534 : : }
535 : :
536 : 281 : const btck_TransactionInput* btck_transaction_get_input_at(const btck_Transaction* transaction, size_t input_index)
537 : : {
538 [ - + - + ]: 281 : assert(input_index < btck_Transaction::get(transaction)->vin.size());
539 : 281 : return btck_TransactionInput::ref(&btck_Transaction::get(transaction)->vin[input_index]);
540 : : }
541 : :
542 : 1 : uint32_t btck_transaction_get_locktime(const btck_Transaction* transaction)
543 : : {
544 : 1 : return btck_Transaction::get(transaction)->nLockTime;
545 : : }
546 : :
547 : 7633 : const btck_Txid* btck_transaction_get_txid(const btck_Transaction* transaction)
548 : : {
549 : 7633 : return btck_Txid::ref(&btck_Transaction::get(transaction)->GetHash());
550 : : }
551 : :
552 : 384 : btck_Transaction* btck_transaction_copy(const btck_Transaction* transaction)
553 : : {
554 : 384 : return btck_Transaction::copy(transaction);
555 : : }
556 : :
557 : 14 : int btck_transaction_to_bytes(const btck_Transaction* transaction, btck_WriteBytes writer, void* user_data)
558 : : {
559 : 14 : try {
560 : 14 : WriterStream ws{writer, user_data};
561 [ + - ]: 28 : ws << TX_WITH_WITNESS(btck_Transaction::get(transaction));
562 : : return 0;
563 : 0 : } catch (...) {
564 : 0 : return -1;
565 : 0 : }
566 : : }
567 : :
568 : 468 : void btck_transaction_destroy(btck_Transaction* transaction)
569 : : {
570 [ + + ]: 468 : delete transaction;
571 : 468 : }
572 : :
573 : 11 : btck_ScriptPubkey* btck_script_pubkey_create(const void* script_pubkey, size_t script_pubkey_len)
574 : : {
575 [ - + ]: 11 : assert(script_pubkey != nullptr || script_pubkey_len == 0);
576 : 11 : auto data = std::span{reinterpret_cast<const uint8_t*>(script_pubkey), script_pubkey_len};
577 : 11 : return btck_ScriptPubkey::create(data.begin(), data.end());
578 : : }
579 : :
580 : 555 : int btck_script_pubkey_to_bytes(const btck_ScriptPubkey* script_pubkey_, btck_WriteBytes writer, void* user_data)
581 : : {
582 : 555 : const auto& script_pubkey{btck_ScriptPubkey::get(script_pubkey_)};
583 [ + + + + ]: 1317 : return writer(script_pubkey.data(), script_pubkey.size(), user_data);
584 : : }
585 : :
586 : 12 : btck_ScriptPubkey* btck_script_pubkey_copy(const btck_ScriptPubkey* script_pubkey)
587 : : {
588 : 12 : return btck_ScriptPubkey::copy(script_pubkey);
589 : : }
590 : :
591 : 27 : void btck_script_pubkey_destroy(btck_ScriptPubkey* script_pubkey)
592 : : {
593 [ + + ]: 27 : delete script_pubkey;
594 : 27 : }
595 : :
596 : 5 : btck_TransactionOutput* btck_transaction_output_create(const btck_ScriptPubkey* script_pubkey, int64_t amount)
597 : : {
598 : 5 : return btck_TransactionOutput::create(amount, btck_ScriptPubkey::get(script_pubkey));
599 : : }
600 : :
601 : 66 : btck_TransactionOutput* btck_transaction_output_copy(const btck_TransactionOutput* output)
602 : : {
603 : 66 : return btck_TransactionOutput::copy(output);
604 : : }
605 : :
606 : 585 : const btck_ScriptPubkey* btck_transaction_output_get_script_pubkey(const btck_TransactionOutput* output)
607 : : {
608 : 585 : return btck_ScriptPubkey::ref(&btck_TransactionOutput::get(output).scriptPubKey);
609 : : }
610 : :
611 : 388 : int64_t btck_transaction_output_get_amount(const btck_TransactionOutput* output)
612 : : {
613 : 388 : return btck_TransactionOutput::get(output).nValue;
614 : : }
615 : :
616 : 80 : void btck_transaction_output_destroy(btck_TransactionOutput* output)
617 : : {
618 [ + + ]: 80 : delete output;
619 : 80 : }
620 : :
621 : 266 : btck_PrecomputedTransactionData* btck_precomputed_transaction_data_create(
622 : : const btck_Transaction* tx_to,
623 : : const btck_TransactionOutput** spent_outputs_, size_t spent_outputs_len)
624 : : {
625 : 266 : try {
626 [ + - ]: 266 : const CTransaction& tx{*btck_Transaction::get(tx_to)};
627 [ + - ]: 266 : auto txdata{btck_PrecomputedTransactionData::create()};
628 [ + + ]: 266 : if (spent_outputs_ != nullptr && spent_outputs_len > 0) {
629 [ - + - + ]: 55 : assert(spent_outputs_len == tx.vin.size());
630 : 55 : std::vector<CTxOut> spent_outputs;
631 [ + - ]: 55 : spent_outputs.reserve(spent_outputs_len);
632 [ + + ]: 117 : for (size_t i = 0; i < spent_outputs_len; i++) {
633 : 62 : const CTxOut& tx_out{btck_TransactionOutput::get(spent_outputs_[i])};
634 [ + - ]: 62 : spent_outputs.push_back(tx_out);
635 : : }
636 [ + - ]: 55 : btck_PrecomputedTransactionData::get(txdata).Init(tx, std::move(spent_outputs));
637 : 55 : } else {
638 [ + - ]: 211 : btck_PrecomputedTransactionData::get(txdata).Init(tx, {});
639 : : }
640 : :
641 : : return txdata;
642 : 0 : } catch (...) {
643 : 0 : return nullptr;
644 : 0 : }
645 : : }
646 : :
647 : 5 : btck_PrecomputedTransactionData* btck_precomputed_transaction_data_copy(const btck_PrecomputedTransactionData* precomputed_txdata)
648 : : {
649 : 5 : return btck_PrecomputedTransactionData::copy(precomputed_txdata);
650 : : }
651 : :
652 : 273 : void btck_precomputed_transaction_data_destroy(btck_PrecomputedTransactionData* precomputed_txdata)
653 : : {
654 [ + + ]: 273 : delete precomputed_txdata;
655 : 273 : }
656 : :
657 : 80 : int btck_script_pubkey_verify(const btck_ScriptPubkey* script_pubkey,
658 : : const int64_t amount,
659 : : const btck_Transaction* tx_to,
660 : : const btck_PrecomputedTransactionData* precomputed_txdata,
661 : : const unsigned int input_index,
662 : : const btck_ScriptVerificationFlags flags,
663 : : btck_ScriptVerifyStatus* status)
664 : : {
665 : : // Assert that all specified flags are part of the interface before continuing
666 [ - + ]: 80 : assert((flags & ~btck_ScriptVerificationFlags_ALL) == 0);
667 : :
668 [ - + ]: 80 : if (!is_valid_flag_combination(script_verify_flags::from_int(flags))) {
669 [ # # ]: 0 : if (status) *status = btck_ScriptVerifyStatus_ERROR_INVALID_FLAGS_COMBINATION;
670 : 0 : return 0;
671 : : }
672 : :
673 [ - + ]: 80 : const CTransaction& tx{*btck_Transaction::get(tx_to)};
674 [ - + - + ]: 80 : assert(input_index < tx.vin.size());
675 : :
676 [ + + ]: 80 : const PrecomputedTransactionData& txdata{precomputed_txdata ? btck_PrecomputedTransactionData::get(precomputed_txdata) : PrecomputedTransactionData(tx)};
677 : :
678 [ + + + + ]: 80 : if (flags & btck_ScriptVerificationFlags_TAPROOT && txdata.m_spent_outputs.empty()) {
679 [ + - ]: 4 : if (status) *status = btck_ScriptVerifyStatus_ERROR_SPENT_OUTPUTS_REQUIRED;
680 : 4 : return 0;
681 : : }
682 : :
683 [ + - ]: 76 : if (status) *status = btck_ScriptVerifyStatus_OK;
684 : :
685 [ + - ]: 76 : bool result = VerifyScript(tx.vin[input_index].scriptSig,
686 : : btck_ScriptPubkey::get(script_pubkey),
687 [ + - ]: 76 : &tx.vin[input_index].scriptWitness,
688 : : script_verify_flags::from_int(flags),
689 [ + - ]: 76 : TransactionSignatureChecker(&tx, input_index, amount, txdata, MissingDataBehavior::FAIL),
690 : : nullptr);
691 [ - + ]: 76 : return result ? 1 : 0;
692 : 80 : }
693 : :
694 : 66 : btck_TransactionInput* btck_transaction_input_copy(const btck_TransactionInput* input)
695 : : {
696 : 66 : return btck_TransactionInput::copy(input);
697 : : }
698 : :
699 : 268 : const btck_TransactionOutPoint* btck_transaction_input_get_out_point(const btck_TransactionInput* input)
700 : : {
701 : 268 : return btck_TransactionOutPoint::ref(&btck_TransactionInput::get(input).prevout);
702 : : }
703 : :
704 : 1 : uint32_t btck_transaction_input_get_sequence(const btck_TransactionInput* input)
705 : : {
706 : 1 : return btck_TransactionInput::get(input).nSequence;
707 : : }
708 : :
709 : 74 : void btck_transaction_input_destroy(btck_TransactionInput* input)
710 : : {
711 [ + + ]: 74 : delete input;
712 : 74 : }
713 : :
714 : 7 : btck_TransactionOutPoint* btck_transaction_out_point_copy(const btck_TransactionOutPoint* out_point)
715 : : {
716 : 7 : return btck_TransactionOutPoint::copy(out_point);
717 : : }
718 : :
719 : 325 : uint32_t btck_transaction_out_point_get_index(const btck_TransactionOutPoint* out_point)
720 : : {
721 : 325 : return btck_TransactionOutPoint::get(out_point).n;
722 : : }
723 : :
724 : 177 : const btck_Txid* btck_transaction_out_point_get_txid(const btck_TransactionOutPoint* out_point)
725 : : {
726 : 177 : return btck_Txid::ref(&btck_TransactionOutPoint::get(out_point).hash);
727 : : }
728 : :
729 : 9 : void btck_transaction_out_point_destroy(btck_TransactionOutPoint* out_point)
730 : : {
731 [ + + ]: 9 : delete out_point;
732 : 9 : }
733 : :
734 : 7 : btck_Txid* btck_txid_copy(const btck_Txid* txid)
735 : : {
736 : 7 : return btck_Txid::copy(txid);
737 : : }
738 : :
739 : 13 : void btck_txid_to_bytes(const btck_Txid* txid, unsigned char output[32])
740 : : {
741 : 13 : std::memcpy(output, btck_Txid::get(txid).begin(), 32);
742 : 13 : }
743 : :
744 : 7632 : int btck_txid_equals(const btck_Txid* txid1, const btck_Txid* txid2)
745 : : {
746 : 7632 : return btck_Txid::get(txid1) == btck_Txid::get(txid2);
747 : : }
748 : :
749 : 9 : void btck_txid_destroy(btck_Txid* txid)
750 : : {
751 [ + + ]: 9 : delete txid;
752 : 9 : }
753 : :
754 : 6 : void btck_logging_set_options(const btck_LoggingOptions options)
755 : : {
756 : 6 : LOCK(cs_main);
757 [ + - ]: 6 : LogInstance().m_log_timestamps = options.log_timestamps;
758 [ + - ]: 6 : LogInstance().m_log_time_micros = options.log_time_micros;
759 [ + - ]: 6 : LogInstance().m_log_threadnames = options.log_threadnames;
760 [ + - ]: 6 : LogInstance().m_log_sourcelocations = options.log_sourcelocations;
761 [ + - + - ]: 6 : LogInstance().m_always_print_category_level = options.always_print_category_levels;
762 : 6 : }
763 : :
764 : 2 : void btck_logging_set_level_category(btck_LogCategory category, btck_LogLevel level)
765 : : {
766 : 2 : LOCK(cs_main);
767 [ - + ]: 2 : if (category == btck_LogCategory_ALL) {
768 [ # # ]: 0 : LogInstance().SetLogLevel(get_bclog_level(level));
769 : : }
770 : :
771 [ + - + - ]: 2 : LogInstance().AddCategoryLogLevel(get_bclog_flag(category), get_bclog_level(level));
772 : 2 : }
773 : :
774 : 2 : void btck_logging_enable_category(btck_LogCategory category)
775 : : {
776 : 2 : LogInstance().EnableCategory(get_bclog_flag(category));
777 : 2 : }
778 : :
779 : 2 : void btck_logging_disable_category(btck_LogCategory category)
780 : : {
781 : 2 : LogInstance().DisableCategory(get_bclog_flag(category));
782 : 2 : }
783 : :
784 : 0 : void btck_logging_disable()
785 : : {
786 : 0 : LogInstance().DisableLogging();
787 : 0 : }
788 : :
789 : 9 : btck_LoggingConnection* btck_logging_connection_create(btck_LogCallback callback, void* user_data, btck_DestroyCallback user_data_destroy_callback)
790 : : {
791 : 9 : try {
792 [ + - ]: 9 : return btck_LoggingConnection::create(callback, user_data, user_data_destroy_callback);
793 [ - - ]: 0 : } catch (const std::exception&) {
794 : 0 : return nullptr;
795 : 0 : }
796 : : }
797 : :
798 : 9 : void btck_logging_connection_destroy(btck_LoggingConnection* connection)
799 : : {
800 [ + - ]: 9 : delete connection;
801 : 9 : }
802 : :
803 : 15 : btck_ChainParameters* btck_chain_parameters_create(const btck_ChainType chain_type)
804 : : {
805 [ + - - - : 15 : switch (chain_type) {
+ - ]
806 : 6 : case btck_ChainType_MAINNET: {
807 : 6 : return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::Main().release()));
808 : : }
809 : 0 : case btck_ChainType_TESTNET: {
810 : 0 : return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::TestNet().release()));
811 : : }
812 : 0 : case btck_ChainType_TESTNET_4: {
813 : 0 : return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::TestNet4().release()));
814 : : }
815 : 0 : case btck_ChainType_SIGNET: {
816 : 0 : return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::SigNet().release()));
817 : : }
818 : 9 : case btck_ChainType_REGTEST: {
819 : 9 : return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::RegTest().release()));
820 : : }
821 : : }
822 : 0 : assert(false);
823 : : }
824 : :
825 : 5 : btck_ChainParameters* btck_chain_parameters_copy(const btck_ChainParameters* chain_parameters)
826 : : {
827 : 5 : return btck_ChainParameters::copy(chain_parameters);
828 : : }
829 : :
830 : 1 : const btck_ConsensusParams* btck_chain_parameters_get_consensus_params(const btck_ChainParameters* chain_parameters)
831 : : {
832 : 1 : return btck_ConsensusParams::ref(&btck_ChainParameters::get(chain_parameters).GetConsensus());
833 : : }
834 : :
835 : 22 : void btck_chain_parameters_destroy(btck_ChainParameters* chain_parameters)
836 : : {
837 [ + + ]: 22 : delete chain_parameters;
838 : 22 : }
839 : :
840 : 19 : btck_ContextOptions* btck_context_options_create()
841 : : {
842 : 19 : return btck_ContextOptions::create();
843 : : }
844 : :
845 : 13 : void btck_context_options_set_chainparams(btck_ContextOptions* options, const btck_ChainParameters* chain_parameters)
846 : : {
847 : : // Copy the chainparams, so the caller can free it again
848 : 13 : LOCK(btck_ContextOptions::get(options).m_mutex);
849 [ + - + - ]: 13 : btck_ContextOptions::get(options).m_chainparams = std::make_unique<const CChainParams>(btck_ChainParameters::get(chain_parameters));
850 : 13 : }
851 : :
852 : 13 : void btck_context_options_set_notifications(btck_ContextOptions* options, btck_NotificationInterfaceCallbacks notifications)
853 : : {
854 : : // The KernelNotifications are copy-initialized, so the caller can free them again.
855 : 13 : LOCK(btck_ContextOptions::get(options).m_mutex);
856 [ + - - + : 13 : btck_ContextOptions::get(options).m_notifications = std::make_shared<KernelNotifications>(notifications);
+ - ]
857 : 13 : }
858 : :
859 : 6 : void btck_context_options_set_validation_interface(btck_ContextOptions* options, btck_ValidationInterfaceCallbacks vi_cbs)
860 : : {
861 : 6 : LOCK(btck_ContextOptions::get(options).m_mutex);
862 [ + - - + : 6 : btck_ContextOptions::get(options).m_validation_interface = std::make_shared<KernelValidationInterface>(vi_cbs);
+ - ]
863 : 6 : }
864 : :
865 : 19 : void btck_context_options_destroy(btck_ContextOptions* options)
866 : : {
867 [ + - ]: 19 : delete options;
868 : 19 : }
869 : :
870 : 19 : btck_Context* btck_context_create(const btck_ContextOptions* options)
871 : : {
872 : 19 : bool sane{true};
873 : 19 : const ContextOptions* opts = options ? &btck_ContextOptions::get(options) : nullptr;
874 : 19 : auto context{std::make_shared<const Context>(opts, sane)};
875 [ - + ]: 19 : if (!sane) {
876 [ - - + - ]: 19 : LogError("Kernel context sanity check failed.");
877 : : return nullptr;
878 : : }
879 [ + - ]: 19 : return btck_Context::create(context);
880 : 19 : }
881 : :
882 : 5 : btck_Context* btck_context_copy(const btck_Context* context)
883 : : {
884 : 5 : return btck_Context::copy(context);
885 : : }
886 : :
887 : 1 : int btck_context_interrupt(btck_Context* context)
888 : : {
889 [ - + ]: 1 : return (*btck_Context::get(context)->m_interrupt)() ? 0 : -1;
890 : : }
891 : :
892 : 26 : void btck_context_destroy(btck_Context* context)
893 : : {
894 [ + + ]: 26 : delete context;
895 : 26 : }
896 : :
897 : 6 : const btck_BlockTreeEntry* btck_block_tree_entry_get_previous(const btck_BlockTreeEntry* entry)
898 : : {
899 [ + + ]: 6 : if (!btck_BlockTreeEntry::get(entry).pprev) {
900 : 2 : LogInfo("Genesis block has no previous.");
901 : 2 : return nullptr;
902 : : }
903 : :
904 : : return btck_BlockTreeEntry::ref(btck_BlockTreeEntry::get(entry).pprev);
905 : : }
906 : :
907 : 3 : const btck_BlockTreeEntry* btck_block_tree_entry_get_ancestor(const btck_BlockTreeEntry* block_tree_entry, int32_t height)
908 : : {
909 : 3 : const auto* ancestor{btck_BlockTreeEntry::get(block_tree_entry).GetAncestor(height)};
910 [ - + ]: 3 : assert(ancestor);
911 : 3 : return btck_BlockTreeEntry::ref(ancestor);
912 : : }
913 : :
914 : 1 : btck_BlockValidationState* btck_block_validation_state_create()
915 : : {
916 : 1 : return btck_BlockValidationState::create();
917 : : }
918 : :
919 : 0 : btck_BlockValidationState* btck_block_validation_state_copy(const btck_BlockValidationState* state)
920 : : {
921 : 0 : return btck_BlockValidationState::copy(state);
922 : : }
923 : :
924 : 207 : void btck_block_validation_state_destroy(btck_BlockValidationState* state)
925 : : {
926 [ + - ]: 207 : delete state;
927 : 207 : }
928 : :
929 : 218 : btck_ValidationMode btck_block_validation_state_get_validation_mode(const btck_BlockValidationState* block_validation_state_)
930 : : {
931 : 218 : auto& block_validation_state = btck_BlockValidationState::get(block_validation_state_);
932 [ + + ]: 218 : if (block_validation_state.IsValid()) return btck_ValidationMode_VALID;
933 [ + - ]: 4 : if (block_validation_state.IsInvalid()) return btck_ValidationMode_INVALID;
934 : : return btck_ValidationMode_INTERNAL_ERROR;
935 : : }
936 : :
937 : 210 : btck_BlockValidationResult btck_block_validation_state_get_block_validation_result(const btck_BlockValidationState* block_validation_state_)
938 : : {
939 : 210 : auto& block_validation_state = btck_BlockValidationState::get(block_validation_state_);
940 [ + - + + : 210 : switch (block_validation_state.GetResult()) {
- - - - -
+ ]
941 : : case BlockValidationResult::BLOCK_RESULT_UNSET:
942 : : return btck_BlockValidationResult_UNSET;
943 : 1 : case BlockValidationResult::BLOCK_CONSENSUS:
944 : 1 : return btck_BlockValidationResult_CONSENSUS;
945 : 0 : case BlockValidationResult::BLOCK_CACHED_INVALID:
946 : 0 : return btck_BlockValidationResult_CACHED_INVALID;
947 : 2 : case BlockValidationResult::BLOCK_INVALID_HEADER:
948 : 2 : return btck_BlockValidationResult_INVALID_HEADER;
949 : 1 : case BlockValidationResult::BLOCK_MUTATED:
950 : 1 : return btck_BlockValidationResult_MUTATED;
951 : 0 : case BlockValidationResult::BLOCK_MISSING_PREV:
952 : 0 : return btck_BlockValidationResult_MISSING_PREV;
953 : 0 : case BlockValidationResult::BLOCK_INVALID_PREV:
954 : 0 : return btck_BlockValidationResult_INVALID_PREV;
955 : 0 : case BlockValidationResult::BLOCK_TIME_FUTURE:
956 : 0 : return btck_BlockValidationResult_TIME_FUTURE;
957 : 0 : case BlockValidationResult::BLOCK_HEADER_LOW_WORK:
958 : 0 : return btck_BlockValidationResult_HEADER_LOW_WORK;
959 : : } // no default case, so the compiler can warn about missing cases
960 : 0 : assert(false);
961 : : }
962 : :
963 : 20 : 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)
964 : : {
965 [ - + ]: 20 : assert(data_dir != nullptr || data_dir_len == 0);
966 [ - + ]: 20 : assert(blocks_dir != nullptr || blocks_dir_len == 0);
967 [ + + ]: 20 : if (data_dir_len == 0 || blocks_dir_len == 0) {
968 : 4 : LogError("Failed to create chainstate manager options: dir must be non-null and non-empty");
969 : 4 : return nullptr;
970 : : }
971 : 16 : try {
972 [ + - + - : 32 : fs::path abs_data_dir{fs::absolute(fs::PathFromString({data_dir, data_dir_len}))};
+ - ]
973 [ + - ]: 16 : fs::create_directories(abs_data_dir);
974 [ + - + - : 32 : fs::path abs_blocks_dir{fs::absolute(fs::PathFromString({blocks_dir, blocks_dir_len}))};
+ - ]
975 [ + - ]: 16 : fs::create_directories(abs_blocks_dir);
976 [ + - ]: 16 : return btck_ChainstateManagerOptions::create(btck_Context::get(context), abs_data_dir, abs_blocks_dir);
977 [ - - ]: 32 : } catch (const std::exception& e) {
978 [ - - ]: 0 : LogError("Failed to create chainstate manager options: %s", e.what());
979 : 0 : return nullptr;
980 : 0 : }
981 : : }
982 : :
983 : 6 : void btck_chainstate_manager_options_set_worker_threads_num(btck_ChainstateManagerOptions* opts, int worker_threads)
984 : : {
985 : 6 : LOCK(btck_ChainstateManagerOptions::get(opts).m_mutex);
986 [ + - ]: 6 : btck_ChainstateManagerOptions::get(opts).m_chainman_options.worker_threads_num = worker_threads;
987 : 6 : }
988 : :
989 : 16 : void btck_chainstate_manager_options_destroy(btck_ChainstateManagerOptions* options)
990 : : {
991 [ + - ]: 16 : delete options;
992 : 16 : }
993 : :
994 : 6 : int btck_chainstate_manager_options_set_wipe_dbs(btck_ChainstateManagerOptions* chainman_opts, int wipe_block_tree_db, int wipe_chainstate_db)
995 : : {
996 [ + + ]: 6 : if (wipe_block_tree_db == 1 && wipe_chainstate_db != 1) {
997 : 1 : LogError("Wiping the block tree db without also wiping the chainstate db is currently unsupported.");
998 : 1 : return -1;
999 : : }
1000 : 5 : auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1001 : 5 : LOCK(opts.m_mutex);
1002 : 5 : opts.m_blockman_options.block_tree_db_params.wipe_data = wipe_block_tree_db == 1;
1003 : 5 : opts.m_chainstate_load_options.wipe_chainstate_db = wipe_chainstate_db == 1;
1004 [ + - ]: 5 : return 0;
1005 : 5 : }
1006 : :
1007 : 2 : void btck_chainstate_manager_options_update_block_tree_db_in_memory(
1008 : : btck_ChainstateManagerOptions* chainman_opts,
1009 : : int block_tree_db_in_memory)
1010 : : {
1011 : 2 : auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1012 : 2 : LOCK(opts.m_mutex);
1013 [ + - ]: 2 : opts.m_blockman_options.block_tree_db_params.memory_only = block_tree_db_in_memory == 1;
1014 : 2 : }
1015 : :
1016 : 2 : void btck_chainstate_manager_options_update_chainstate_db_in_memory(
1017 : : btck_ChainstateManagerOptions* chainman_opts,
1018 : : int chainstate_db_in_memory)
1019 : : {
1020 : 2 : auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1021 : 2 : LOCK(opts.m_mutex);
1022 [ + - ]: 2 : opts.m_chainstate_load_options.coins_db_in_memory = chainstate_db_in_memory == 1;
1023 : 2 : }
1024 : :
1025 : 16 : btck_ChainstateManager* btck_chainstate_manager_create(
1026 : : const btck_ChainstateManagerOptions* chainman_opts)
1027 : : {
1028 : 16 : auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1029 : 16 : std::unique_ptr<ChainstateManager> chainman;
1030 : 16 : try {
1031 [ + - ]: 16 : LOCK(opts.m_mutex);
1032 [ + - + - ]: 32 : chainman = std::make_unique<ChainstateManager>(*opts.m_context->m_interrupt, opts.m_chainman_options, opts.m_blockman_options);
1033 [ - - ]: 0 : } catch (const std::exception& e) {
1034 [ - - ]: 0 : LogError("Failed to create chainstate manager: %s", e.what());
1035 : 0 : return nullptr;
1036 : 0 : }
1037 : :
1038 : 16 : try {
1039 [ + - + - ]: 48 : const auto chainstate_load_opts{WITH_LOCK(opts.m_mutex, return opts.m_chainstate_load_options)};
1040 : :
1041 [ + - ]: 16 : kernel::CacheSizes cache_sizes{DEFAULT_KERNEL_CACHE};
1042 [ + - - + ]: 16 : auto [status, chainstate_err]{node::LoadChainstate(*chainman, cache_sizes, chainstate_load_opts)};
1043 [ - + ]: 16 : if (status != node::ChainstateLoadStatus::SUCCESS) {
1044 [ # # ]: 0 : LogError("Failed to load chain state from your data directory: %s", chainstate_err.original);
1045 : : return nullptr;
1046 : : }
1047 [ + - ]: 16 : std::tie(status, chainstate_err) = node::VerifyLoadedChainstate(*chainman, chainstate_load_opts);
1048 [ - + ]: 16 : if (status != node::ChainstateLoadStatus::SUCCESS) {
1049 [ # # ]: 0 : LogError("Failed to verify loaded chain state from your datadir: %s", chainstate_err.original);
1050 : : return nullptr;
1051 : : }
1052 [ + - - + ]: 16 : if (auto result = chainman->ActivateBestChains(); !result) {
1053 [ # # # # ]: 0 : LogError("%s", util::ErrorString(result).original);
1054 : 0 : return nullptr;
1055 : 16 : }
1056 [ - - ]: 16 : } catch (const std::exception& e) {
1057 [ - - ]: 0 : LogError("Failed to load chainstate: %s", e.what());
1058 : 0 : return nullptr;
1059 : 0 : }
1060 : :
1061 [ + - ]: 16 : return btck_ChainstateManager::create(std::move(chainman), opts.m_context);
1062 : 16 : }
1063 : :
1064 : 207 : const btck_BlockTreeEntry* btck_chainstate_manager_get_block_tree_entry_by_hash(const btck_ChainstateManager* chainman, const btck_BlockHash* block_hash)
1065 : : {
1066 [ + - + - ]: 621 : auto block_index = WITH_LOCK(btck_ChainstateManager::get(chainman).m_chainman->GetMutex(),
1067 : : return btck_ChainstateManager::get(chainman).m_chainman->m_blockman.LookupBlockIndex(btck_BlockHash::get(block_hash)));
1068 [ - + ]: 207 : if (!block_index) {
1069 [ # # ]: 0 : LogDebug(BCLog::KERNEL, "A block with the given hash is not indexed.");
1070 : 0 : return nullptr;
1071 : : }
1072 : : return btck_BlockTreeEntry::ref(block_index);
1073 : : }
1074 : :
1075 : 206 : const btck_BlockTreeEntry* btck_chainstate_manager_get_best_entry(const btck_ChainstateManager* chainstate_manager)
1076 : : {
1077 : 206 : auto& chainman = *btck_ChainstateManager::get(chainstate_manager).m_chainman;
1078 [ + - ]: 412 : return btck_BlockTreeEntry::ref(WITH_LOCK(chainman.GetMutex(), return chainman.m_best_header));
1079 : : }
1080 : :
1081 : 16 : void btck_chainstate_manager_destroy(btck_ChainstateManager* chainman)
1082 : : {
1083 : 16 : {
1084 : 16 : LOCK(btck_ChainstateManager::get(chainman).m_chainman->GetMutex());
1085 [ + + ]: 33 : for (const auto& chainstate : btck_ChainstateManager::get(chainman).m_chainman->m_chainstates) {
1086 [ + - ]: 34 : if (chainstate->CanFlushToDisk()) {
1087 [ + - ]: 17 : chainstate->ForceFlushStateToDisk();
1088 : 17 : chainstate->ResetCoinsViews();
1089 : : }
1090 : : }
1091 : 16 : }
1092 : :
1093 [ + - ]: 16 : delete chainman;
1094 : 16 : }
1095 : :
1096 : 2 : 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)
1097 : : {
1098 : 2 : try {
1099 : 2 : std::vector<fs::path> import_files;
1100 [ + - ]: 2 : import_files.reserve(block_file_paths_data_len);
1101 [ + + ]: 3 : for (uint32_t i = 0; i < block_file_paths_data_len; i++) {
1102 [ + - ]: 1 : if (block_file_paths_data[i] != nullptr) {
1103 [ + - + - ]: 2 : import_files.emplace_back(std::string{block_file_paths_data[i], block_file_paths_lens[i]}.c_str());
1104 : : }
1105 : : }
1106 [ - + ]: 2 : auto& chainman_ref{*btck_ChainstateManager::get(chainman).m_chainman};
1107 [ - + + - ]: 2 : node::ImportBlocks(chainman_ref, import_files);
1108 [ + - + - ]: 6 : WITH_LOCK(::cs_main, chainman_ref.UpdateIBDStatus());
1109 [ - - ]: 0 : } catch (const std::exception& e) {
1110 [ - - ]: 0 : LogError("Failed to import blocks: %s", e.what());
1111 : 0 : return -1;
1112 : 0 : }
1113 : 2 : return 0;
1114 : : }
1115 : :
1116 : 638 : btck_Block* btck_block_create(const void* raw_block, size_t raw_block_length)
1117 : : {
1118 [ - + ]: 638 : assert(raw_block != nullptr || raw_block_length == 0);
1119 : 638 : auto block{std::make_shared<CBlock>()};
1120 : :
1121 [ + + ]: 638 : SpanReader stream{std::span{reinterpret_cast<const std::byte*>(raw_block), raw_block_length}};
1122 : :
1123 : 638 : try {
1124 [ + + ]: 638 : stream >> TX_WITH_WITNESS(*block);
1125 : 4 : } catch (...) {
1126 [ + - + + : 4 : LogDebug(BCLog::KERNEL, "Block decode failed.");
+ - ]
1127 : 4 : return nullptr;
1128 [ + - ]: 4 : }
1129 : :
1130 [ + - ]: 634 : return btck_Block::create(block);
1131 : 638 : }
1132 : :
1133 : 5 : btck_Block* btck_block_copy(const btck_Block* block)
1134 : : {
1135 : 5 : return btck_Block::copy(block);
1136 : : }
1137 : :
1138 : 7 : int btck_block_check(const btck_Block* block, const btck_ConsensusParams* consensus_params, btck_BlockCheckFlags flags, btck_BlockValidationState* validation_state)
1139 : : {
1140 : 7 : auto& state = btck_BlockValidationState::get(validation_state);
1141 : 7 : state = BlockValidationState{};
1142 : :
1143 : 7 : const bool check_pow = (flags & btck_BlockCheckFlags_POW) != 0;
1144 : 7 : const bool check_merkle = (flags & btck_BlockCheckFlags_MERKLE) != 0;
1145 : :
1146 : 7 : const bool result = CheckBlock(*btck_Block::get(block), state, btck_ConsensusParams::get(consensus_params), /*fCheckPOW=*/check_pow, /*fCheckMerkleRoot=*/check_merkle);
1147 : :
1148 [ + + ]: 7 : return result ? 1 : 0;
1149 : : }
1150 : :
1151 : 6688 : size_t btck_block_count_transactions(const btck_Block* block)
1152 : : {
1153 [ - + ]: 6688 : return btck_Block::get(block)->vtx.size();
1154 : : }
1155 : :
1156 : 8049 : const btck_Transaction* btck_block_get_transaction_at(const btck_Block* block, size_t index)
1157 : : {
1158 [ - + - + ]: 8049 : assert(index < btck_Block::get(block)->vtx.size());
1159 : 8049 : return btck_Transaction::ref(&btck_Block::get(block)->vtx[index]);
1160 : : }
1161 : :
1162 : 208 : btck_BlockHeader* btck_block_get_header(const btck_Block* block)
1163 : : {
1164 : 208 : const auto& block_ptr = btck_Block::get(block);
1165 : 208 : return btck_BlockHeader::create(static_cast<const CBlockHeader&>(*block_ptr));
1166 : : }
1167 : :
1168 : 22 : int btck_block_to_bytes(const btck_Block* block, btck_WriteBytes writer, void* user_data)
1169 : : {
1170 : 22 : try {
1171 : 22 : WriterStream ws{writer, user_data};
1172 [ + - ]: 44 : ws << TX_WITH_WITNESS(*btck_Block::get(block));
1173 : : return 0;
1174 : 0 : } catch (...) {
1175 : 0 : return -1;
1176 : 0 : }
1177 : : }
1178 : :
1179 : 1 : btck_BlockHash* btck_block_get_hash(const btck_Block* block)
1180 : : {
1181 : 1 : return btck_BlockHash::create(btck_Block::get(block)->GetHash());
1182 : : }
1183 : :
1184 : 7329 : void btck_block_destroy(btck_Block* block)
1185 : : {
1186 [ + + ]: 7329 : delete block;
1187 : 7329 : }
1188 : :
1189 : 6676 : btck_Block* btck_block_read(const btck_ChainstateManager* chainman, const btck_BlockTreeEntry* entry)
1190 : : {
1191 : 6676 : auto block{std::make_shared<CBlock>()};
1192 [ + - + + ]: 6676 : if (!btck_ChainstateManager::get(chainman).m_chainman->m_blockman.ReadBlock(*block, btck_BlockTreeEntry::get(entry))) {
1193 [ + - + - ]: 6676 : LogError("Failed to read block.");
1194 : : return nullptr;
1195 : : }
1196 [ + - ]: 6675 : return btck_Block::create(block);
1197 : 6676 : }
1198 : :
1199 : 206 : btck_BlockHeader* btck_block_tree_entry_get_block_header(const btck_BlockTreeEntry* entry)
1200 : : {
1201 : 206 : return btck_BlockHeader::create(btck_BlockTreeEntry::get(entry).GetBlockHeader());
1202 : : }
1203 : :
1204 : 211 : int32_t btck_block_tree_entry_get_height(const btck_BlockTreeEntry* entry)
1205 : : {
1206 : 211 : return btck_BlockTreeEntry::get(entry).nHeight;
1207 : : }
1208 : :
1209 : 207 : const btck_BlockHash* btck_block_tree_entry_get_block_hash(const btck_BlockTreeEntry* entry)
1210 : : {
1211 : 207 : return btck_BlockHash::ref(btck_BlockTreeEntry::get(entry).phashBlock);
1212 : : }
1213 : :
1214 : 10 : int btck_block_tree_entry_equals(const btck_BlockTreeEntry* entry1, const btck_BlockTreeEntry* entry2)
1215 : : {
1216 : 10 : return &btck_BlockTreeEntry::get(entry1) == &btck_BlockTreeEntry::get(entry2);
1217 : : }
1218 : :
1219 : 2 : btck_BlockHash* btck_block_hash_create(const unsigned char block_hash[32])
1220 : : {
1221 : 2 : return btck_BlockHash::create(std::span<const unsigned char>{block_hash, 32});
1222 : : }
1223 : :
1224 : 212 : btck_BlockHash* btck_block_hash_copy(const btck_BlockHash* block_hash)
1225 : : {
1226 : 212 : return btck_BlockHash::copy(block_hash);
1227 : : }
1228 : :
1229 : 18 : void btck_block_hash_to_bytes(const btck_BlockHash* block_hash, unsigned char output[32])
1230 : : {
1231 : 18 : std::memcpy(output, btck_BlockHash::get(block_hash).begin(), 32);
1232 : 18 : }
1233 : :
1234 : 208 : int btck_block_hash_equals(const btck_BlockHash* hash1, const btck_BlockHash* hash2)
1235 : : {
1236 : 208 : return btck_BlockHash::get(hash1) == btck_BlockHash::get(hash2);
1237 : : }
1238 : :
1239 : 632 : void btck_block_hash_destroy(btck_BlockHash* hash)
1240 : : {
1241 [ + + ]: 632 : delete hash;
1242 : 632 : }
1243 : :
1244 : 5 : btck_BlockSpentOutputs* btck_block_spent_outputs_read(const btck_ChainstateManager* chainman, const btck_BlockTreeEntry* entry)
1245 : : {
1246 : 5 : auto block_undo{std::make_shared<CBlockUndo>()};
1247 [ + + ]: 5 : if (btck_BlockTreeEntry::get(entry).nHeight < 1) {
1248 [ + - + - : 1 : LogDebug(BCLog::KERNEL, "The genesis block does not have any spent outputs.");
+ - ]
1249 [ + - ]: 1 : return btck_BlockSpentOutputs::create(block_undo);
1250 : : }
1251 [ + - + + ]: 4 : if (!btck_ChainstateManager::get(chainman).m_chainman->m_blockman.ReadBlockUndo(*block_undo, btck_BlockTreeEntry::get(entry))) {
1252 [ + - + - ]: 5 : LogError("Failed to read block spent outputs data.");
1253 : : return nullptr;
1254 : : }
1255 [ + - ]: 3 : return btck_BlockSpentOutputs::create(block_undo);
1256 : 5 : }
1257 : :
1258 : 5 : btck_BlockSpentOutputs* btck_block_spent_outputs_copy(const btck_BlockSpentOutputs* block_spent_outputs)
1259 : : {
1260 : 5 : return btck_BlockSpentOutputs::copy(block_spent_outputs);
1261 : : }
1262 : :
1263 : 25 : size_t btck_block_spent_outputs_count(const btck_BlockSpentOutputs* block_spent_outputs)
1264 : : {
1265 [ - + ]: 25 : return btck_BlockSpentOutputs::get(block_spent_outputs)->vtxundo.size();
1266 : : }
1267 : :
1268 : 12 : const btck_TransactionSpentOutputs* btck_block_spent_outputs_get_transaction_spent_outputs_at(const btck_BlockSpentOutputs* block_spent_outputs, size_t transaction_index)
1269 : : {
1270 [ - + - + ]: 12 : assert(transaction_index < btck_BlockSpentOutputs::get(block_spent_outputs)->vtxundo.size());
1271 : 12 : const auto* tx_undo{&btck_BlockSpentOutputs::get(block_spent_outputs)->vtxundo.at(transaction_index)};
1272 : 12 : return btck_TransactionSpentOutputs::ref(tx_undo);
1273 : : }
1274 : :
1275 : 11 : void btck_block_spent_outputs_destroy(btck_BlockSpentOutputs* block_spent_outputs)
1276 : : {
1277 [ + + ]: 11 : delete block_spent_outputs;
1278 : 11 : }
1279 : :
1280 : 7 : btck_TransactionSpentOutputs* btck_transaction_spent_outputs_copy(const btck_TransactionSpentOutputs* transaction_spent_outputs)
1281 : : {
1282 : 7 : return btck_TransactionSpentOutputs::copy(transaction_spent_outputs);
1283 : : }
1284 : :
1285 : 22 : size_t btck_transaction_spent_outputs_count(const btck_TransactionSpentOutputs* transaction_spent_outputs)
1286 : : {
1287 [ - + ]: 22 : return btck_TransactionSpentOutputs::get(transaction_spent_outputs).vprevout.size();
1288 : : }
1289 : :
1290 : 9 : void btck_transaction_spent_outputs_destroy(btck_TransactionSpentOutputs* transaction_spent_outputs)
1291 : : {
1292 [ + + ]: 9 : delete transaction_spent_outputs;
1293 : 9 : }
1294 : :
1295 : 12 : const btck_Coin* btck_transaction_spent_outputs_get_coin_at(const btck_TransactionSpentOutputs* transaction_spent_outputs, size_t coin_index)
1296 : : {
1297 [ - + - + ]: 12 : assert(coin_index < btck_TransactionSpentOutputs::get(transaction_spent_outputs).vprevout.size());
1298 : 12 : const Coin* coin{&btck_TransactionSpentOutputs::get(transaction_spent_outputs).vprevout.at(coin_index)};
1299 : 12 : return btck_Coin::ref(coin);
1300 : : }
1301 : :
1302 : 7 : btck_Coin* btck_coin_copy(const btck_Coin* coin)
1303 : : {
1304 : 7 : return btck_Coin::copy(coin);
1305 : : }
1306 : :
1307 : 1 : uint32_t btck_coin_confirmation_height(const btck_Coin* coin)
1308 : : {
1309 : 1 : return btck_Coin::get(coin).nHeight;
1310 : : }
1311 : :
1312 : 1 : int btck_coin_is_coinbase(const btck_Coin* coin)
1313 : : {
1314 [ + - ]: 1 : return btck_Coin::get(coin).IsCoinBase() ? 1 : 0;
1315 : : }
1316 : :
1317 : 2 : const btck_TransactionOutput* btck_coin_get_output(const btck_Coin* coin)
1318 : : {
1319 : 2 : return btck_TransactionOutput::ref(&btck_Coin::get(coin).out);
1320 : : }
1321 : :
1322 : 9 : void btck_coin_destroy(btck_Coin* coin)
1323 : : {
1324 [ + + ]: 9 : delete coin;
1325 : 9 : }
1326 : :
1327 : 421 : int btck_chainstate_manager_process_block(
1328 : : btck_ChainstateManager* chainman,
1329 : : const btck_Block* block,
1330 : : int* _new_block)
1331 : : {
1332 : 421 : bool new_block;
1333 : 421 : auto result = btck_ChainstateManager::get(chainman).m_chainman->ProcessNewBlock(btck_Block::get(block), /*force_processing=*/true, /*min_pow_checked=*/true, /*new_block=*/&new_block);
1334 [ + - ]: 421 : if (_new_block) {
1335 [ + + ]: 424 : *_new_block = new_block ? 1 : 0;
1336 : : }
1337 [ + + ]: 421 : return result ? 0 : -1;
1338 : : }
1339 : :
1340 : 206 : btck_BlockValidationState* btck_chainstate_manager_process_block_header(
1341 : : btck_ChainstateManager* chainstate_manager,
1342 : : const btck_BlockHeader* header)
1343 : : {
1344 : 206 : try {
1345 : 206 : auto& chainman = btck_ChainstateManager::get(chainstate_manager).m_chainman;
1346 : :
1347 [ + - ]: 206 : auto state = btck_BlockValidationState::create();
1348 [ + - ]: 206 : bool result{chainman->ProcessNewBlockHeaders({&btck_BlockHeader::get(header), 1}, /*min_pow_checked=*/true, btck_BlockValidationState::get(state))};
1349 [ - + ]: 206 : assert(result == btck_BlockValidationState::get(state).IsValid());
1350 : : return state;
1351 [ - - ]: 0 : } catch (const std::exception& e) {
1352 [ - - ]: 0 : LogError("Failed to process block header: %s", e.what());
1353 : 0 : return nullptr;
1354 : 0 : }
1355 : : }
1356 : :
1357 : 269 : const btck_Chain* btck_chainstate_manager_get_active_chain(const btck_ChainstateManager* chainman)
1358 : : {
1359 [ + - + - ]: 807 : return btck_Chain::ref(&WITH_LOCK(btck_ChainstateManager::get(chainman).m_chainman->GetMutex(), return btck_ChainstateManager::get(chainman).m_chainman->ActiveChain()));
1360 : : }
1361 : :
1362 : 292 : int32_t btck_chain_get_height(const btck_Chain* chain)
1363 : : {
1364 : 292 : LOCK(::cs_main);
1365 [ - + + - ]: 292 : return btck_Chain::get(chain).Height();
1366 : 292 : }
1367 : :
1368 : 7512 : const btck_BlockTreeEntry* btck_chain_get_by_height(const btck_Chain* chain, int32_t height)
1369 : : {
1370 : 7512 : LOCK(::cs_main);
1371 [ + - + - ]: 15024 : return btck_BlockTreeEntry::ref(btck_Chain::get(chain)[height]);
1372 : 7512 : }
1373 : :
1374 : 207 : int btck_chain_contains(const btck_Chain* chain, const btck_BlockTreeEntry* entry)
1375 : : {
1376 : 207 : LOCK(::cs_main);
1377 [ + + ]: 207 : return btck_Chain::get(chain).Contains(btck_BlockTreeEntry::get(entry)) ? 1 : 0;
1378 : 207 : }
1379 : :
1380 : 4 : btck_BlockHeader* btck_block_header_create(const void* raw_block_header, size_t raw_block_header_len)
1381 : : {
1382 [ - + ]: 4 : assert(raw_block_header != nullptr && raw_block_header_len == 80);
1383 : 4 : auto header{std::make_unique<CBlockHeader>()};
1384 [ + - ]: 4 : SpanReader stream{std::span{reinterpret_cast<const std::byte*>(raw_block_header), raw_block_header_len}};
1385 : :
1386 : 4 : try {
1387 [ + - ]: 4 : stream >> *header;
1388 : 0 : } catch (...) {
1389 [ - - ]: 0 : LogError("Block header decode failed.");
1390 : 0 : return nullptr;
1391 [ - - ]: 0 : }
1392 : :
1393 : 4 : return btck_BlockHeader::ref(header.release());
1394 : 4 : }
1395 : :
1396 : 5 : btck_BlockHeader* btck_block_header_copy(const btck_BlockHeader* header)
1397 : : {
1398 : 5 : return btck_BlockHeader::copy(header);
1399 : : }
1400 : :
1401 : 415 : btck_BlockHash* btck_block_header_get_hash(const btck_BlockHeader* header)
1402 : : {
1403 : 415 : return btck_BlockHash::create(btck_BlockHeader::get(header).GetHash());
1404 : : }
1405 : :
1406 : 1 : const btck_BlockHash* btck_block_header_get_prev_hash(const btck_BlockHeader* header)
1407 : : {
1408 : 1 : return btck_BlockHash::ref(&btck_BlockHeader::get(header).hashPrevBlock);
1409 : : }
1410 : :
1411 : 3 : uint32_t btck_block_header_get_timestamp(const btck_BlockHeader* header)
1412 : : {
1413 : 3 : return btck_BlockHeader::get(header).nTime;
1414 : : }
1415 : :
1416 : 3 : uint32_t btck_block_header_get_bits(const btck_BlockHeader* header)
1417 : : {
1418 : 3 : return btck_BlockHeader::get(header).nBits;
1419 : : }
1420 : :
1421 : 3 : int32_t btck_block_header_get_version(const btck_BlockHeader* header)
1422 : : {
1423 : 3 : return btck_BlockHeader::get(header).nVersion;
1424 : : }
1425 : :
1426 : 3 : uint32_t btck_block_header_get_nonce(const btck_BlockHeader* header)
1427 : : {
1428 : 3 : return btck_BlockHeader::get(header).nNonce;
1429 : : }
1430 : :
1431 : 15 : int btck_block_header_to_bytes(const btck_BlockHeader* header, unsigned char output[80])
1432 : : {
1433 : 15 : try {
1434 [ + - ]: 30 : SpanWriter{std::as_writable_bytes(std::span{output, 80})} << btck_BlockHeader::get(header);
1435 : : return 0;
1436 : 0 : } catch (...) {
1437 : 0 : return -1;
1438 : 0 : }
1439 : : }
1440 : :
1441 : 425 : void btck_block_header_destroy(btck_BlockHeader* header)
1442 : : {
1443 [ + + ]: 425 : delete header;
1444 : 425 : }
1445 : :
1446 : 12 : btck_ValidationMode btck_tx_validation_state_get_validation_mode(const btck_TxValidationState* state_)
1447 : : {
1448 : 12 : const auto& state = btck_TxValidationState::get(state_);
1449 [ + + ]: 12 : if (state.IsValid()) return btck_ValidationMode_VALID;
1450 [ + - ]: 9 : if (state.IsInvalid()) return btck_ValidationMode_INVALID;
1451 : : return btck_ValidationMode_INTERNAL_ERROR;
1452 : : }
1453 : :
1454 : 11 : btck_TxValidationState* btck_tx_validation_state_create()
1455 : : {
1456 : 11 : return btck_TxValidationState::create();
1457 : : }
1458 : :
1459 : 12 : btck_TxValidationResult btck_tx_validation_state_get_tx_validation_result(const btck_TxValidationState* state_)
1460 : : {
1461 [ + - - - : 12 : switch (btck_TxValidationState::get(state_).GetResult()) {
- - - - -
- - - -
+ ]
1462 : : case TxValidationResult::TX_RESULT_UNSET: return btck_TxValidationResult_UNSET;
1463 : 9 : case TxValidationResult::TX_CONSENSUS: return btck_TxValidationResult_CONSENSUS;
1464 : 0 : case TxValidationResult::TX_INPUTS_NOT_STANDARD: return btck_TxValidationResult_INPUTS_NOT_STANDARD;
1465 : 0 : case TxValidationResult::TX_NOT_STANDARD: return btck_TxValidationResult_NOT_STANDARD;
1466 : 0 : case TxValidationResult::TX_MISSING_INPUTS: return btck_TxValidationResult_MISSING_INPUTS;
1467 : 0 : case TxValidationResult::TX_PREMATURE_SPEND: return btck_TxValidationResult_PREMATURE_SPEND;
1468 : 0 : case TxValidationResult::TX_WITNESS_MUTATED: return btck_TxValidationResult_WITNESS_MUTATED;
1469 : 0 : case TxValidationResult::TX_WITNESS_STRIPPED: return btck_TxValidationResult_WITNESS_STRIPPED;
1470 : 0 : case TxValidationResult::TX_CONFLICT: return btck_TxValidationResult_CONFLICT;
1471 : 0 : case TxValidationResult::TX_MEMPOOL_POLICY: return btck_TxValidationResult_MEMPOOL_POLICY;
1472 : 0 : case TxValidationResult::TX_NO_MEMPOOL: return btck_TxValidationResult_NO_MEMPOOL;
1473 : 0 : case TxValidationResult::TX_RECONSIDERABLE: return btck_TxValidationResult_RECONSIDERABLE;
1474 : 0 : case TxValidationResult::TX_UNKNOWN: return btck_TxValidationResult_UNKNOWN;
1475 : : } // no default case, so the compiler can warn about missing cases
1476 : 0 : assert(false);
1477 : : }
1478 : :
1479 : 11 : void btck_tx_validation_state_destroy(btck_TxValidationState* state)
1480 : : {
1481 [ + - ]: 11 : delete state;
1482 : 11 : }
1483 : :
1484 : 12 : int btck_transaction_check(const btck_Transaction* tx, btck_TxValidationState* validation_state)
1485 : : {
1486 : 12 : auto& state = btck_TxValidationState::get(validation_state);
1487 : 12 : state = TxValidationState{};
1488 : 12 : const bool ok = CheckTransaction(*btck_Transaction::get(tx), state);
1489 [ + + ]: 12 : return ok ? 1 : 0;
1490 : : }
|