Coverage Report

Created: 2026-11-13 17:38

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