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 [ - + + - : 129 : 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 : : uint64_t m_db_cache_bytes GUARDED_BY(m_mutex){DEFAULT_KERNEL_CACHE};
459 : :
460 : 11 : ChainstateManagerOptions(const std::shared_ptr<const Context>& context, const fs::path& data_dir, const fs::path& blocks_dir)
461 [ + - ]: 11 : : m_chainman_options{ChainstateManager::Options{
462 : 11 : .chainparams = *context->m_chainparams,
463 : : .datadir = data_dir,
464 [ + - ]: 11 : .notifications = *context->m_notifications,
465 [ + - ]: 11 : .signals = context->m_signals.get()}},
466 [ + - ]: 22 : m_blockman_options{node::BlockManager::Options{
467 [ + - ]: 11 : .chainparams = *context->m_chainparams,
468 : : .blocks_dir = blocks_dir,
469 [ + - ]: 11 : .notifications = *context->m_notifications,
470 : : .block_tree_db_params = DBParams{
471 [ + - + - ]: 33 : .path = data_dir / "blocks" / "index",
472 : 11 : .cache_bytes = kernel::CacheSizes{DEFAULT_KERNEL_CACHE}.block_tree_db,
473 : : }}},
474 [ + - ]: 33 : m_context{context}, m_chainstate_load_options{node::ChainstateLoadOptions{}}
475 : : {
476 : 11 : }
477 : : };
478 : :
479 : : struct ChainMan {
480 : : std::unique_ptr<ChainstateManager> m_chainman;
481 : : std::shared_ptr<const Context> m_context;
482 : :
483 : 11 : ChainMan(std::unique_ptr<ChainstateManager> chainman, std::shared_ptr<const Context> context)
484 : 11 : : m_chainman(std::move(chainman)), m_context(std::move(context)) {}
485 : : };
486 : :
487 : : } // namespace
488 : :
489 : : struct btck_Transaction : Handle<btck_Transaction, std::shared_ptr<const CTransaction>> {};
490 : : struct btck_TransactionOutput : Handle<btck_TransactionOutput, CTxOut> {};
491 : : struct btck_ScriptPubkey : Handle<btck_ScriptPubkey, CScript> {};
492 : : struct btck_LoggingConnection : Handle<btck_LoggingConnection, LoggingConnection> {};
493 : : struct btck_ContextOptions : Handle<btck_ContextOptions, ContextOptions> {};
494 : : struct btck_Context : Handle<btck_Context, std::shared_ptr<const Context>> {};
495 : : struct btck_ChainParameters : Handle<btck_ChainParameters, CChainParams> {};
496 : : struct btck_ChainstateManagerOptions : Handle<btck_ChainstateManagerOptions, ChainstateManagerOptions> {};
497 : : struct btck_ChainstateManager : Handle<btck_ChainstateManager, ChainMan> {};
498 : : struct btck_Chain : Handle<btck_Chain, CChain> {};
499 : : struct btck_BlockSpentOutputs : Handle<btck_BlockSpentOutputs, std::shared_ptr<CBlockUndo>> {};
500 : : struct btck_TransactionSpentOutputs : Handle<btck_TransactionSpentOutputs, CTxUndo> {};
501 : : struct btck_Coin : Handle<btck_Coin, Coin> {};
502 : : struct btck_BlockHash : Handle<btck_BlockHash, uint256> {};
503 : : struct btck_TransactionInput : Handle<btck_TransactionInput, CTxIn> {};
504 : : struct btck_WitnessStack : Handle<btck_WitnessStack, CScriptWitness> {};
505 : : struct btck_TransactionOutPoint: Handle<btck_TransactionOutPoint, COutPoint> {};
506 : : struct btck_Txid: Handle<btck_Txid, Txid> {};
507 : : struct btck_PrecomputedTransactionData : Handle<btck_PrecomputedTransactionData, PrecomputedTransactionData> {};
508 : : struct btck_BlockHeader: Handle<btck_BlockHeader, CBlockHeader> {};
509 : : struct btck_ConsensusParams: Handle<btck_ConsensusParams, Consensus::Params> {};
510 : :
511 : 27 : btck_Transaction* btck_transaction_create(const void* raw_transaction, size_t raw_transaction_len)
512 : : {
513 [ - + ]: 27 : assert(raw_transaction != nullptr || raw_transaction_len == 0);
514 : 27 : try {
515 [ + + ]: 27 : SpanReader stream{std::span{reinterpret_cast<const std::byte*>(raw_transaction), raw_transaction_len}};
516 [ + + + - : 27 : return btck_Transaction::create(std::make_shared<const CTransaction>(deserialize, TX_WITH_WITNESS, stream));
- + ]
517 : 3 : } catch (...) {
518 : 3 : return nullptr;
519 : 3 : }
520 : : }
521 : :
522 : 287 : size_t btck_transaction_count_outputs(const btck_Transaction* transaction)
523 : : {
524 [ - + ]: 287 : return btck_Transaction::get(transaction)->vout.size();
525 : : }
526 : :
527 : 601 : const btck_TransactionOutput* btck_transaction_get_output_at(const btck_Transaction* transaction, size_t output_index)
528 : : {
529 [ - + ]: 601 : const CTransaction& tx = *btck_Transaction::get(transaction);
530 [ - + - + ]: 601 : assert(output_index < tx.vout.size());
531 : 601 : return btck_TransactionOutput::ref(&tx.vout[output_index]);
532 : : }
533 : :
534 : 284 : size_t btck_transaction_count_inputs(const btck_Transaction* transaction)
535 : : {
536 [ - + ]: 284 : return btck_Transaction::get(transaction)->vin.size();
537 : : }
538 : :
539 : 282 : const btck_TransactionInput* btck_transaction_get_input_at(const btck_Transaction* transaction, size_t input_index)
540 : : {
541 [ - + - + ]: 282 : assert(input_index < btck_Transaction::get(transaction)->vin.size());
542 : 282 : return btck_TransactionInput::ref(&btck_Transaction::get(transaction)->vin[input_index]);
543 : : }
544 : :
545 : 1 : uint32_t btck_transaction_get_locktime(const btck_Transaction* transaction)
546 : : {
547 : 1 : return btck_Transaction::get(transaction)->nLockTime;
548 : : }
549 : :
550 : 7633 : const btck_Txid* btck_transaction_get_txid(const btck_Transaction* transaction)
551 : : {
552 : 7633 : return btck_Txid::ref(&btck_Transaction::get(transaction)->GetHash());
553 : : }
554 : :
555 : 384 : btck_Transaction* btck_transaction_copy(const btck_Transaction* transaction)
556 : : {
557 : 384 : return btck_Transaction::copy(transaction);
558 : : }
559 : :
560 : 14 : int btck_transaction_to_bytes(const btck_Transaction* transaction, btck_WriteBytes writer, void* user_data)
561 : : {
562 : 14 : try {
563 : 14 : WriterStream ws{writer, user_data};
564 [ + - ]: 28 : ws << TX_WITH_WITNESS(btck_Transaction::get(transaction));
565 : : return 0;
566 : 0 : } catch (...) {
567 : 0 : return -1;
568 : 0 : }
569 : : }
570 : :
571 : 469 : void btck_transaction_destroy(btck_Transaction* transaction)
572 : : {
573 [ + + ]: 469 : delete transaction;
574 : 469 : }
575 : :
576 : 11 : btck_ScriptPubkey* btck_script_pubkey_create(const void* script_pubkey, size_t script_pubkey_len)
577 : : {
578 [ - + ]: 11 : assert(script_pubkey != nullptr || script_pubkey_len == 0);
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 : 555 : int btck_script_pubkey_to_bytes(const btck_ScriptPubkey* script_pubkey_, btck_WriteBytes writer, void* user_data)
584 : : {
585 : 555 : const auto& script_pubkey{btck_ScriptPubkey::get(script_pubkey_)};
586 [ + + + + ]: 1317 : 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 : 66 : btck_TransactionOutput* btck_transaction_output_copy(const btck_TransactionOutput* output)
605 : : {
606 : 66 : return btck_TransactionOutput::copy(output);
607 : : }
608 : :
609 : 585 : const btck_ScriptPubkey* btck_transaction_output_get_script_pubkey(const btck_TransactionOutput* output)
610 : : {
611 : 585 : return btck_ScriptPubkey::ref(&btck_TransactionOutput::get(output).scriptPubKey);
612 : : }
613 : :
614 : 388 : int64_t btck_transaction_output_get_amount(const btck_TransactionOutput* output)
615 : : {
616 : 388 : return btck_TransactionOutput::get(output).nValue;
617 : : }
618 : :
619 : 80 : void btck_transaction_output_destroy(btck_TransactionOutput* output)
620 : : {
621 [ + + ]: 80 : delete output;
622 : 80 : }
623 : :
624 : 266 : 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 : 266 : try {
629 [ + - ]: 266 : const CTransaction& tx{*btck_Transaction::get(tx_to)};
630 [ + - ]: 266 : auto txdata{btck_PrecomputedTransactionData::create()};
631 [ + + ]: 266 : if (spent_outputs_ != nullptr && spent_outputs_len > 0) {
632 [ - + - + ]: 55 : assert(spent_outputs_len == tx.vin.size());
633 : 55 : std::vector<CTxOut> spent_outputs;
634 [ + - ]: 55 : spent_outputs.reserve(spent_outputs_len);
635 [ + + ]: 117 : for (size_t i = 0; i < spent_outputs_len; i++) {
636 : 62 : const CTxOut& tx_out{btck_TransactionOutput::get(spent_outputs_[i])};
637 [ + - ]: 62 : spent_outputs.push_back(tx_out);
638 : : }
639 [ + - ]: 55 : btck_PrecomputedTransactionData::get(txdata).Init(tx, std::move(spent_outputs));
640 : 55 : } 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 : 273 : void btck_precomputed_transaction_data_destroy(btck_PrecomputedTransactionData* precomputed_txdata)
656 : : {
657 [ + + ]: 273 : delete precomputed_txdata;
658 : 273 : }
659 : :
660 : 80 : 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 [ - + ]: 80 : assert((flags & ~btck_ScriptVerificationFlags_ALL) == 0);
670 : :
671 [ - + ]: 80 : 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 [ - + ]: 80 : const CTransaction& tx{*btck_Transaction::get(tx_to)};
677 [ - + - + ]: 80 : assert(input_index < tx.vin.size());
678 : :
679 [ + + ]: 80 : const PrecomputedTransactionData& txdata{precomputed_txdata ? btck_PrecomputedTransactionData::get(precomputed_txdata) : PrecomputedTransactionData(tx)};
680 : :
681 [ + + + + ]: 80 : 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 [ + - ]: 76 : if (status) *status = btck_ScriptVerifyStatus_OK;
687 : :
688 [ + - ]: 76 : bool result = VerifyScript(tx.vin[input_index].scriptSig,
689 : : btck_ScriptPubkey::get(script_pubkey),
690 [ + - ]: 76 : &tx.vin[input_index].scriptWitness,
691 : : script_verify_flags::from_int(flags),
692 [ + - ]: 76 : TransactionSignatureChecker(&tx, input_index, amount, txdata, MissingDataBehavior::FAIL),
693 : : nullptr);
694 [ - + ]: 76 : return result ? 1 : 0;
695 : 80 : }
696 : :
697 : 66 : btck_TransactionInput* btck_transaction_input_copy(const btck_TransactionInput* input)
698 : : {
699 : 66 : return btck_TransactionInput::copy(input);
700 : : }
701 : :
702 : 268 : const btck_TransactionOutPoint* btck_transaction_input_get_out_point(const btck_TransactionInput* input)
703 : : {
704 : 268 : 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 : 2 : const btck_WitnessStack* btck_transaction_input_get_witness_stack(const btck_TransactionInput* input)
713 : : {
714 : 2 : return btck_WitnessStack::ref(&btck_TransactionInput::get(input).scriptWitness);
715 : : }
716 : :
717 : 3 : int btck_transaction_input_get_script_sig(const btck_TransactionInput* input, btck_WriteBytes writer, void* user_data)
718 : : {
719 : 3 : const auto& script_sig{btck_TransactionInput::get(input).scriptSig};
720 [ + + + + ]: 8 : return writer(script_sig.data(), script_sig.size(), user_data);
721 : : }
722 : :
723 : 74 : void btck_transaction_input_destroy(btck_TransactionInput* input)
724 : : {
725 [ + + ]: 74 : delete input;
726 : 74 : }
727 : :
728 : 9 : size_t btck_witness_stack_count_items(const btck_WitnessStack* witness_stack)
729 : : {
730 [ - + ]: 9 : return btck_WitnessStack::get(witness_stack).stack.size();
731 : : }
732 : :
733 : 12 : int btck_witness_stack_get_item_at(const btck_WitnessStack* witness_stack, size_t index, btck_WriteBytes writer, void* user_data)
734 : : {
735 : 12 : const auto& stack{btck_WitnessStack::get(witness_stack).stack};
736 [ - + - + ]: 12 : assert(index < stack.size());
737 [ - + ]: 12 : return writer(stack[index].data(), stack[index].size(), user_data);
738 : : }
739 : :
740 : 7 : btck_WitnessStack* btck_witness_stack_copy(const btck_WitnessStack* witness_stack)
741 : : {
742 : 7 : return btck_WitnessStack::copy(witness_stack);
743 : : }
744 : :
745 : 9 : void btck_witness_stack_destroy(btck_WitnessStack* witness_stack)
746 : : {
747 [ + + ]: 9 : delete witness_stack;
748 : 9 : }
749 : :
750 : 7 : btck_TransactionOutPoint* btck_transaction_out_point_copy(const btck_TransactionOutPoint* out_point)
751 : : {
752 : 7 : return btck_TransactionOutPoint::copy(out_point);
753 : : }
754 : :
755 : 325 : uint32_t btck_transaction_out_point_get_index(const btck_TransactionOutPoint* out_point)
756 : : {
757 : 325 : return btck_TransactionOutPoint::get(out_point).n;
758 : : }
759 : :
760 : 177 : const btck_Txid* btck_transaction_out_point_get_txid(const btck_TransactionOutPoint* out_point)
761 : : {
762 : 177 : return btck_Txid::ref(&btck_TransactionOutPoint::get(out_point).hash);
763 : : }
764 : :
765 : 9 : void btck_transaction_out_point_destroy(btck_TransactionOutPoint* out_point)
766 : : {
767 [ + + ]: 9 : delete out_point;
768 : 9 : }
769 : :
770 : 7 : btck_Txid* btck_txid_copy(const btck_Txid* txid)
771 : : {
772 : 7 : return btck_Txid::copy(txid);
773 : : }
774 : :
775 : 13 : void btck_txid_to_bytes(const btck_Txid* txid, unsigned char output[32])
776 : : {
777 : 13 : std::memcpy(output, btck_Txid::get(txid).begin(), 32);
778 : 13 : }
779 : :
780 : 7632 : int btck_txid_equals(const btck_Txid* txid1, const btck_Txid* txid2)
781 : : {
782 : 7632 : return btck_Txid::get(txid1) == btck_Txid::get(txid2);
783 : : }
784 : :
785 : 9 : void btck_txid_destroy(btck_Txid* txid)
786 : : {
787 [ + + ]: 9 : delete txid;
788 : 9 : }
789 : :
790 : 1 : void btck_logging_set_options(const btck_LoggingOptions options)
791 : : {
792 : 1 : LOCK(cs_main);
793 [ + - ]: 1 : LogInstance().m_log_timestamps = options.log_timestamps;
794 [ + - ]: 1 : LogInstance().m_log_time_micros = options.log_time_micros;
795 [ + - ]: 1 : LogInstance().m_log_threadnames = options.log_threadnames;
796 [ + - ]: 1 : LogInstance().m_log_sourcelocations = options.log_sourcelocations;
797 [ + - + - ]: 1 : LogInstance().m_always_print_category_level = options.always_print_category_levels;
798 : 1 : }
799 : :
800 : 2 : void btck_logging_set_level_category(btck_LogCategory category, btck_LogLevel level)
801 : : {
802 : 2 : LOCK(cs_main);
803 [ - + ]: 2 : if (category == btck_LogCategory_ALL) {
804 [ # # ]: 0 : LogInstance().SetLogLevel(get_bclog_level(level));
805 : : }
806 : :
807 [ + - + - ]: 2 : LogInstance().AddCategoryLogLevel(get_bclog_flag(category), get_bclog_level(level));
808 : 2 : }
809 : :
810 : 2 : void btck_logging_enable_category(btck_LogCategory category)
811 : : {
812 : 2 : LogInstance().EnableCategory(get_bclog_flag(category));
813 : 2 : }
814 : :
815 : 2 : void btck_logging_disable_category(btck_LogCategory category)
816 : : {
817 : 2 : LogInstance().DisableCategory(get_bclog_flag(category));
818 : 2 : }
819 : :
820 : 0 : void btck_logging_disable()
821 : : {
822 : 0 : LogInstance().DisableLogging();
823 : 0 : }
824 : :
825 : 4 : btck_LoggingConnection* btck_logging_connection_create(btck_LogCallback callback, void* user_data, btck_DestroyCallback user_data_destroy_callback)
826 : : {
827 : 4 : try {
828 [ + - ]: 4 : return btck_LoggingConnection::create(callback, user_data, user_data_destroy_callback);
829 [ - - ]: 0 : } catch (const std::exception&) {
830 : 0 : return nullptr;
831 : 0 : }
832 : : }
833 : :
834 : 4 : void btck_logging_connection_destroy(btck_LoggingConnection* connection)
835 : : {
836 [ + - ]: 4 : delete connection;
837 : 4 : }
838 : :
839 : 11 : btck_ChainParameters* btck_chain_parameters_create(const btck_ChainType chain_type)
840 : : {
841 [ + - - + : 11 : switch (chain_type) {
+ - ]
842 : 6 : case btck_ChainType_MAINNET: {
843 : 6 : return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::Main().release()));
844 : : }
845 : 0 : case btck_ChainType_TESTNET: {
846 : 0 : return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::TestNet().release()));
847 : : }
848 : 0 : case btck_ChainType_TESTNET_4: {
849 : 0 : return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::TestNet4().release()));
850 : : }
851 : 1 : case btck_ChainType_SIGNET: {
852 : 1 : return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::SigNet().release()));
853 : : }
854 : 4 : case btck_ChainType_REGTEST: {
855 : 4 : return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::RegTest().release()));
856 : : }
857 : : }
858 : 0 : assert(false);
859 : : }
860 : :
861 : 1 : btck_ChainParameters* btck_chain_parameters_create_signet(const void* challenge, size_t challenge_len)
862 : : {
863 [ - + ]: 1 : assert(challenge != nullptr || challenge_len == 0);
864 : 1 : const uint8_t* p = static_cast<const uint8_t*>(challenge);
865 : 1 : CChainParams::SigNetOptions options{
866 [ + - + - ]: 2 : .challenge = std::vector<uint8_t>{p, p + challenge_len},
867 [ + - ]: 1 : };
868 [ + - ]: 2 : return btck_ChainParameters::ref(const_cast<CChainParams*>(CChainParams::SigNet(options).release()));
869 : 1 : }
870 : :
871 : 10 : btck_ChainParameters* btck_chain_parameters_copy(const btck_ChainParameters* chain_parameters)
872 : : {
873 : 10 : return btck_ChainParameters::copy(chain_parameters);
874 : : }
875 : :
876 : 1 : const btck_ConsensusParams* btck_chain_parameters_get_consensus_params(const btck_ChainParameters* chain_parameters)
877 : : {
878 : 1 : return btck_ConsensusParams::ref(&btck_ChainParameters::get(chain_parameters).GetConsensus());
879 : : }
880 : :
881 : 26 : void btck_chain_parameters_destroy(btck_ChainParameters* chain_parameters)
882 : : {
883 [ + + ]: 26 : delete chain_parameters;
884 : 26 : }
885 : :
886 : 14 : btck_ContextOptions* btck_context_options_create()
887 : : {
888 : 14 : return btck_ContextOptions::create();
889 : : }
890 : :
891 : 8 : void btck_context_options_set_chainparams(btck_ContextOptions* options, const btck_ChainParameters* chain_parameters)
892 : : {
893 : : // Copy the chainparams, so the caller can free it again
894 : 8 : LOCK(btck_ContextOptions::get(options).m_mutex);
895 [ + - + - ]: 8 : btck_ContextOptions::get(options).m_chainparams = std::make_unique<const CChainParams>(btck_ChainParameters::get(chain_parameters));
896 : 8 : }
897 : :
898 : 8 : void btck_context_options_set_notifications(btck_ContextOptions* options, btck_NotificationInterfaceCallbacks notifications)
899 : : {
900 : : // The KernelNotifications are copy-initialized, so the caller can free them again.
901 : 8 : LOCK(btck_ContextOptions::get(options).m_mutex);
902 [ + - - + : 8 : btck_ContextOptions::get(options).m_notifications = std::make_shared<KernelNotifications>(notifications);
+ - ]
903 : 8 : }
904 : :
905 : 1 : void btck_context_options_set_validation_interface(btck_ContextOptions* options, btck_ValidationInterfaceCallbacks vi_cbs)
906 : : {
907 : 1 : LOCK(btck_ContextOptions::get(options).m_mutex);
908 [ + - - + : 1 : btck_ContextOptions::get(options).m_validation_interface = std::make_shared<KernelValidationInterface>(vi_cbs);
+ - ]
909 : 1 : }
910 : :
911 : 14 : void btck_context_options_destroy(btck_ContextOptions* options)
912 : : {
913 [ + - ]: 14 : delete options;
914 : 14 : }
915 : :
916 : 14 : btck_Context* btck_context_create(const btck_ContextOptions* options)
917 : : {
918 : 14 : bool sane{true};
919 : 14 : const ContextOptions* opts = options ? &btck_ContextOptions::get(options) : nullptr;
920 : 14 : auto context{std::make_shared<const Context>(opts, sane)};
921 [ - + ]: 14 : if (!sane) {
922 [ - - + - ]: 14 : LogError("Kernel context sanity check failed.");
923 : : return nullptr;
924 : : }
925 [ + - ]: 14 : return btck_Context::create(context);
926 : 14 : }
927 : :
928 : 5 : btck_Context* btck_context_copy(const btck_Context* context)
929 : : {
930 : 5 : return btck_Context::copy(context);
931 : : }
932 : :
933 : 1 : int btck_context_interrupt(btck_Context* context)
934 : : {
935 [ - + ]: 1 : return (*btck_Context::get(context)->m_interrupt)() ? 0 : -1;
936 : : }
937 : :
938 : 21 : void btck_context_destroy(btck_Context* context)
939 : : {
940 [ + + ]: 21 : delete context;
941 : 21 : }
942 : :
943 : 6 : const btck_BlockTreeEntry* btck_block_tree_entry_get_previous(const btck_BlockTreeEntry* entry)
944 : : {
945 [ + + ]: 6 : if (!btck_BlockTreeEntry::get(entry).pprev) {
946 : 2 : LogInfo("Genesis block has no previous.");
947 : 2 : return nullptr;
948 : : }
949 : :
950 : : return btck_BlockTreeEntry::ref(btck_BlockTreeEntry::get(entry).pprev);
951 : : }
952 : :
953 : 3 : const btck_BlockTreeEntry* btck_block_tree_entry_get_ancestor(const btck_BlockTreeEntry* block_tree_entry, int32_t height)
954 : : {
955 : 3 : const auto* ancestor{btck_BlockTreeEntry::get(block_tree_entry).GetAncestor(height)};
956 [ - + ]: 3 : assert(ancestor);
957 : 3 : return btck_BlockTreeEntry::ref(ancestor);
958 : : }
959 : :
960 : 1 : btck_BlockValidationState* btck_block_validation_state_create()
961 : : {
962 : 1 : return btck_BlockValidationState::create();
963 : : }
964 : :
965 : 0 : btck_BlockValidationState* btck_block_validation_state_copy(const btck_BlockValidationState* state)
966 : : {
967 : 0 : return btck_BlockValidationState::copy(state);
968 : : }
969 : :
970 : 207 : void btck_block_validation_state_destroy(btck_BlockValidationState* state)
971 : : {
972 [ + - ]: 207 : delete state;
973 : 207 : }
974 : :
975 : 216 : btck_ValidationMode btck_block_validation_state_get_validation_mode(const btck_BlockValidationState* block_validation_state_)
976 : : {
977 : 216 : auto& block_validation_state = btck_BlockValidationState::get(block_validation_state_);
978 [ + + ]: 216 : if (block_validation_state.IsValid()) return btck_ValidationMode_VALID;
979 [ + - ]: 4 : if (block_validation_state.IsInvalid()) return btck_ValidationMode_INVALID;
980 : : return btck_ValidationMode_INTERNAL_ERROR;
981 : : }
982 : :
983 : 210 : btck_BlockValidationResult btck_block_validation_state_get_block_validation_result(const btck_BlockValidationState* block_validation_state_)
984 : : {
985 : 210 : auto& block_validation_state = btck_BlockValidationState::get(block_validation_state_);
986 [ + - + + : 210 : switch (block_validation_state.GetResult()) {
- - - - -
+ ]
987 : : case BlockValidationResult::BLOCK_RESULT_UNSET:
988 : : return btck_BlockValidationResult_UNSET;
989 : 1 : case BlockValidationResult::BLOCK_CONSENSUS:
990 : 1 : return btck_BlockValidationResult_CONSENSUS;
991 : 0 : case BlockValidationResult::BLOCK_CACHED_INVALID:
992 : 0 : return btck_BlockValidationResult_CACHED_INVALID;
993 : 2 : case BlockValidationResult::BLOCK_INVALID_HEADER:
994 : 2 : return btck_BlockValidationResult_INVALID_HEADER;
995 : 1 : case BlockValidationResult::BLOCK_MUTATED:
996 : 1 : return btck_BlockValidationResult_MUTATED;
997 : 0 : case BlockValidationResult::BLOCK_MISSING_PREV:
998 : 0 : return btck_BlockValidationResult_MISSING_PREV;
999 : 0 : case BlockValidationResult::BLOCK_INVALID_PREV:
1000 : 0 : return btck_BlockValidationResult_INVALID_PREV;
1001 : 0 : case BlockValidationResult::BLOCK_TIME_FUTURE:
1002 : 0 : return btck_BlockValidationResult_TIME_FUTURE;
1003 : 0 : case BlockValidationResult::BLOCK_HEADER_LOW_WORK:
1004 : 0 : return btck_BlockValidationResult_HEADER_LOW_WORK;
1005 : : } // no default case, so the compiler can warn about missing cases
1006 : 0 : assert(false);
1007 : : }
1008 : :
1009 : 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)
1010 : : {
1011 [ - + ]: 15 : assert(data_dir != nullptr || data_dir_len == 0);
1012 [ - + ]: 15 : assert(blocks_dir != nullptr || blocks_dir_len == 0);
1013 [ + + ]: 15 : if (data_dir_len == 0 || blocks_dir_len == 0) {
1014 : 4 : LogError("Failed to create chainstate manager options: dir must be non-null and non-empty");
1015 : 4 : return nullptr;
1016 : : }
1017 : 11 : try {
1018 [ + - + - : 22 : fs::path abs_data_dir{fs::absolute(fs::PathFromString({data_dir, data_dir_len}))};
+ - ]
1019 [ + - ]: 11 : fs::create_directories(abs_data_dir);
1020 [ + - + - : 22 : fs::path abs_blocks_dir{fs::absolute(fs::PathFromString({blocks_dir, blocks_dir_len}))};
+ - ]
1021 [ + - ]: 11 : fs::create_directories(abs_blocks_dir);
1022 [ + - ]: 11 : return btck_ChainstateManagerOptions::create(btck_Context::get(context), abs_data_dir, abs_blocks_dir);
1023 [ - - ]: 22 : } catch (const std::exception& e) {
1024 [ - - ]: 0 : LogError("Failed to create chainstate manager options: %s", e.what());
1025 : 0 : return nullptr;
1026 : 0 : }
1027 : : }
1028 : :
1029 : 1 : void btck_chainstate_manager_options_set_worker_threads_num(btck_ChainstateManagerOptions* opts, int worker_threads)
1030 : : {
1031 : 1 : LOCK(btck_ChainstateManagerOptions::get(opts).m_mutex);
1032 [ + - ]: 1 : btck_ChainstateManagerOptions::get(opts).m_chainman_options.worker_threads_num = worker_threads;
1033 : 1 : }
1034 : :
1035 : 2 : int btck_chainstate_manager_options_set_database_cache_bytes(btck_ChainstateManagerOptions* chainman_opts, uint64_t database_cache_bytes)
1036 : : {
1037 [ + + ]: 2 : if (database_cache_bytes < MIN_DBCACHE_BYTES || database_cache_bytes > MAX_DBCACHE_BYTES) {
1038 : 1 : LogError("Failed to set database cache: size is outside the supported range.");
1039 : 1 : return -1;
1040 : : }
1041 : :
1042 : 1 : auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1043 : 1 : LOCK(opts.m_mutex);
1044 : 1 : opts.m_db_cache_bytes = database_cache_bytes;
1045 : 1 : opts.m_blockman_options.block_tree_db_params.cache_bytes = kernel::CacheSizes{database_cache_bytes}.block_tree_db;
1046 [ + - ]: 1 : return 0;
1047 : 1 : }
1048 : :
1049 : 11 : void btck_chainstate_manager_options_destroy(btck_ChainstateManagerOptions* options)
1050 : : {
1051 [ + - ]: 11 : delete options;
1052 : 11 : }
1053 : :
1054 : 6 : int btck_chainstate_manager_options_set_wipe_dbs(btck_ChainstateManagerOptions* chainman_opts, int wipe_block_tree_db, int wipe_chainstate_db)
1055 : : {
1056 [ + + ]: 6 : if (wipe_block_tree_db == 1 && wipe_chainstate_db != 1) {
1057 : 1 : LogError("Wiping the block tree db without also wiping the chainstate db is currently unsupported.");
1058 : 1 : return -1;
1059 : : }
1060 : 5 : auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1061 : 5 : LOCK(opts.m_mutex);
1062 : 5 : opts.m_blockman_options.block_tree_db_params.wipe_data = wipe_block_tree_db == 1;
1063 : 5 : opts.m_chainstate_load_options.wipe_chainstate_db = wipe_chainstate_db == 1;
1064 [ + - ]: 5 : return 0;
1065 : 5 : }
1066 : :
1067 : 2 : void btck_chainstate_manager_options_update_block_tree_db_in_memory(
1068 : : btck_ChainstateManagerOptions* chainman_opts,
1069 : : int block_tree_db_in_memory)
1070 : : {
1071 : 2 : auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1072 : 2 : LOCK(opts.m_mutex);
1073 [ + - ]: 2 : opts.m_blockman_options.block_tree_db_params.memory_only = block_tree_db_in_memory == 1;
1074 : 2 : }
1075 : :
1076 : 2 : void btck_chainstate_manager_options_update_chainstate_db_in_memory(
1077 : : btck_ChainstateManagerOptions* chainman_opts,
1078 : : int chainstate_db_in_memory)
1079 : : {
1080 : 2 : auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1081 : 2 : LOCK(opts.m_mutex);
1082 [ + - ]: 2 : opts.m_chainstate_load_options.coins_db_in_memory = chainstate_db_in_memory == 1;
1083 : 2 : }
1084 : :
1085 : 11 : btck_ChainstateManager* btck_chainstate_manager_create(
1086 : : const btck_ChainstateManagerOptions* chainman_opts)
1087 : : {
1088 : 11 : auto& opts{btck_ChainstateManagerOptions::get(chainman_opts)};
1089 : 11 : std::unique_ptr<ChainstateManager> chainman;
1090 : 11 : try {
1091 [ + - ]: 11 : LOCK(opts.m_mutex);
1092 [ + - + - ]: 22 : chainman = std::make_unique<ChainstateManager>(*opts.m_context->m_interrupt, opts.m_chainman_options, opts.m_blockman_options);
1093 [ - - ]: 0 : } catch (const std::exception& e) {
1094 [ - - ]: 0 : LogError("Failed to create chainstate manager: %s", e.what());
1095 : 0 : return nullptr;
1096 : 0 : }
1097 : :
1098 : 11 : try {
1099 [ + - + - ]: 33 : const auto chainstate_load_opts{WITH_LOCK(opts.m_mutex, return opts.m_chainstate_load_options)};
1100 : :
1101 [ + - + - ]: 22 : const kernel::CacheSizes cache_sizes{WITH_LOCK(opts.m_mutex, return opts.m_db_cache_bytes)};
1102 [ + - - + ]: 11 : auto [status, chainstate_err]{node::LoadChainstate(*chainman, cache_sizes, chainstate_load_opts)};
1103 [ - + ]: 11 : if (status != node::ChainstateLoadStatus::SUCCESS) {
1104 [ # # ]: 0 : LogError("Failed to load chain state from your data directory: %s", chainstate_err.original);
1105 : : return nullptr;
1106 : : }
1107 [ + - ]: 11 : std::tie(status, chainstate_err) = node::VerifyLoadedChainstate(*chainman, chainstate_load_opts);
1108 [ - + ]: 11 : if (status != node::ChainstateLoadStatus::SUCCESS) {
1109 [ # # ]: 0 : LogError("Failed to verify loaded chain state from your datadir: %s", chainstate_err.original);
1110 : : return nullptr;
1111 : : }
1112 [ + - - + ]: 11 : if (auto result = chainman->ActivateBestChains(); !result) {
1113 [ # # # # ]: 0 : LogError("%s", util::ErrorString(result).original);
1114 : 0 : return nullptr;
1115 : 11 : }
1116 [ - - ]: 11 : } catch (const std::exception& e) {
1117 [ - - ]: 0 : LogError("Failed to load chainstate: %s", e.what());
1118 : 0 : return nullptr;
1119 : 0 : }
1120 : :
1121 [ + - ]: 11 : return btck_ChainstateManager::create(std::move(chainman), opts.m_context);
1122 : 11 : }
1123 : :
1124 : 207 : const btck_BlockTreeEntry* btck_chainstate_manager_get_block_tree_entry_by_hash(const btck_ChainstateManager* chainman, const btck_BlockHash* block_hash)
1125 : : {
1126 [ + - + - ]: 621 : auto block_index = WITH_LOCK(btck_ChainstateManager::get(chainman).m_chainman->GetMutex(),
1127 : : return btck_ChainstateManager::get(chainman).m_chainman->m_blockman.LookupBlockIndex(btck_BlockHash::get(block_hash)));
1128 [ - + ]: 207 : if (!block_index) {
1129 [ # # ]: 0 : LogDebug(BCLog::KERNEL, "A block with the given hash is not indexed.");
1130 : 0 : return nullptr;
1131 : : }
1132 : : return btck_BlockTreeEntry::ref(block_index);
1133 : : }
1134 : :
1135 : 206 : const btck_BlockTreeEntry* btck_chainstate_manager_get_best_entry(const btck_ChainstateManager* chainstate_manager)
1136 : : {
1137 : 206 : auto& chainman = *btck_ChainstateManager::get(chainstate_manager).m_chainman;
1138 [ + - ]: 412 : return btck_BlockTreeEntry::ref(WITH_LOCK(chainman.GetMutex(), return chainman.m_best_header));
1139 : : }
1140 : :
1141 : 11 : void btck_chainstate_manager_destroy(btck_ChainstateManager* chainman)
1142 : : {
1143 : 11 : {
1144 : 11 : LOCK(btck_ChainstateManager::get(chainman).m_chainman->GetMutex());
1145 [ + + ]: 22 : for (const auto& chainstate : btck_ChainstateManager::get(chainman).m_chainman->m_chainstates) {
1146 [ + - ]: 22 : if (chainstate->CanFlushToDisk()) {
1147 [ + - ]: 11 : chainstate->ForceFlushStateToDisk();
1148 : 11 : chainstate->ResetCoinsViews();
1149 : : }
1150 : : }
1151 : 11 : }
1152 : :
1153 [ + - ]: 11 : delete chainman;
1154 : 11 : }
1155 : :
1156 : 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)
1157 : : {
1158 : 2 : try {
1159 : 2 : std::vector<fs::path> import_files;
1160 [ + - ]: 2 : import_files.reserve(block_file_paths_data_len);
1161 [ + + ]: 3 : for (uint32_t i = 0; i < block_file_paths_data_len; i++) {
1162 [ + - ]: 1 : if (block_file_paths_data[i] != nullptr) {
1163 [ + - + - ]: 2 : import_files.emplace_back(std::string{block_file_paths_data[i], block_file_paths_lens[i]}.c_str());
1164 : : }
1165 : : }
1166 [ - + ]: 2 : auto& chainman_ref{*btck_ChainstateManager::get(chainman).m_chainman};
1167 [ - + + - ]: 2 : node::ImportBlocks(chainman_ref, import_files);
1168 [ + - + - ]: 6 : WITH_LOCK(::cs_main, chainman_ref.UpdateIBDStatus());
1169 [ - - ]: 0 : } catch (const std::exception& e) {
1170 [ - - ]: 0 : LogError("Failed to import blocks: %s", e.what());
1171 : 0 : return -1;
1172 : 0 : }
1173 : 2 : return 0;
1174 : : }
1175 : :
1176 : 634 : btck_Block* btck_block_create(const void* raw_block, size_t raw_block_length)
1177 : : {
1178 [ - + ]: 634 : assert(raw_block != nullptr || raw_block_length == 0);
1179 : 634 : auto block{std::make_shared<CBlock>()};
1180 : :
1181 [ + + ]: 634 : SpanReader stream{std::span{reinterpret_cast<const std::byte*>(raw_block), raw_block_length}};
1182 : :
1183 : 634 : try {
1184 [ + + ]: 634 : stream >> TX_WITH_WITNESS(*block);
1185 : 3 : } catch (...) {
1186 [ + - + - : 3 : LogDebug(BCLog::KERNEL, "Block decode failed.");
+ - ]
1187 : 3 : return nullptr;
1188 [ + - ]: 3 : }
1189 : :
1190 [ + - ]: 631 : return btck_Block::create(block);
1191 : 634 : }
1192 : :
1193 : 5 : btck_Block* btck_block_copy(const btck_Block* block)
1194 : : {
1195 : 5 : return btck_Block::copy(block);
1196 : : }
1197 : :
1198 : 7 : int btck_block_check(const btck_Block* block, const btck_ConsensusParams* consensus_params, btck_BlockCheckFlags flags, btck_BlockValidationState* validation_state)
1199 : : {
1200 : 7 : auto& state = btck_BlockValidationState::get(validation_state);
1201 : 7 : state = BlockValidationState{};
1202 : :
1203 : 7 : const bool check_pow = (flags & btck_BlockCheckFlags_POW) != 0;
1204 : 7 : const bool check_merkle = (flags & btck_BlockCheckFlags_MERKLE) != 0;
1205 : :
1206 : 7 : const bool result = CheckBlock(*btck_Block::get(block), state, btck_ConsensusParams::get(consensus_params), /*fCheckPOW=*/check_pow, /*fCheckMerkleRoot=*/check_merkle);
1207 : :
1208 [ + + ]: 7 : return result ? 1 : 0;
1209 : : }
1210 : :
1211 : 6688 : size_t btck_block_count_transactions(const btck_Block* block)
1212 : : {
1213 [ - + ]: 6688 : return btck_Block::get(block)->vtx.size();
1214 : : }
1215 : :
1216 : 8049 : const btck_Transaction* btck_block_get_transaction_at(const btck_Block* block, size_t index)
1217 : : {
1218 [ - + - + ]: 8049 : assert(index < btck_Block::get(block)->vtx.size());
1219 : 8049 : return btck_Transaction::ref(&btck_Block::get(block)->vtx[index]);
1220 : : }
1221 : :
1222 : 208 : btck_BlockHeader* btck_block_get_header(const btck_Block* block)
1223 : : {
1224 : 208 : const auto& block_ptr = btck_Block::get(block);
1225 : 208 : return btck_BlockHeader::create(static_cast<const CBlockHeader&>(*block_ptr));
1226 : : }
1227 : :
1228 : 22 : int btck_block_to_bytes(const btck_Block* block, btck_WriteBytes writer, void* user_data)
1229 : : {
1230 : 22 : try {
1231 : 22 : WriterStream ws{writer, user_data};
1232 [ + - ]: 44 : ws << TX_WITH_WITNESS(*btck_Block::get(block));
1233 : : return 0;
1234 : 0 : } catch (...) {
1235 : 0 : return -1;
1236 : 0 : }
1237 : : }
1238 : :
1239 : 1 : btck_BlockHash* btck_block_get_hash(const btck_Block* block)
1240 : : {
1241 : 1 : return btck_BlockHash::create(btck_Block::get(block)->GetHash());
1242 : : }
1243 : :
1244 : 7322 : void btck_block_destroy(btck_Block* block)
1245 : : {
1246 [ + + ]: 7322 : delete block;
1247 : 7322 : }
1248 : :
1249 : 6676 : btck_Block* btck_block_read(const btck_ChainstateManager* chainman, const btck_BlockTreeEntry* entry)
1250 : : {
1251 : 6676 : auto block{std::make_shared<CBlock>()};
1252 [ + - + + ]: 6676 : if (!btck_ChainstateManager::get(chainman).m_chainman->m_blockman.ReadBlock(*block, btck_BlockTreeEntry::get(entry))) {
1253 [ + - + - ]: 6676 : LogError("Failed to read block.");
1254 : : return nullptr;
1255 : : }
1256 [ + - ]: 6675 : return btck_Block::create(block);
1257 : 6676 : }
1258 : :
1259 : 206 : btck_BlockHeader* btck_block_tree_entry_get_block_header(const btck_BlockTreeEntry* entry)
1260 : : {
1261 : 206 : return btck_BlockHeader::create(btck_BlockTreeEntry::get(entry).GetBlockHeader());
1262 : : }
1263 : :
1264 : 211 : int32_t btck_block_tree_entry_get_height(const btck_BlockTreeEntry* entry)
1265 : : {
1266 : 211 : return btck_BlockTreeEntry::get(entry).nHeight;
1267 : : }
1268 : :
1269 : 207 : const btck_BlockHash* btck_block_tree_entry_get_block_hash(const btck_BlockTreeEntry* entry)
1270 : : {
1271 : 207 : return btck_BlockHash::ref(btck_BlockTreeEntry::get(entry).phashBlock);
1272 : : }
1273 : :
1274 : 10 : int btck_block_tree_entry_equals(const btck_BlockTreeEntry* entry1, const btck_BlockTreeEntry* entry2)
1275 : : {
1276 : 10 : return &btck_BlockTreeEntry::get(entry1) == &btck_BlockTreeEntry::get(entry2);
1277 : : }
1278 : :
1279 : 2 : btck_BlockHash* btck_block_hash_create(const unsigned char block_hash[32])
1280 : : {
1281 : 2 : return btck_BlockHash::create(std::span<const unsigned char>{block_hash, 32});
1282 : : }
1283 : :
1284 : 212 : btck_BlockHash* btck_block_hash_copy(const btck_BlockHash* block_hash)
1285 : : {
1286 : 212 : return btck_BlockHash::copy(block_hash);
1287 : : }
1288 : :
1289 : 18 : void btck_block_hash_to_bytes(const btck_BlockHash* block_hash, unsigned char output[32])
1290 : : {
1291 : 18 : std::memcpy(output, btck_BlockHash::get(block_hash).begin(), 32);
1292 : 18 : }
1293 : :
1294 : 208 : int btck_block_hash_equals(const btck_BlockHash* hash1, const btck_BlockHash* hash2)
1295 : : {
1296 : 208 : return btck_BlockHash::get(hash1) == btck_BlockHash::get(hash2);
1297 : : }
1298 : :
1299 : 632 : void btck_block_hash_destroy(btck_BlockHash* hash)
1300 : : {
1301 [ + + ]: 632 : delete hash;
1302 : 632 : }
1303 : :
1304 : 5 : btck_BlockSpentOutputs* btck_block_spent_outputs_read(const btck_ChainstateManager* chainman, const btck_BlockTreeEntry* entry)
1305 : : {
1306 : 5 : auto block_undo{std::make_shared<CBlockUndo>()};
1307 [ + + ]: 5 : if (btck_BlockTreeEntry::get(entry).nHeight < 1) {
1308 [ + - + - : 1 : LogDebug(BCLog::KERNEL, "The genesis block does not have any spent outputs.");
+ - ]
1309 [ + - ]: 1 : return btck_BlockSpentOutputs::create(block_undo);
1310 : : }
1311 [ + - + + ]: 4 : if (!btck_ChainstateManager::get(chainman).m_chainman->m_blockman.ReadBlockUndo(*block_undo, btck_BlockTreeEntry::get(entry))) {
1312 [ + - + - ]: 5 : LogError("Failed to read block spent outputs data.");
1313 : : return nullptr;
1314 : : }
1315 [ + - ]: 3 : return btck_BlockSpentOutputs::create(block_undo);
1316 : 5 : }
1317 : :
1318 : 5 : btck_BlockSpentOutputs* btck_block_spent_outputs_copy(const btck_BlockSpentOutputs* block_spent_outputs)
1319 : : {
1320 : 5 : return btck_BlockSpentOutputs::copy(block_spent_outputs);
1321 : : }
1322 : :
1323 : 25 : size_t btck_block_spent_outputs_count(const btck_BlockSpentOutputs* block_spent_outputs)
1324 : : {
1325 [ - + ]: 25 : return btck_BlockSpentOutputs::get(block_spent_outputs)->vtxundo.size();
1326 : : }
1327 : :
1328 : 12 : const btck_TransactionSpentOutputs* btck_block_spent_outputs_get_transaction_spent_outputs_at(const btck_BlockSpentOutputs* block_spent_outputs, size_t transaction_index)
1329 : : {
1330 [ - + - + ]: 12 : assert(transaction_index < btck_BlockSpentOutputs::get(block_spent_outputs)->vtxundo.size());
1331 : 12 : const auto* tx_undo{&btck_BlockSpentOutputs::get(block_spent_outputs)->vtxundo.at(transaction_index)};
1332 : 12 : return btck_TransactionSpentOutputs::ref(tx_undo);
1333 : : }
1334 : :
1335 : 11 : void btck_block_spent_outputs_destroy(btck_BlockSpentOutputs* block_spent_outputs)
1336 : : {
1337 [ + + ]: 11 : delete block_spent_outputs;
1338 : 11 : }
1339 : :
1340 : 7 : btck_TransactionSpentOutputs* btck_transaction_spent_outputs_copy(const btck_TransactionSpentOutputs* transaction_spent_outputs)
1341 : : {
1342 : 7 : return btck_TransactionSpentOutputs::copy(transaction_spent_outputs);
1343 : : }
1344 : :
1345 : 22 : size_t btck_transaction_spent_outputs_count(const btck_TransactionSpentOutputs* transaction_spent_outputs)
1346 : : {
1347 [ - + ]: 22 : return btck_TransactionSpentOutputs::get(transaction_spent_outputs).vprevout.size();
1348 : : }
1349 : :
1350 : 9 : void btck_transaction_spent_outputs_destroy(btck_TransactionSpentOutputs* transaction_spent_outputs)
1351 : : {
1352 [ + + ]: 9 : delete transaction_spent_outputs;
1353 : 9 : }
1354 : :
1355 : 12 : const btck_Coin* btck_transaction_spent_outputs_get_coin_at(const btck_TransactionSpentOutputs* transaction_spent_outputs, size_t coin_index)
1356 : : {
1357 [ - + - + ]: 12 : assert(coin_index < btck_TransactionSpentOutputs::get(transaction_spent_outputs).vprevout.size());
1358 : 12 : const Coin* coin{&btck_TransactionSpentOutputs::get(transaction_spent_outputs).vprevout.at(coin_index)};
1359 : 12 : return btck_Coin::ref(coin);
1360 : : }
1361 : :
1362 : 7 : btck_Coin* btck_coin_copy(const btck_Coin* coin)
1363 : : {
1364 : 7 : return btck_Coin::copy(coin);
1365 : : }
1366 : :
1367 : 1 : uint32_t btck_coin_confirmation_height(const btck_Coin* coin)
1368 : : {
1369 : 1 : return btck_Coin::get(coin).nHeight;
1370 : : }
1371 : :
1372 : 1 : int btck_coin_is_coinbase(const btck_Coin* coin)
1373 : : {
1374 [ + - ]: 1 : return btck_Coin::get(coin).IsCoinBase() ? 1 : 0;
1375 : : }
1376 : :
1377 : 2 : const btck_TransactionOutput* btck_coin_get_output(const btck_Coin* coin)
1378 : : {
1379 : 2 : return btck_TransactionOutput::ref(&btck_Coin::get(coin).out);
1380 : : }
1381 : :
1382 : 9 : void btck_coin_destroy(btck_Coin* coin)
1383 : : {
1384 [ + + ]: 9 : delete coin;
1385 : 9 : }
1386 : :
1387 : 418 : int btck_chainstate_manager_process_block(
1388 : : btck_ChainstateManager* chainman,
1389 : : const btck_Block* block,
1390 : : int* _new_block)
1391 : : {
1392 : 418 : bool new_block;
1393 : 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);
1394 [ + - ]: 418 : if (_new_block) {
1395 [ + + ]: 420 : *_new_block = new_block ? 1 : 0;
1396 : : }
1397 [ + + ]: 418 : return result ? 0 : -1;
1398 : : }
1399 : :
1400 : 206 : btck_BlockValidationState* btck_chainstate_manager_process_block_header(
1401 : : btck_ChainstateManager* chainstate_manager,
1402 : : const btck_BlockHeader* header)
1403 : : {
1404 : 206 : try {
1405 : 206 : auto& chainman = btck_ChainstateManager::get(chainstate_manager).m_chainman;
1406 : :
1407 [ + - ]: 206 : auto state = btck_BlockValidationState::create();
1408 [ + - ]: 206 : bool result{chainman->ProcessNewBlockHeaders({&btck_BlockHeader::get(header), 1}, /*min_pow_checked=*/true, btck_BlockValidationState::get(state))};
1409 [ - + ]: 206 : assert(result == btck_BlockValidationState::get(state).IsValid());
1410 : : return state;
1411 [ - - ]: 0 : } catch (const std::exception& e) {
1412 [ - - ]: 0 : LogError("Failed to process block header: %s", e.what());
1413 : 0 : return nullptr;
1414 : 0 : }
1415 : : }
1416 : :
1417 : 269 : const btck_Chain* btck_chainstate_manager_get_active_chain(const btck_ChainstateManager* chainman)
1418 : : {
1419 [ + - + - ]: 807 : return btck_Chain::ref(&WITH_LOCK(btck_ChainstateManager::get(chainman).m_chainman->GetMutex(), return btck_ChainstateManager::get(chainman).m_chainman->ActiveChain()));
1420 : : }
1421 : :
1422 : 292 : int32_t btck_chain_get_height(const btck_Chain* chain)
1423 : : {
1424 : 292 : LOCK(::cs_main);
1425 [ - + + - ]: 292 : return btck_Chain::get(chain).Height();
1426 : 292 : }
1427 : :
1428 : 7512 : const btck_BlockTreeEntry* btck_chain_get_by_height(const btck_Chain* chain, int32_t height)
1429 : : {
1430 : 7512 : LOCK(::cs_main);
1431 [ + - + - ]: 15024 : return btck_BlockTreeEntry::ref(btck_Chain::get(chain)[height]);
1432 : 7512 : }
1433 : :
1434 : 207 : int btck_chain_contains(const btck_Chain* chain, const btck_BlockTreeEntry* entry)
1435 : : {
1436 : 207 : LOCK(::cs_main);
1437 [ + + ]: 207 : return btck_Chain::get(chain).Contains(btck_BlockTreeEntry::get(entry)) ? 1 : 0;
1438 : 207 : }
1439 : :
1440 : 4 : btck_BlockHeader* btck_block_header_create(const void* raw_block_header, size_t raw_block_header_len)
1441 : : {
1442 [ - + ]: 4 : assert(raw_block_header != nullptr && raw_block_header_len == 80);
1443 : 4 : auto header{std::make_unique<CBlockHeader>()};
1444 [ + - ]: 4 : SpanReader stream{std::span{reinterpret_cast<const std::byte*>(raw_block_header), raw_block_header_len}};
1445 : :
1446 : 4 : try {
1447 [ + - ]: 4 : stream >> *header;
1448 : 0 : } catch (...) {
1449 [ - - ]: 0 : LogError("Block header decode failed.");
1450 : 0 : return nullptr;
1451 [ - - ]: 0 : }
1452 : :
1453 : 4 : return btck_BlockHeader::ref(header.release());
1454 : 4 : }
1455 : :
1456 : 5 : btck_BlockHeader* btck_block_header_copy(const btck_BlockHeader* header)
1457 : : {
1458 : 5 : return btck_BlockHeader::copy(header);
1459 : : }
1460 : :
1461 : 415 : btck_BlockHash* btck_block_header_get_hash(const btck_BlockHeader* header)
1462 : : {
1463 : 415 : return btck_BlockHash::create(btck_BlockHeader::get(header).GetHash());
1464 : : }
1465 : :
1466 : 1 : const btck_BlockHash* btck_block_header_get_prev_hash(const btck_BlockHeader* header)
1467 : : {
1468 : 1 : return btck_BlockHash::ref(&btck_BlockHeader::get(header).hashPrevBlock);
1469 : : }
1470 : :
1471 : 3 : uint32_t btck_block_header_get_timestamp(const btck_BlockHeader* header)
1472 : : {
1473 : 3 : return btck_BlockHeader::get(header).nTime;
1474 : : }
1475 : :
1476 : 3 : uint32_t btck_block_header_get_bits(const btck_BlockHeader* header)
1477 : : {
1478 : 3 : return btck_BlockHeader::get(header).nBits;
1479 : : }
1480 : :
1481 : 3 : int32_t btck_block_header_get_version(const btck_BlockHeader* header)
1482 : : {
1483 : 3 : return btck_BlockHeader::get(header).nVersion;
1484 : : }
1485 : :
1486 : 3 : uint32_t btck_block_header_get_nonce(const btck_BlockHeader* header)
1487 : : {
1488 : 3 : return btck_BlockHeader::get(header).nNonce;
1489 : : }
1490 : :
1491 : 15 : int btck_block_header_to_bytes(const btck_BlockHeader* header, unsigned char output[80])
1492 : : {
1493 : 15 : try {
1494 [ + - ]: 30 : SpanWriter{std::as_writable_bytes(std::span{output, 80})} << btck_BlockHeader::get(header);
1495 : : return 0;
1496 : 0 : } catch (...) {
1497 : 0 : return -1;
1498 : 0 : }
1499 : : }
1500 : :
1501 : 425 : void btck_block_header_destroy(btck_BlockHeader* header)
1502 : : {
1503 [ + + ]: 425 : delete header;
1504 : 425 : }
1505 : :
1506 : 12 : btck_ValidationMode btck_tx_validation_state_get_validation_mode(const btck_TxValidationState* state_)
1507 : : {
1508 : 12 : const auto& state = btck_TxValidationState::get(state_);
1509 [ + + ]: 12 : if (state.IsValid()) return btck_ValidationMode_VALID;
1510 [ + - ]: 9 : if (state.IsInvalid()) return btck_ValidationMode_INVALID;
1511 : : return btck_ValidationMode_INTERNAL_ERROR;
1512 : : }
1513 : :
1514 : 11 : btck_TxValidationState* btck_tx_validation_state_create()
1515 : : {
1516 : 11 : return btck_TxValidationState::create();
1517 : : }
1518 : :
1519 : 12 : btck_TxValidationResult btck_tx_validation_state_get_tx_validation_result(const btck_TxValidationState* state_)
1520 : : {
1521 [ + - - - : 12 : switch (btck_TxValidationState::get(state_).GetResult()) {
- - - - -
- - - -
+ ]
1522 : : case TxValidationResult::TX_RESULT_UNSET: return btck_TxValidationResult_UNSET;
1523 : 9 : case TxValidationResult::TX_CONSENSUS: return btck_TxValidationResult_CONSENSUS;
1524 : 0 : case TxValidationResult::TX_INPUTS_NOT_STANDARD: return btck_TxValidationResult_INPUTS_NOT_STANDARD;
1525 : 0 : case TxValidationResult::TX_NOT_STANDARD: return btck_TxValidationResult_NOT_STANDARD;
1526 : 0 : case TxValidationResult::TX_MISSING_INPUTS: return btck_TxValidationResult_MISSING_INPUTS;
1527 : 0 : case TxValidationResult::TX_PREMATURE_SPEND: return btck_TxValidationResult_PREMATURE_SPEND;
1528 : 0 : case TxValidationResult::TX_WITNESS_MUTATED: return btck_TxValidationResult_WITNESS_MUTATED;
1529 : 0 : case TxValidationResult::TX_WITNESS_STRIPPED: return btck_TxValidationResult_WITNESS_STRIPPED;
1530 : 0 : case TxValidationResult::TX_CONFLICT: return btck_TxValidationResult_CONFLICT;
1531 : 0 : case TxValidationResult::TX_MEMPOOL_POLICY: return btck_TxValidationResult_MEMPOOL_POLICY;
1532 : 0 : case TxValidationResult::TX_NO_MEMPOOL: return btck_TxValidationResult_NO_MEMPOOL;
1533 : 0 : case TxValidationResult::TX_RECONSIDERABLE: return btck_TxValidationResult_RECONSIDERABLE;
1534 : 0 : case TxValidationResult::TX_UNKNOWN: return btck_TxValidationResult_UNKNOWN;
1535 : : } // no default case, so the compiler can warn about missing cases
1536 : 0 : assert(false);
1537 : : }
1538 : :
1539 : 11 : void btck_tx_validation_state_destroy(btck_TxValidationState* state)
1540 : : {
1541 [ + - ]: 11 : delete state;
1542 : 11 : }
1543 : :
1544 : 12 : int btck_transaction_check(const btck_Transaction* tx, btck_TxValidationState* validation_state)
1545 : : {
1546 : 12 : auto& state = btck_TxValidationState::get(validation_state);
1547 : 12 : state = TxValidationState{};
1548 : 12 : const bool ok = CheckTransaction(*btck_Transaction::get(tx), state);
1549 [ + + ]: 12 : return ok ? 1 : 0;
1550 : : }
|