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