Bitcoin Core Fuzz Coverage Report

Coverage Report

Created: 2026-05-28 15:05

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/Users/brunogarcia/projects/bitcoin-core-dev/src/index/base.cpp
Line
Count
Source
1
// Copyright (c) 2017-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
#include <index/base.h>
6
7
#include <chain.h>
8
#include <common/args.h>
9
#include <dbwrapper.h>
10
#include <interfaces/chain.h>
11
#include <interfaces/types.h>
12
#include <kernel/types.h>
13
#include <node/abort.h>
14
#include <node/blockstorage.h>
15
#include <node/context.h>
16
#include <node/database_args.h>
17
#include <node/interface_ui.h>
18
#include <primitives/block.h>
19
#include <sync.h>
20
#include <tinyformat.h>
21
#include <uint256.h>
22
#include <undo.h>
23
#include <util/fs.h>
24
#include <util/log.h>
25
#include <util/string.h>
26
#include <util/thread.h>
27
#include <util/threadinterrupt.h>
28
#include <util/time.h>
29
#include <util/translation.h>
30
#include <validation.h>
31
#include <validationinterface.h>
32
33
#include <cassert>
34
#include <compare>
35
#include <cstdint>
36
#include <functional>
37
#include <memory>
38
#include <optional>
39
#include <stdexcept>
40
#include <string>
41
#include <thread>
42
#include <utility>
43
#include <vector>
44
45
using kernel::ChainstateRole;
46
47
constexpr uint8_t DB_BEST_BLOCK{'B'};
48
49
constexpr auto SYNC_LOG_INTERVAL{30s};
50
constexpr auto SYNC_LOCATOR_WRITE_INTERVAL{30s};
51
52
template <typename... Args>
53
void BaseIndex::FatalErrorf(util::ConstevalFormatString<sizeof...(Args)> fmt, const Args&... args)
54
0
{
55
0
    auto message = tfm::format(fmt, args...);
56
0
    node::AbortNode(m_chain->context()->shutdown_request, m_chain->context()->exit_status, Untranslated(message), m_chain->context()->warnings.get());
57
0
}
Unexecuted instantiation: void BaseIndex::FatalErrorf<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>(util::ConstevalFormatString<sizeof...(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>)>, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>> const&)
Unexecuted instantiation: void BaseIndex::FatalErrorf<int>(util::ConstevalFormatString<sizeof...(int)>, int const&)
58
59
CBlockLocator GetLocator(interfaces::Chain& chain, const uint256& block_hash)
60
0
{
61
0
    CBlockLocator locator;
62
0
    bool found = chain.findBlock(block_hash, interfaces::FoundBlock().locator(locator));
63
0
    assert(found);
64
0
    assert(!locator.IsNull());
65
0
    return locator;
66
0
}
67
68
BaseIndex::DB::DB(const fs::path& path, size_t n_cache_size, bool f_memory, bool f_wipe, bool f_obfuscate) :
69
0
    CDBWrapper{DBParams{
70
0
        .path = path,
71
0
        .cache_bytes = n_cache_size,
72
0
        .memory_only = f_memory,
73
0
        .wipe_data = f_wipe,
74
0
        .obfuscate = f_obfuscate,
75
0
        .options = [] { DBOptions options; node::ReadDatabaseArgs(gArgs, options); return options; }()}}
76
0
{}
77
78
CBlockLocator BaseIndex::DB::ReadBestBlock() const
79
0
{
80
0
    CBlockLocator locator;
81
82
0
    bool success = Read(DB_BEST_BLOCK, locator);
83
0
    if (!success) {
84
0
        locator.SetNull();
85
0
    }
86
87
0
    return locator;
88
0
}
89
90
void BaseIndex::DB::WriteBestBlock(CDBBatch& batch, const CBlockLocator& locator)
91
0
{
92
0
    batch.Write(DB_BEST_BLOCK, locator);
93
0
}
94
95
BaseIndex::BaseIndex(std::unique_ptr<interfaces::Chain> chain, std::string name)
96
0
    : m_chain{std::move(chain)}, m_name{std::move(name)} {}
97
98
BaseIndex::~BaseIndex()
99
0
{
100
0
    Interrupt();
101
0
    Stop();
102
0
}
103
104
bool BaseIndex::Init()
105
0
{
106
0
    AssertLockNotHeld(cs_main);
Line
Count
Source
149
0
#define AssertLockNotHeld(cs) AssertLockNotHeldInline(#cs, __FILE__, __LINE__, &cs)
107
108
    // May need reset if index is being restarted.
109
0
    m_interrupt.reset();
110
111
    // m_chainstate member gives indexing code access to node internals. It is
112
    // removed in followup https://github.com/bitcoin/bitcoin/pull/24230
113
0
    m_chainstate = WITH_LOCK(::cs_main,
Line
Count
Source
299
0
#define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }())
114
0
                             return &m_chain->context()->chainman->ValidatedChainstate());
115
    // Register to validation interface before setting the 'm_synced' flag, so that
116
    // callbacks are not missed once m_synced is true.
117
0
    m_chain->context()->validation_signals->RegisterValidationInterface(this);
118
119
0
    const auto locator{GetDB().ReadBestBlock()};
120
121
0
    LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
122
0
    CChain& index_chain = m_chainstate->m_chain;
123
124
0
    if (locator.IsNull()) {
125
0
        SetBestBlockIndex(nullptr);
126
0
    } else {
127
        // Setting the best block to the locator's top block. If it is not part of the
128
        // best chain, we will rewind to the fork point during index sync
129
0
        const CBlockIndex* locator_index{m_chainstate->m_blockman.LookupBlockIndex(locator.vHave.at(0))};
130
0
        if (!locator_index) {
131
0
            return InitError(Untranslated(strprintf("best block of %s not found. Please rebuild the index.", GetName())));
Line
Count
Source
1172
0
#define strprintf tfm::format
132
0
        }
133
0
        SetBestBlockIndex(locator_index);
134
0
    }
135
136
    // Child init
137
0
    const CBlockIndex* start_block = m_best_block_index.load();
138
0
    if (!CustomInit(start_block ? std::make_optional(interfaces::BlockRef{start_block->GetBlockHash(), start_block->nHeight}) : std::nullopt)) {
139
0
        return false;
140
0
    }
141
142
    // Note: this will latch to true immediately if the user starts up with an empty
143
    // datadir and an index enabled. If this is the case, indexation will happen solely
144
    // via `BlockConnected` signals until, possibly, the next restart.
145
0
    m_synced = start_block == index_chain.Tip();
146
0
    m_init = true;
147
0
    return true;
148
0
}
149
150
static const CBlockIndex* NextSyncBlock(const CBlockIndex* pindex_prev, CChain& chain) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
151
0
{
152
0
    AssertLockHeld(cs_main);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
153
154
0
    if (!pindex_prev) {
155
0
        return chain.Genesis();
156
0
    }
157
158
0
    if (const auto* pindex{chain.Next(pindex_prev)}) {
159
0
        return pindex;
160
0
    }
161
162
    // If there is no next block, we might be synced
163
0
    if (pindex_prev == chain.Tip()) {
164
0
        return nullptr;
165
0
    }
166
167
    // Since block is not in the chain, return the next block in the chain AFTER the last common ancestor.
168
    // Caller will be responsible for rewinding back to the common ancestor.
169
0
    return chain.Next(chain.FindFork(pindex_prev));
170
0
}
171
172
bool BaseIndex::ProcessBlock(const CBlockIndex* pindex, const CBlock* block_data)
173
0
{
174
0
    interfaces::BlockInfo block_info = kernel::MakeBlockInfo(pindex, block_data);
175
176
0
    CBlock block;
177
0
    if (!block_data) { // disk lookup if block data wasn't provided
178
0
        if (!m_chainstate->m_blockman.ReadBlock(block, *pindex)) {
179
0
            FatalErrorf("Failed to read block %s from disk",
180
0
                        pindex->GetBlockHash().ToString());
181
0
            return false;
182
0
        }
183
0
        block_info.data = &block;
184
0
    }
185
186
0
    CBlockUndo block_undo;
187
0
    if (CustomOptions().connect_undo_data) {
188
0
        if (pindex->nHeight > 0 && !m_chainstate->m_blockman.ReadBlockUndo(block_undo, *pindex)) {
189
0
            FatalErrorf("Failed to read undo block data %s from disk",
190
0
                        pindex->GetBlockHash().ToString());
191
0
            return false;
192
0
        }
193
0
        block_info.undo_data = &block_undo;
194
0
    }
195
196
0
    if (!CustomAppend(block_info)) {
197
0
        FatalErrorf("Failed to write block %s to index database",
198
0
                    pindex->GetBlockHash().ToString());
199
0
        return false;
200
0
    }
201
202
0
    return true;
203
0
}
204
205
void BaseIndex::Sync()
206
0
{
207
0
    const CBlockIndex* pindex = m_best_block_index.load();
208
0
    if (!m_synced) {
209
0
        auto last_log_time{NodeClock::now()};
210
0
        auto last_locator_write_time{last_log_time};
211
0
        while (true) {
212
0
            if (m_interrupt) {
213
0
                LogInfo("%s: m_interrupt set; exiting ThreadSync", GetName());
Line
Count
Source
97
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
91
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
214
215
0
                SetBestBlockIndex(pindex);
216
                // No need to handle errors in Commit. If it fails, the error will be already be
217
                // logged. The best way to recover is to continue, as index cannot be corrupted by
218
                // a missed commit to disk for an advanced index state.
219
0
                Commit();
220
0
                return;
221
0
            }
222
223
0
            const CBlockIndex* pindex_next = WITH_LOCK(cs_main, return NextSyncBlock(pindex, m_chainstate->m_chain));
Line
Count
Source
299
0
#define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }())
224
            // If pindex_next is null, it means pindex is the chain tip, so
225
            // commit data indexed so far.
226
0
            if (!pindex_next) {
227
0
                SetBestBlockIndex(pindex);
228
                // No need to handle errors in Commit. See rationale above.
229
0
                Commit();
230
231
                // If pindex is still the chain tip after committing, exit the
232
                // sync loop. It is important for cs_main to be locked while
233
                // setting m_synced = true, otherwise a new block could be
234
                // attached while m_synced is still false, and it would not be
235
                // indexed.
236
0
                LOCK(::cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
237
0
                pindex_next = NextSyncBlock(pindex, m_chainstate->m_chain);
238
0
                if (!pindex_next) {
239
0
                    m_synced = true;
240
0
                    break;
241
0
                }
242
0
            }
243
0
            if (pindex_next->pprev != pindex && !Rewind(pindex, pindex_next->pprev)) {
244
0
                FatalErrorf("Failed to rewind %s to a previous chain tip", GetName());
245
0
                return;
246
0
            }
247
0
            pindex = pindex_next;
248
249
250
0
            if (!ProcessBlock(pindex)) return; // error logged internally
251
252
0
            auto current_time{NodeClock::now()};
253
0
            if (current_time - last_log_time >= SYNC_LOG_INTERVAL) {
254
0
                LogInfo("Syncing %s with block chain from height %d", GetName(), pindex->nHeight);
Line
Count
Source
97
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
91
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
255
0
                last_log_time = current_time;
256
0
            }
257
258
0
            if (current_time - last_locator_write_time >= SYNC_LOCATOR_WRITE_INTERVAL) {
259
0
                SetBestBlockIndex(pindex);
260
0
                last_locator_write_time = current_time;
261
                // No need to handle errors in Commit. See rationale above.
262
0
                Commit();
263
0
            }
264
0
        }
265
0
    }
266
267
0
    if (pindex) {
268
0
        LogInfo("%s is enabled at height %d", GetName(), pindex->nHeight);
Line
Count
Source
97
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
91
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
269
0
    } else {
270
0
        LogInfo("%s is enabled", GetName());
Line
Count
Source
97
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
91
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
271
0
    }
272
0
}
273
274
bool BaseIndex::Commit()
275
0
{
276
    // Don't commit anything if we haven't indexed any block yet
277
    // (this could happen if init is interrupted).
278
0
    bool ok = m_best_block_index != nullptr;
279
0
    if (ok) {
280
0
        CDBBatch batch(GetDB());
281
0
        ok = CustomCommit(batch);
282
0
        if (ok) {
283
0
            GetDB().WriteBestBlock(batch, GetLocator(*m_chain, m_best_block_index.load()->GetBlockHash()));
284
0
            GetDB().WriteBatch(batch);
285
0
        }
286
0
    }
287
0
    if (!ok) {
288
0
        LogError("Failed to commit latest %s state", GetName());
Line
Count
Source
99
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
91
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
289
0
        return false;
290
0
    }
291
0
    return true;
292
0
}
293
294
bool BaseIndex::Rewind(const CBlockIndex* current_tip, const CBlockIndex* new_tip)
295
0
{
296
0
    assert(current_tip->GetAncestor(new_tip->nHeight) == new_tip);
297
298
0
    CBlock block;
299
0
    CBlockUndo block_undo;
300
301
0
    for (const CBlockIndex* iter_tip = current_tip; iter_tip != new_tip; iter_tip = iter_tip->pprev) {
302
0
        interfaces::BlockInfo block_info = kernel::MakeBlockInfo(iter_tip);
303
0
        if (CustomOptions().disconnect_data) {
304
0
            if (!m_chainstate->m_blockman.ReadBlock(block, *iter_tip)) {
305
0
                LogError("Failed to read block %s from disk",
Line
Count
Source
99
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
91
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
306
0
                         iter_tip->GetBlockHash().ToString());
307
0
                return false;
308
0
            }
309
0
            block_info.data = &block;
310
0
        }
311
0
        if (CustomOptions().disconnect_undo_data && iter_tip->nHeight > 0) {
312
0
            if (!m_chainstate->m_blockman.ReadBlockUndo(block_undo, *iter_tip)) {
313
0
                return false;
314
0
            }
315
0
            block_info.undo_data = &block_undo;
316
0
        }
317
0
        if (!CustomRemove(block_info)) {
318
0
            return false;
319
0
        }
320
0
    }
321
322
    // Don't commit here - the committed index state must never be ahead of the
323
    // flushed chainstate, otherwise unclean restarts would lead to index corruption.
324
    // Pruning has a minimum of 288 blocks-to-keep and getting the index
325
    // out of sync may be possible but a users fault.
326
    // In case we reorg beyond the pruned depth, ReadBlock would
327
    // throw and lead to a graceful shutdown
328
0
    SetBestBlockIndex(new_tip);
329
0
    return true;
330
0
}
331
332
void BaseIndex::BlockConnected(const ChainstateRole& role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex)
333
0
{
334
    // Ignore events from not fully validated chains to avoid out-of-order indexing.
335
    //
336
    // TODO at some point we could parameterize whether a particular index can be
337
    // built out of order, but for now just do the conservative simple thing.
338
0
    if (!role.validated) {
339
0
        return;
340
0
    }
341
342
    // Ignore BlockConnected signals until we have fully indexed the chain.
343
0
    if (!m_synced) {
344
0
        return;
345
0
    }
346
347
0
    const CBlockIndex* best_block_index = m_best_block_index.load();
348
0
    if (!best_block_index) {
349
0
        if (pindex->nHeight != 0) {
350
0
            FatalErrorf("First block connected is not the genesis block (height=%d)",
351
0
                       pindex->nHeight);
352
0
            return;
353
0
        }
354
0
    } else {
355
        // Ensure block connects to an ancestor of the current best block. This should be the case
356
        // most of the time, but may not be immediately after the sync thread catches up and sets
357
        // m_synced. Consider the case where there is a reorg and the blocks on the stale branch are
358
        // in the ValidationInterface queue backlog even after the sync thread has caught up to the
359
        // new chain tip. In this unlikely event, log a warning and let the queue clear.
360
0
        if (best_block_index->GetAncestor(pindex->nHeight - 1) != pindex->pprev) {
361
0
            LogWarning("Block %s does not connect to an ancestor of "
Line
Count
Source
98
0
#define LogWarning(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Warning, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
91
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
362
0
                      "known best chain (tip=%s); not updating index",
363
0
                      pindex->GetBlockHash().ToString(),
364
0
                      best_block_index->GetBlockHash().ToString());
365
0
            return;
366
0
        }
367
0
        if (best_block_index != pindex->pprev && !Rewind(best_block_index, pindex->pprev)) {
368
0
            FatalErrorf("Failed to rewind %s to a previous chain tip",
369
0
                       GetName());
370
0
            return;
371
0
        }
372
0
    }
373
374
    // Dispatch block to child class; errors are logged internally and abort the node.
375
0
    if (ProcessBlock(pindex, block.get())) {
376
        // Setting the best block index is intentionally the last step of this
377
        // function, so BlockUntilSyncedToCurrentChain callers waiting for the
378
        // best block index to be updated can rely on the block being fully
379
        // processed, and the index object being safe to delete.
380
0
        SetBestBlockIndex(pindex);
381
0
    }
382
0
}
383
384
void BaseIndex::ChainStateFlushed(const ChainstateRole& role, const CBlockLocator& locator)
385
0
{
386
    // Ignore events from not fully validated chains to avoid out-of-order indexing.
387
0
    if (!role.validated) {
388
0
        return;
389
0
    }
390
391
0
    if (!m_synced) {
392
0
        return;
393
0
    }
394
395
0
    const uint256& locator_tip_hash = locator.vHave.front();
396
0
    const CBlockIndex* locator_tip_index;
397
0
    {
398
0
        LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
399
0
        locator_tip_index = m_chainstate->m_blockman.LookupBlockIndex(locator_tip_hash);
400
0
    }
401
402
0
    if (!locator_tip_index) {
403
0
        FatalErrorf("First block (hash=%s) in locator was not found",
404
0
                   locator_tip_hash.ToString());
405
0
        return;
406
0
    }
407
408
    // This checks that ChainStateFlushed callbacks are received after BlockConnected. The check may fail
409
    // immediately after the sync thread catches up and sets m_synced. Consider the case where
410
    // there is a reorg and the blocks on the stale branch are in the ValidationInterface queue
411
    // backlog even after the sync thread has caught up to the new chain tip. In this unlikely
412
    // event, log a warning and let the queue clear.
413
0
    const CBlockIndex* best_block_index = m_best_block_index.load();
414
0
    if (best_block_index->GetAncestor(locator_tip_index->nHeight) != locator_tip_index) {
415
0
        LogWarning("Locator contains block (hash=%s) not on known best "
Line
Count
Source
98
0
#define LogWarning(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Warning, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
91
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
416
0
                  "chain (tip=%s); not writing index locator",
417
0
                  locator_tip_hash.ToString(),
418
0
                  best_block_index->GetBlockHash().ToString());
419
0
        return;
420
0
    }
421
422
    // No need to handle errors in Commit. If it fails, the error will be already be logged. The
423
    // best way to recover is to continue, as index cannot be corrupted by a missed commit to disk
424
    // for an advanced index state.
425
0
    Commit();
426
0
}
427
428
bool BaseIndex::BlockUntilSyncedToCurrentChain() const
429
0
{
430
0
    AssertLockNotHeld(cs_main);
Line
Count
Source
149
0
#define AssertLockNotHeld(cs) AssertLockNotHeldInline(#cs, __FILE__, __LINE__, &cs)
431
432
0
    if (!m_synced) {
433
0
        return false;
434
0
    }
435
436
0
    {
437
        // Skip the queue-draining stuff if we know we're caught up with
438
        // m_chain.Tip().
439
0
        LOCK(cs_main);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
440
0
        const CBlockIndex* chain_tip = m_chainstate->m_chain.Tip();
441
0
        const CBlockIndex* best_block_index = m_best_block_index.load();
442
0
        if (best_block_index->GetAncestor(chain_tip->nHeight) == chain_tip) {
443
0
            return true;
444
0
        }
445
0
    }
446
447
0
    LogInfo("%s is catching up on block notifications", GetName());
Line
Count
Source
97
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
91
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
448
0
    m_chain->context()->validation_signals->SyncWithValidationInterfaceQueue();
449
0
    return true;
450
0
}
451
452
void BaseIndex::Interrupt()
453
0
{
454
0
    m_interrupt();
455
0
}
456
457
bool BaseIndex::StartBackgroundSync()
458
0
{
459
0
    if (!m_init) throw std::logic_error("Error: Cannot start a non-initialized index");
460
461
0
    m_thread_sync = std::thread(&util::TraceThread, GetName(), [this] { Sync(); });
462
0
    return true;
463
0
}
464
465
void BaseIndex::Stop()
466
0
{
467
0
    if (m_chain->context()->validation_signals) {
468
0
        m_chain->context()->validation_signals->UnregisterValidationInterface(this);
469
0
    }
470
471
0
    if (m_thread_sync.joinable()) {
472
0
        m_thread_sync.join();
473
0
    }
474
0
}
475
476
IndexSummary BaseIndex::GetSummary() const
477
0
{
478
0
    IndexSummary summary{};
479
0
    summary.name = GetName();
480
0
    summary.synced = m_synced;
481
0
    if (const auto& pindex = m_best_block_index.load()) {
482
0
        summary.best_block_height = pindex->nHeight;
483
0
        summary.best_block_hash = pindex->GetBlockHash();
484
0
    } else {
485
0
        summary.best_block_height = 0;
486
0
        summary.best_block_hash = m_chain->getBlockHash(0);
487
0
    }
488
0
    return summary;
489
0
}
490
491
void BaseIndex::SetBestBlockIndex(const CBlockIndex* block)
492
0
{
493
0
    assert(!m_chainstate->m_blockman.IsPruneMode() || AllowPrune());
494
495
0
    if (AllowPrune() && block) {
496
0
        node::PruneLockInfo prune_lock;
497
0
        prune_lock.height_first = block->nHeight;
498
0
        WITH_LOCK(::cs_main, m_chainstate->m_blockman.UpdatePruneLock(GetName(), prune_lock));
Line
Count
Source
299
0
#define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }())
499
0
    }
500
501
    // Intentionally set m_best_block_index as the last step in this function,
502
    // after updating prune locks above, and after making any other references
503
    // to *this, so the BlockUntilSyncedToCurrentChain function (which checks
504
    // m_best_block_index as an optimization) can be used to wait for the last
505
    // BlockConnected notification and safely assume that prune locks are
506
    // updated and that the index object is safe to delete.
507
0
    m_best_block_index = block;
508
0
}