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