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