Coverage Report

Created: 2026-07-14 18:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/bitcoin/src/node/blockstorage.cpp
Line
Count
Source
1
// Copyright (c) 2011-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 <node/blockstorage.h>
6
7
#include <arith_uint256.h>
8
#include <chain.h>
9
#include <consensus/params.h>
10
#include <crypto/hex_base.h>
11
#include <dbwrapper.h>
12
#include <flatfile.h>
13
#include <hash.h>
14
#include <kernel/blockmanager_opts.h>
15
#include <kernel/chainparams.h>
16
#include <kernel/messagestartchars.h>
17
#include <kernel/notifications_interface.h>
18
#include <kernel/types.h>
19
#include <pow.h>
20
#include <primitives/block.h>
21
#include <primitives/transaction.h>
22
#include <random.h>
23
#include <serialize.h>
24
#include <signet.h>
25
#include <streams.h>
26
#include <sync.h>
27
#include <tinyformat.h>
28
#include <uint256.h>
29
#include <undo.h>
30
#include <util/check.h>
31
#include <util/expected.h>
32
#include <util/fs.h>
33
#include <util/log.h>
34
#include <util/obfuscation.h>
35
#include <util/overflow.h>
36
#include <util/result.h>
37
#include <util/signalinterrupt.h>
38
#include <util/strencodings.h>
39
#include <util/syserror.h>
40
#include <util/time.h>
41
#include <util/translation.h>
42
#include <validation.h>
43
44
#include <cerrno>
45
#include <compare>
46
#include <cstddef>
47
#include <cstdio>
48
#include <exception>
49
#include <map>
50
#include <optional>
51
#include <ostream>
52
#include <span>
53
#include <stdexcept>
54
#include <system_error>
55
#include <unordered_map>
56
57
namespace kernel {
58
static constexpr uint8_t DB_BLOCK_FILES{'f'};
59
static constexpr uint8_t DB_BLOCK_INDEX{'b'};
60
static constexpr uint8_t DB_FLAG{'F'};
61
static constexpr uint8_t DB_REINDEX_FLAG{'R'};
62
static constexpr uint8_t DB_LAST_BLOCK{'l'};
63
// Keys used in previous version that might still be found in the DB:
64
// BlockTreeDB::DB_TXINDEX_BLOCK{'T'};
65
// BlockTreeDB::DB_TXINDEX{'t'}
66
// BlockTreeDB::ReadFlag("txindex")
67
68
bool BlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo& info)
69
54
{
70
54
    return Read(std::make_pair(DB_BLOCK_FILES, nFile), info);
71
54
}
72
73
void BlockTreeDB::WriteReindexing(bool fReindexing)
74
0
{
75
0
    if (fReindexing) {
  Branch (75:9): [True: 0, False: 0]
76
0
        Write(DB_REINDEX_FLAG, uint8_t{'1'});
77
0
    } else {
78
0
        Erase(DB_REINDEX_FLAG);
79
0
    }
80
0
}
81
82
void BlockTreeDB::ReadReindexing(bool& fReindexing)
83
27
{
84
27
    fReindexing = Exists(DB_REINDEX_FLAG);
85
27
}
86
87
bool BlockTreeDB::ReadLastBlockFile(int& nFile)
88
27
{
89
27
    return Read(DB_LAST_BLOCK, nFile);
90
27
}
91
92
void BlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*>>& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo)
93
305k
{
94
305k
    CDBBatch batch(*this);
95
305k
    for (const auto& [file, info] : fileInfo) {
  Branch (95:35): [True: 153k, False: 305k]
96
153k
        batch.Write(std::make_pair(DB_BLOCK_FILES, file), *info);
97
153k
    }
98
305k
    batch.Write(DB_LAST_BLOCK, nLastFile);
99
30.2M
    for (const CBlockIndex* bi : blockinfo) {
  Branch (99:32): [True: 30.2M, False: 305k]
100
30.2M
        batch.Write(std::make_pair(DB_BLOCK_INDEX, bi->GetBlockHash()), CDiskBlockIndex{bi});
101
30.2M
    }
102
305k
    WriteBatch(batch, true);
103
305k
}
104
105
void BlockTreeDB::WriteFlag(const std::string& name, bool fValue)
106
0
{
107
0
    Write(std::make_pair(DB_FLAG, name), fValue ? uint8_t{'1'} : uint8_t{'0'});
  Branch (107:42): [True: 0, False: 0]
108
0
}
109
110
bool BlockTreeDB::ReadFlag(const std::string& name, bool& fValue)
111
27
{
112
27
    uint8_t ch;
113
27
    if (!Read(std::make_pair(DB_FLAG, name), ch)) {
  Branch (113:9): [True: 27, False: 0]
114
27
        return false;
115
27
    }
116
0
    fValue = ch == uint8_t{'1'};
117
0
    return true;
118
27
}
119
120
bool BlockTreeDB::LoadBlockIndexGuts(const Consensus::Params& consensusParams, std::function<CBlockIndex*(const uint256&)> insertBlockIndex, const util::SignalInterrupt& interrupt)
121
27
{
122
27
    AssertLockHeld(::cs_main);
123
27
    std::unique_ptr<CDBIterator> pcursor(NewIterator());
124
27
    pcursor->Seek(std::make_pair(DB_BLOCK_INDEX, uint256()));
125
126
    // Load m_block_index
127
27
    while (pcursor->Valid()) {
  Branch (127:12): [True: 0, False: 27]
128
0
        if (interrupt) return false;
  Branch (128:13): [True: 0, False: 0]
129
0
        std::pair<uint8_t, uint256> key;
130
0
        if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) {
  Branch (130:13): [True: 0, False: 0]
  Branch (130:37): [True: 0, False: 0]
131
0
            CDiskBlockIndex diskindex;
132
0
            if (pcursor->GetValue(diskindex)) {
  Branch (132:17): [True: 0, False: 0]
133
                // Construct block index object
134
0
                CBlockIndex* pindexNew = insertBlockIndex(diskindex.ConstructBlockHash());
135
0
                pindexNew->pprev          = insertBlockIndex(diskindex.hashPrev);
136
0
                pindexNew->nHeight        = diskindex.nHeight;
137
0
                pindexNew->nFile          = diskindex.nFile;
138
0
                pindexNew->nDataPos       = diskindex.nDataPos;
139
0
                pindexNew->nUndoPos       = diskindex.nUndoPos;
140
0
                pindexNew->nVersion       = diskindex.nVersion;
141
0
                pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
142
0
                pindexNew->nTime          = diskindex.nTime;
143
0
                pindexNew->nBits          = diskindex.nBits;
144
0
                pindexNew->nNonce         = diskindex.nNonce;
145
0
                pindexNew->nStatus        = diskindex.nStatus;
146
0
                pindexNew->nTx            = diskindex.nTx;
147
148
0
                if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, consensusParams)) {
  Branch (148:21): [True: 0, False: 0]
149
0
                    LogError("%s: CheckProofOfWork failed: %s\n", __func__, pindexNew->ToString());
150
0
                    return false;
151
0
                }
152
153
0
                pcursor->Next();
154
0
            } else {
155
0
                LogError("%s: failed to read value\n", __func__);
156
0
                return false;
157
0
            }
158
0
        } else {
159
0
            break;
160
0
        }
161
0
    }
162
163
27
    return true;
164
27
}
165
166
std::string CBlockFileInfo::ToString() const
167
27
{
168
27
    return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, FormatISO8601Date(nTimeFirst), FormatISO8601Date(nTimeLast));
169
27
}
170
} // namespace kernel
171
172
namespace node {
173
174
bool CBlockIndexWorkComparator::operator()(const CBlockIndex* pa, const CBlockIndex* pb) const
175
278M
{
176
    // First sort by most total work, ...
177
278M
    if (pa->nChainWork > pb->nChainWork) return false;
  Branch (177:9): [True: 92.8M, False: 185M]
178
185M
    if (pa->nChainWork < pb->nChainWork) return true;
  Branch (178:9): [True: 182M, False: 2.72M]
179
180
    // ... then by earliest activatable time, ...
181
2.72M
    if (pa->nSequenceId < pb->nSequenceId) return false;
  Branch (181:9): [True: 408k, False: 2.31M]
182
2.31M
    if (pa->nSequenceId > pb->nSequenceId) return true;
  Branch (182:9): [True: 560k, False: 1.75M]
183
184
    // Use pointer address as tie breaker (should only happen with blocks
185
    // loaded from disk, as those share the same id: 0 for blocks on the
186
    // best chain, 1 for all others).
187
1.75M
    if (pa < pb) return false;
  Branch (187:9): [True: 0, False: 1.75M]
188
1.75M
    if (pa > pb) return true;
  Branch (188:9): [True: 0, False: 1.75M]
189
190
    // Identical blocks.
191
1.75M
    return false;
192
1.75M
}
193
194
bool CBlockIndexHeightOnlyComparator::operator()(const CBlockIndex* pa, const CBlockIndex* pb) const
195
0
{
196
0
    return pa->nHeight < pb->nHeight;
197
0
}
198
199
std::vector<CBlockIndex*> BlockManager::GetAllBlockIndices()
200
81
{
201
81
    AssertLockHeld(cs_main);
202
81
    std::vector<CBlockIndex*> rv;
203
81
    rv.reserve(m_block_index.size());
204
81
    for (auto& [_, block_index] : m_block_index) {
  Branch (204:33): [True: 27, False: 81]
205
27
        rv.push_back(&block_index);
206
27
    }
207
81
    return rv;
208
81
}
209
210
CBlockIndex* BlockManager::LookupBlockIndex(const uint256& hash)
211
2.43M
{
212
2.43M
    AssertLockHeld(cs_main);
213
2.43M
    BlockMap::iterator it = m_block_index.find(hash);
214
2.43M
    return it == m_block_index.end() ? nullptr : &it->second;
  Branch (214:12): [True: 386k, False: 2.04M]
215
2.43M
}
216
217
const CBlockIndex* BlockManager::LookupBlockIndex(const uint256& hash) const
218
0
{
219
0
    AssertLockHeld(cs_main);
220
0
    BlockMap::const_iterator it = m_block_index.find(hash);
221
0
    return it == m_block_index.end() ? nullptr : &it->second;
  Branch (221:12): [True: 0, False: 0]
222
0
}
223
224
CBlockIndex* BlockManager::AddToBlockIndex(const CBlockHeader& block, CBlockIndex*& best_header)
225
107k
{
226
107k
    AssertLockHeld(cs_main);
227
228
107k
    auto [mi, inserted] = m_block_index.try_emplace(block.GetHash(), block);
229
107k
    if (!inserted) {
  Branch (229:9): [True: 0, False: 107k]
230
0
        return &mi->second;
231
0
    }
232
107k
    CBlockIndex* pindexNew = &(*mi).second;
233
234
    // We assign the sequence id to blocks only when the full data is available,
235
    // to avoid miners withholding blocks but broadcasting headers, to get a
236
    // competitive advantage.
237
107k
    pindexNew->nSequenceId = SEQ_ID_INIT_FROM_DISK;
238
239
107k
    pindexNew->phashBlock = &((*mi).first);
240
107k
    BlockMap::iterator miPrev = m_block_index.find(block.hashPrevBlock);
241
107k
    if (miPrev != m_block_index.end()) {
  Branch (241:9): [True: 107k, False: 27]
242
107k
        pindexNew->pprev = &(*miPrev).second;
243
107k
        pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
244
107k
        pindexNew->BuildSkip();
245
107k
    }
246
107k
    pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
  Branch (246:28): [True: 107k, False: 27]
247
107k
    pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
  Branch (247:30): [True: 107k, False: 27]
248
107k
    pindexNew->RaiseValidity(BLOCK_VALID_TREE);
249
107k
    if (best_header == nullptr || best_header->nChainWork < pindexNew->nChainWork) {
  Branch (249:9): [True: 18.4E, False: 107k]
  Branch (249:35): [True: 40.7k, False: 67.1k]
250
40.5k
        best_header = pindexNew;
251
40.5k
    }
252
253
107k
    m_dirty_blockindex.insert(pindexNew);
254
255
107k
    return pindexNew;
256
107k
}
257
258
void BlockManager::AddUnlinkedBlock(CBlockIndex* block)
259
34.5k
{
260
34.5k
    AssertLockHeld(cs_main);
261
34.5k
    Assume(block != nullptr);
262
34.5k
    Assume(block->nStatus & BLOCK_HAVE_DATA);
263
34.5k
    auto range = m_blocks_unlinked.equal_range(block->pprev);
264
45.4k
    for (auto it = range.first; it != range.second; ++it) {
  Branch (264:33): [True: 10.8k, False: 34.5k]
265
10.8k
        if (it->second == block) return;  // don't insert duplicates
  Branch (265:13): [True: 0, False: 10.8k]
266
10.8k
    }
267
34.5k
    m_blocks_unlinked.emplace(block->pprev, block);
268
34.5k
}
269
270
void BlockManager::PruneOneBlockFile(const int fileNumber)
271
0
{
272
0
    AssertLockHeld(cs_main);
273
274
0
    for (auto& entry : m_block_index) {
  Branch (274:22): [True: 0, False: 0]
275
0
        CBlockIndex* pindex = &entry.second;
276
0
        if (pindex->nFile == fileNumber) {
  Branch (276:13): [True: 0, False: 0]
277
0
            pindex->nStatus &= ~BLOCK_HAVE_DATA;
278
0
            pindex->nStatus &= ~BLOCK_HAVE_UNDO;
279
0
            pindex->nFile = 0;
280
0
            pindex->nDataPos = 0;
281
0
            pindex->nUndoPos = 0;
282
0
            m_dirty_blockindex.insert(pindex);
283
284
            // Prune from m_blocks_unlinked -- any block we prune would have
285
            // to be downloaded again in order to consider its chain, at which
286
            // point it would be considered as a candidate for
287
            // m_blocks_unlinked or setBlockIndexCandidates.
288
0
            auto range = m_blocks_unlinked.equal_range(pindex->pprev);
289
0
            while (range.first != range.second) {
  Branch (289:20): [True: 0, False: 0]
290
0
                std::multimap<CBlockIndex*, CBlockIndex*>::iterator _it = range.first;
291
0
                range.first++;
292
0
                if (_it->second == pindex) {
  Branch (292:21): [True: 0, False: 0]
293
0
                    m_blocks_unlinked.erase(_it);
294
0
                }
295
0
            }
296
0
        }
297
0
    }
298
299
0
    m_blockfile_info.at(fileNumber) = CBlockFileInfo{};
300
0
    m_dirty_fileinfo.insert(fileNumber);
301
0
}
302
303
void BlockManager::FindFilesToPruneManual(
304
    std::set<int>& setFilesToPrune,
305
    int nManualPruneHeight,
306
    const Chainstate& chain)
307
0
{
308
0
    assert(IsPruneMode() && nManualPruneHeight > 0);
  Branch (308:5): [True: 0, False: 0]
  Branch (308:5): [True: 0, False: 0]
  Branch (308:5): [True: 0, False: 0]
309
310
0
    LOCK(::cs_main);
311
0
    if (chain.m_chain.Height() < 0) {
  Branch (311:9): [True: 0, False: 0]
312
0
        return;
313
0
    }
314
315
0
    const auto [min_block_to_prune, last_block_can_prune] = chain.GetPruneRange(nManualPruneHeight);
316
317
0
    int count = 0;
318
0
    for (int fileNumber = 0; fileNumber < this->MaxBlockfileNum(); fileNumber++) {
  Branch (318:30): [True: 0, False: 0]
319
0
        const auto& fileinfo = m_blockfile_info[fileNumber];
320
0
        if (fileinfo.nSize == 0 || fileinfo.nHeightLast > (unsigned)last_block_can_prune || fileinfo.nHeightFirst < (unsigned)min_block_to_prune) {
  Branch (320:13): [True: 0, False: 0]
  Branch (320:36): [True: 0, False: 0]
  Branch (320:93): [True: 0, False: 0]
321
0
            continue;
322
0
        }
323
324
0
        PruneOneBlockFile(fileNumber);
325
0
        setFilesToPrune.insert(fileNumber);
326
0
        count++;
327
0
    }
328
0
    LogInfo("[%s] Prune (Manual): prune_height=%d removed %d blk/rev pairs",
329
0
        chain.GetRole(), last_block_can_prune, count);
330
0
}
331
332
void BlockManager::FindFilesToPrune(
333
    std::set<int>& setFilesToPrune,
334
    int last_prune,
335
    const Chainstate& chain,
336
    ChainstateManager& chainman)
337
0
{
338
0
    LOCK(::cs_main);
339
    // Compute `target` value with maximum size (in bytes) of blocks below the
340
    // `last_prune` height which should be preserved and not pruned. The
341
    // `target` value will be derived from the -prune preference provided by the
342
    // user. If there is a historical chainstate being used to populate indexes
343
    // and validate the snapshot, the target is divided by two so half of the
344
    // block storage will be reserved for the historical chainstate, and the
345
    // other half will be reserved for the most-work chainstate.
346
0
    const int num_chainstates{chainman.HistoricalChainstate() ? 2 : 1};
  Branch (346:31): [True: 0, False: 0]
347
0
    const auto target = std::max(
348
0
        MIN_DISK_SPACE_FOR_BLOCK_FILES, GetPruneTarget() / num_chainstates);
349
0
    const uint64_t target_sync_height = chainman.m_best_header->nHeight;
350
351
0
    if (chain.m_chain.Height() < 0 || target == 0) {
  Branch (351:9): [True: 0, False: 0]
  Branch (351:39): [True: 0, False: 0]
352
0
        return;
353
0
    }
354
0
    if (static_cast<uint64_t>(chain.m_chain.Height()) <= chainman.GetParams().PruneAfterHeight()) {
  Branch (354:9): [True: 0, False: 0]
355
0
        return;
356
0
    }
357
358
0
    const auto [min_block_to_prune, last_block_can_prune] = chain.GetPruneRange(last_prune);
359
360
0
    uint64_t nCurrentUsage = CalculateCurrentUsage();
361
    // We don't check to prune until after we've allocated new space for files
362
    // So we should leave a buffer under our target to account for another allocation
363
    // before the next pruning.
364
0
    uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
365
0
    uint64_t nBytesToPrune;
366
0
    int count = 0;
367
368
0
    if (nCurrentUsage + nBuffer >= target) {
  Branch (368:9): [True: 0, False: 0]
369
        // On a prune event, the chainstate DB is flushed.
370
        // To avoid excessive prune events negating the benefit of high dbcache
371
        // values, we should not prune too rapidly.
372
        // So when pruning in IBD, increase the buffer to avoid a re-prune too soon.
373
0
        const auto chain_tip_height = chain.m_chain.Height();
374
0
        if (chainman.IsInitialBlockDownload() && target_sync_height > (uint64_t)chain_tip_height) {
  Branch (374:13): [True: 0, False: 0]
  Branch (374:50): [True: 0, False: 0]
375
            // Since this is only relevant during IBD, we assume blocks are at least 1 MB on average
376
0
            static constexpr uint64_t average_block_size = 1000000;  /* 1 MB */
377
0
            const uint64_t remaining_blocks = target_sync_height - chain_tip_height;
378
0
            nBuffer += average_block_size * remaining_blocks;
379
0
        }
380
381
0
        for (int fileNumber = 0; fileNumber < this->MaxBlockfileNum(); fileNumber++) {
  Branch (381:34): [True: 0, False: 0]
382
0
            const auto& fileinfo = m_blockfile_info[fileNumber];
383
0
            nBytesToPrune = fileinfo.nSize + fileinfo.nUndoSize;
384
385
0
            if (fileinfo.nSize == 0) {
  Branch (385:17): [True: 0, False: 0]
386
0
                continue;
387
0
            }
388
389
0
            if (nCurrentUsage + nBuffer < target) { // are we below our target?
  Branch (389:17): [True: 0, False: 0]
390
0
                break;
391
0
            }
392
393
            // don't prune files that could have a block that's not within the allowable
394
            // prune range for the chain being pruned.
395
0
            if (fileinfo.nHeightLast > (unsigned)last_block_can_prune || fileinfo.nHeightFirst < (unsigned)min_block_to_prune) {
  Branch (395:17): [True: 0, False: 0]
  Branch (395:74): [True: 0, False: 0]
396
0
                continue;
397
0
            }
398
399
0
            PruneOneBlockFile(fileNumber);
400
            // Queue up the files for removal
401
0
            setFilesToPrune.insert(fileNumber);
402
0
            nCurrentUsage -= nBytesToPrune;
403
0
            count++;
404
0
        }
405
0
    }
406
407
0
    LogDebug(BCLog::PRUNE, "[%s] target=%dMiB actual=%dMiB diff=%dMiB min_height=%d max_prune_height=%d removed %d blk/rev pairs\n",
408
0
             chain.GetRole(), target / 1_MiB, nCurrentUsage / 1_MiB,
409
0
             (int64_t(target) - int64_t(nCurrentUsage)) / int64_t(1_MiB),
410
0
             min_block_to_prune, last_block_can_prune, count);
411
0
}
412
413
59.5k
void BlockManager::UpdatePruneLock(const std::string& name, const PruneLockInfo& lock_info) {
414
59.5k
    AssertLockHeld(::cs_main);
415
59.5k
    m_prune_locks[name] = lock_info;
416
59.5k
}
417
418
bool BlockManager::DeletePruneLock(const std::string& name)
419
0
{
420
0
    AssertLockHeld(::cs_main);
421
0
    return m_prune_locks.erase(name) > 0;
422
0
}
423
424
CBlockIndex* BlockManager::InsertBlockIndex(const uint256& hash)
425
0
{
426
0
    AssertLockHeld(cs_main);
427
428
0
    if (hash.IsNull()) {
  Branch (428:9): [True: 0, False: 0]
429
0
        return nullptr;
430
0
    }
431
432
0
    const auto [mi, inserted]{m_block_index.try_emplace(hash)};
433
0
    CBlockIndex* pindex = &(*mi).second;
434
0
    if (inserted) {
  Branch (434:9): [True: 0, False: 0]
435
0
        pindex->phashBlock = &((*mi).first);
436
0
    }
437
0
    return pindex;
438
0
}
439
440
bool BlockManager::LoadBlockIndex(const std::optional<uint256>& snapshot_blockhash)
441
27
{
442
27
    if (!m_block_tree_db->LoadBlockIndexGuts(
  Branch (442:9): [True: 0, False: 27]
443
27
            GetConsensus(), [this](const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return this->InsertBlockIndex(hash); }, m_interrupt)) {
444
0
        return false;
445
0
    }
446
447
27
    if (snapshot_blockhash) {
  Branch (447:9): [True: 0, False: 27]
448
0
        const std::optional<AssumeutxoData> maybe_au_data = GetParams().AssumeutxoForBlockhash(*snapshot_blockhash);
449
0
        if (!maybe_au_data) {
  Branch (449:13): [True: 0, False: 0]
450
0
            m_opts.notifications.fatalError(strprintf(_("Assumeutxo data not found for the given blockhash '%s'."), snapshot_blockhash->ToString()));
451
0
            return false;
452
0
        }
453
0
        const AssumeutxoData& au_data = *Assert(maybe_au_data);
454
0
        m_snapshot_height = au_data.height;
455
0
        CBlockIndex* base{LookupBlockIndex(*snapshot_blockhash)};
456
457
        // Since m_chain_tx_count (responsible for estimated progress) isn't persisted
458
        // to disk, we must bootstrap the value for assumedvalid chainstates
459
        // from the hardcoded assumeutxo chainparams.
460
0
        base->m_chain_tx_count = au_data.m_chain_tx_count;
461
0
        LogInfo("[snapshot] set m_chain_tx_count=%d for %s", au_data.m_chain_tx_count, snapshot_blockhash->ToString());
462
27
    } else {
463
        // If this isn't called with a snapshot blockhash, make sure the cached snapshot height
464
        // is null. This is relevant during snapshot completion, when the blockman may be loaded
465
        // with a height that then needs to be cleared after the snapshot is fully validated.
466
27
        m_snapshot_height.reset();
467
27
    }
468
469
27
    Assert(m_snapshot_height.has_value() == snapshot_blockhash.has_value());
470
471
    // Calculate nChainWork
472
27
    std::vector<CBlockIndex*> vSortedByHeight{GetAllBlockIndices()};
473
27
    std::sort(vSortedByHeight.begin(), vSortedByHeight.end(),
474
27
              CBlockIndexHeightOnlyComparator());
475
476
27
    CBlockIndex* previous_index{nullptr};
477
27
    for (CBlockIndex* pindex : vSortedByHeight) {
  Branch (477:30): [True: 0, False: 27]
478
0
        if (m_interrupt) return false;
  Branch (478:13): [True: 0, False: 0]
479
0
        if (previous_index && pindex->nHeight > previous_index->nHeight + 1) {
  Branch (479:13): [True: 0, False: 0]
  Branch (479:31): [True: 0, False: 0]
480
0
            LogError("%s: block index is non-contiguous, index of height %d missing\n", __func__, previous_index->nHeight + 1);
481
0
            return false;
482
0
        }
483
0
        previous_index = pindex;
484
0
        pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
  Branch (484:31): [True: 0, False: 0]
485
0
        pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
  Branch (485:29): [True: 0, False: 0]
486
487
        // We can link the chain of blocks for which we've received transactions at some point, or
488
        // blocks that are assumed-valid on the basis of snapshot load (see
489
        // PopulateAndValidateSnapshot()).
490
        // Pruned nodes may have deleted the block.
491
0
        if (pindex->nTx > 0) {
  Branch (491:13): [True: 0, False: 0]
492
0
            if (pindex->pprev) {
  Branch (492:17): [True: 0, False: 0]
493
0
                if (m_snapshot_height && pindex->nHeight == *m_snapshot_height &&
  Branch (493:21): [True: 0, False: 0]
  Branch (493:21): [True: 0, False: 0]
  Branch (493:42): [True: 0, False: 0]
494
0
                        pindex->GetBlockHash() == *snapshot_blockhash) {
  Branch (494:25): [True: 0, False: 0]
495
                    // Should have been set above; don't disturb it with code below.
496
0
                    Assert(pindex->m_chain_tx_count > 0);
497
0
                } else if (pindex->pprev->m_chain_tx_count > 0) {
  Branch (497:28): [True: 0, False: 0]
498
0
                    pindex->m_chain_tx_count = pindex->pprev->m_chain_tx_count + pindex->nTx;
499
0
                } else {
500
0
                    pindex->m_chain_tx_count = 0;
501
0
                    if (pindex->nStatus & BLOCK_HAVE_DATA) {
  Branch (501:25): [True: 0, False: 0]
502
0
                        AddUnlinkedBlock(pindex);
503
0
                    }
504
0
                }
505
0
            } else {
506
0
                pindex->m_chain_tx_count = pindex->nTx;
507
0
            }
508
0
        }
509
510
0
        if (pindex->nStatus & BLOCK_FAILED_CHILD) {
  Branch (510:13): [True: 0, False: 0]
511
            // BLOCK_FAILED_CHILD is deprecated, but may still exist on disk. Replace it with BLOCK_FAILED_VALID.
512
0
            pindex->nStatus = (pindex->nStatus & ~BLOCK_FAILED_CHILD) | BLOCK_FAILED_VALID;
513
0
            m_dirty_blockindex.insert(pindex);
514
0
        }
515
0
        if (!(pindex->nStatus & BLOCK_FAILED_VALID) && pindex->pprev && (pindex->pprev->nStatus & BLOCK_FAILED_VALID)) {
  Branch (515:13): [True: 0, False: 0]
  Branch (515:56): [True: 0, False: 0]
  Branch (515:73): [True: 0, False: 0]
516
            // All descendants of invalid blocks are invalid too.
517
0
            pindex->nStatus |= BLOCK_FAILED_VALID;
518
0
            m_dirty_blockindex.insert(pindex);
519
0
        }
520
521
0
        if (pindex->pprev) {
  Branch (521:13): [True: 0, False: 0]
522
0
            pindex->BuildSkip();
523
0
        }
524
0
    }
525
526
27
    return true;
527
27
}
528
529
void BlockManager::WriteBlockIndexDB()
530
305k
{
531
305k
    AssertLockHeld(::cs_main);
532
305k
    std::vector<std::pair<int, const CBlockFileInfo*>> vFiles;
533
305k
    vFiles.reserve(m_dirty_fileinfo.size());
534
459k
    for (std::set<int>::iterator it = m_dirty_fileinfo.begin(); it != m_dirty_fileinfo.end();) {
  Branch (534:65): [True: 153k, False: 305k]
535
153k
        vFiles.emplace_back(*it, &m_blockfile_info[*it]);
536
153k
        m_dirty_fileinfo.erase(it++);
537
153k
    }
538
305k
    std::vector<const CBlockIndex*> vBlocks;
539
305k
    vBlocks.reserve(m_dirty_blockindex.size());
540
30.5M
    for (std::set<CBlockIndex*>::iterator it = m_dirty_blockindex.begin(); it != m_dirty_blockindex.end();) {
  Branch (540:76): [True: 30.2M, False: 305k]
541
30.2M
        vBlocks.push_back(*it);
542
30.2M
        m_dirty_blockindex.erase(it++);
543
30.2M
    }
544
305k
    int max_blockfile{this->MaxBlockfileNum()};
545
305k
    m_block_tree_db->WriteBatchSync(vFiles, max_blockfile, vBlocks);
546
305k
}
547
548
bool BlockManager::LoadBlockIndexDB(const std::optional<uint256>& snapshot_blockhash)
549
27
{
550
27
    AssertLockHeld(::cs_main);
551
27
    if (!LoadBlockIndex(snapshot_blockhash)) {
  Branch (551:9): [True: 0, False: 27]
552
0
        return false;
553
0
    }
554
27
    int max_blockfile_num{0};
555
556
    // Load block file info
557
27
    m_block_tree_db->ReadLastBlockFile(max_blockfile_num);
558
27
    m_blockfile_info.resize(max_blockfile_num + 1);
559
27
    LogInfo("Loading block index db: last block file = %i", max_blockfile_num);
560
54
    for (int nFile = 0; nFile <= max_blockfile_num; nFile++) {
  Branch (560:25): [True: 27, False: 27]
561
27
        m_block_tree_db->ReadBlockFileInfo(nFile, m_blockfile_info[nFile]);
562
27
    }
563
27
    LogInfo("Loading block index db: last block file info: %s", m_blockfile_info[max_blockfile_num].ToString());
564
27
    for (int nFile = max_blockfile_num + 1; true; nFile++) {
  Branch (564:45): [Folded - Ignored]
565
27
        CBlockFileInfo info;
566
27
        if (m_block_tree_db->ReadBlockFileInfo(nFile, info)) {
  Branch (566:13): [True: 0, False: 27]
567
0
            m_blockfile_info.push_back(info);
568
27
        } else {
569
27
            break;
570
27
        }
571
27
    }
572
573
    // Check presence of blk files
574
27
    LogInfo("Checking all blk files are present...");
575
27
    std::set<int> setBlkDataFiles;
576
27
    for (const auto& [_, block_index] : m_block_index) {
  Branch (576:39): [True: 0, False: 27]
577
0
        if (block_index.nStatus & BLOCK_HAVE_DATA) {
  Branch (577:13): [True: 0, False: 0]
578
0
            setBlkDataFiles.insert(block_index.nFile);
579
0
        }
580
0
    }
581
27
    for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) {
  Branch (581:64): [True: 0, False: 27]
582
0
        FlatFilePos pos(*it, 0);
583
0
        if (OpenBlockFile(pos, /*fReadOnly=*/true).IsNull()) {
  Branch (583:13): [True: 0, False: 0]
584
0
            return false;
585
0
        }
586
0
    }
587
588
27
    {
589
        // Initialize the blockfile cursors.
590
54
        for (size_t i = 0; i < m_blockfile_info.size(); ++i) {
  Branch (590:28): [True: 27, False: 27]
591
27
            const auto last_height_in_file = m_blockfile_info[i].nHeightLast;
592
27
            m_blockfile_cursors[BlockfileTypeForHeight(last_height_in_file)] = {static_cast<int>(i), 0};
593
27
        }
594
27
    }
595
596
    // Check whether we have ever pruned block & undo files
597
27
    m_block_tree_db->ReadFlag("prunedblockfiles", m_have_pruned);
598
27
    if (m_have_pruned) {
  Branch (598:9): [True: 0, False: 27]
599
0
        LogInfo("Loading block index db: Block files have previously been pruned");
600
0
    }
601
602
    // Check whether we need to continue reindexing
603
27
    bool fReindexing = false;
604
27
    m_block_tree_db->ReadReindexing(fReindexing);
605
27
    if (fReindexing) m_blockfiles_indexed = false;
  Branch (605:9): [True: 0, False: 27]
606
607
27
    return true;
608
27
}
609
610
void BlockManager::ScanAndUnlinkAlreadyPrunedFiles()
611
27
{
612
27
    AssertLockHeld(::cs_main);
613
27
    int max_blockfile{this->MaxBlockfileNum()};
614
27
    if (!m_have_pruned) {
  Branch (614:9): [True: 27, False: 0]
615
27
        return;
616
27
    }
617
618
0
    std::set<int> block_files_to_prune;
619
0
    for (int file_number = 0; file_number < max_blockfile; file_number++) {
  Branch (619:31): [True: 0, False: 0]
620
0
        if (m_blockfile_info[file_number].nSize == 0) {
  Branch (620:13): [True: 0, False: 0]
621
0
            block_files_to_prune.insert(file_number);
622
0
        }
623
0
    }
624
625
0
    UnlinkPrunedFiles(block_files_to_prune);
626
0
}
627
628
bool BlockManager::IsBlockPruned(const CBlockIndex& block) const
629
0
{
630
0
    AssertLockHeld(::cs_main);
631
0
    return m_have_pruned && !(block.nStatus & BLOCK_HAVE_DATA) && (block.nTx > 0);
  Branch (631:12): [True: 0, False: 0]
  Branch (631:29): [True: 0, False: 0]
  Branch (631:67): [True: 0, False: 0]
632
0
}
633
634
const CBlockIndex& BlockManager::GetFirstBlock(const CBlockIndex& upper_block, uint32_t status_mask, const CBlockIndex* lower_block) const
635
0
{
636
0
    AssertLockHeld(::cs_main);
637
0
    const CBlockIndex* last_block = &upper_block;
638
0
    assert((last_block->nStatus & status_mask) == status_mask); // 'upper_block' must satisfy the status mask
  Branch (638:5): [True: 0, False: 0]
639
0
    while (last_block->pprev && ((last_block->pprev->nStatus & status_mask) == status_mask)) {
  Branch (639:12): [True: 0, False: 0]
  Branch (639:33): [True: 0, False: 0]
640
0
        if (lower_block) {
  Branch (640:13): [True: 0, False: 0]
641
            // Return if we reached the lower_block
642
0
            if (last_block == lower_block) return *lower_block;
  Branch (642:17): [True: 0, False: 0]
643
            // if range was surpassed, means that 'lower_block' is not part of the 'upper_block' chain
644
            // and so far this is not allowed.
645
0
            assert(last_block->nHeight >= lower_block->nHeight);
  Branch (645:13): [True: 0, False: 0]
646
0
        }
647
0
        last_block = last_block->pprev;
648
0
    }
649
0
    assert(last_block != nullptr);
  Branch (649:5): [True: 0, False: 0]
650
0
    return *last_block;
651
0
}
652
653
bool BlockManager::CheckBlockDataAvailability(const CBlockIndex& upper_block, const CBlockIndex& lower_block, BlockStatus block_status)
654
0
{
655
0
    if (!(upper_block.nStatus & block_status)) return false;
  Branch (655:9): [True: 0, False: 0]
656
0
    const auto& first_block = GetFirstBlock(upper_block, block_status, &lower_block);
657
    // Special case: the genesis block has no undo data
658
0
    if (block_status & BLOCK_HAVE_UNDO && lower_block.nHeight == 0 && first_block.nHeight == 1) {
  Branch (658:9): [True: 0, False: 0]
  Branch (658:43): [True: 0, False: 0]
  Branch (658:71): [True: 0, False: 0]
659
        // This might indicate missing data, or it could simply reflect the expected absence of undo data for the genesis block.
660
        // To distinguish between the two, check if all required block data *except* undo is available up to the genesis block.
661
0
        BlockStatus flags{block_status & ~BLOCK_HAVE_UNDO};
662
0
        return first_block.pprev && first_block.pprev->nStatus & flags;
  Branch (662:16): [True: 0, False: 0]
  Branch (662:37): [True: 0, False: 0]
663
0
    }
664
0
    return &first_block == &lower_block;
665
0
}
666
667
// If we're using -prune with -reindex, then delete block files that will be ignored by the
668
// reindex.  Since reindexing works by starting at block file 0 and looping until a blockfile
669
// is missing, do the same here to delete any later block files after a gap.  Also delete all
670
// rev files since they'll be rewritten by the reindex anyway.  This ensures that m_blockfile_info
671
// is in sync with what's actually on disk by the time we start downloading, so that pruning
672
// works correctly.
673
void BlockManager::CleanupBlockRevFiles() const
674
0
{
675
0
    std::map<std::string, fs::path> mapBlockFiles;
676
677
    // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
678
    // Remove the rev files immediately and insert the blk file paths into an
679
    // ordered map keyed by block file index.
680
0
    LogInfo("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune");
681
0
    for (fs::directory_iterator it(m_opts.blocks_dir); it != fs::directory_iterator(); it++) {
  Branch (681:56): [True: 0, False: 0]
682
0
        const std::string path = fs::PathToString(it->path().filename());
683
0
        if (fs::is_regular_file(*it) &&
  Branch (683:13): [True: 0, False: 0]
684
0
            path.length() == 12 &&
  Branch (684:13): [True: 0, False: 0]
685
0
            path.ends_with(".dat"))
  Branch (685:13): [True: 0, False: 0]
686
0
        {
687
0
            if (path.starts_with("blk")) {
  Branch (687:17): [True: 0, False: 0]
688
0
                mapBlockFiles[path.substr(3, 5)] = it->path();
689
0
            } else if (path.starts_with("rev")) {
  Branch (689:24): [True: 0, False: 0]
690
0
                remove(it->path());
691
0
            }
692
0
        }
693
0
    }
694
695
    // Remove all block files that aren't part of a contiguous set starting at
696
    // zero by walking the ordered map (keys are block file indices) by
697
    // keeping a separate counter.  Once we hit a gap (or if 0 doesn't exist)
698
    // start removing block files.
699
0
    int nContigCounter = 0;
700
0
    for (const std::pair<const std::string, fs::path>& item : mapBlockFiles) {
  Branch (700:61): [True: 0, False: 0]
701
0
        if (LocaleIndependentAtoi<int>(item.first) == nContigCounter) {
  Branch (701:13): [True: 0, False: 0]
702
0
            nContigCounter++;
703
0
            continue;
704
0
        }
705
0
        remove(item.second);
706
0
    }
707
0
}
708
709
CBlockFileInfo* BlockManager::GetBlockFileInfo(size_t n)
710
0
{
711
0
    AssertLockHeld(::cs_main);
712
0
    return &m_blockfile_info.at(n);
713
0
}
714
715
bool BlockManager::ReadBlockUndo(CBlockUndo& blockundo, const CBlockIndex& index) const
716
64.5k
{
717
64.5k
    const FlatFilePos pos{WITH_LOCK(::cs_main, return index.GetUndoPos())};
718
719
    // Open history file to read
720
64.5k
    AutoFile file{OpenUndoFile(pos, true)};
721
64.5k
    if (file.IsNull()) {
  Branch (721:9): [True: 0, False: 64.5k]
722
0
        LogError("OpenUndoFile failed for %s while reading block undo", pos.ToString());
723
0
        return false;
724
0
    }
725
64.5k
    BufferedReader filein{std::move(file)};
726
727
64.5k
    try {
728
        // Read block
729
64.5k
        HashVerifier verifier{filein}; // Use HashVerifier, as reserializing may lose data, c.f. commit d3424243
730
731
64.5k
        verifier << index.pprev->GetBlockHash();
732
64.5k
        verifier >> blockundo;
733
734
64.5k
        uint256 hashChecksum;
735
64.5k
        filein >> hashChecksum;
736
737
        // Verify checksum
738
64.5k
        if (hashChecksum != verifier.GetHash()) {
  Branch (738:13): [True: 0, False: 64.5k]
739
0
            LogError("Checksum mismatch at %s while reading block undo", pos.ToString());
740
0
            return false;
741
0
        }
742
64.5k
    } catch (const std::exception& e) {
743
0
        LogError("Deserialize or I/O error - %s at %s while reading block undo", e.what(), pos.ToString());
744
0
        return false;
745
0
    }
746
747
64.5k
    return true;
748
64.5k
}
749
750
bool BlockManager::FlushUndoFile(int block_file, bool finalize)
751
305k
{
752
305k
    FlatFilePos undo_pos_old(block_file, m_blockfile_info[block_file].nUndoSize);
753
305k
    if (!m_undo_file_seq.Flush(undo_pos_old, finalize)) {
  Branch (753:9): [True: 0, False: 305k]
754
0
        m_opts.notifications.flushError(_("Flushing undo file to disk failed. This is likely the result of an I/O error."));
755
0
        return false;
756
0
    }
757
305k
    return true;
758
305k
}
759
760
bool BlockManager::FlushBlockFile(int blockfile_num, bool fFinalize, bool finalize_undo)
761
305k
{
762
305k
    AssertLockHeld(::cs_main);
763
305k
    bool success = true;
764
765
305k
    if (m_blockfile_info.size() < 1) {
  Branch (765:9): [True: 0, False: 305k]
766
        // Return if we haven't loaded any blockfiles yet. This happens during
767
        // chainstate init, when we call ChainstateManager::MaybeRebalanceCaches() (which
768
        // then calls FlushStateToDisk()), resulting in a call to this function before we
769
        // have populated `m_blockfile_info` via LoadBlockIndexDB().
770
0
        return true;
771
0
    }
772
305k
    assert(static_cast<int>(m_blockfile_info.size()) > blockfile_num);
  Branch (772:5): [True: 305k, False: 0]
773
774
305k
    FlatFilePos block_pos_old(blockfile_num, m_blockfile_info[blockfile_num].nSize);
775
305k
    if (!m_block_file_seq.Flush(block_pos_old, fFinalize)) {
  Branch (775:9): [True: 0, False: 305k]
776
0
        m_opts.notifications.flushError(_("Flushing block file to disk failed. This is likely the result of an I/O error."));
777
0
        success = false;
778
0
    }
779
    // we do not always flush the undo file, as the chain tip may be lagging behind the incoming blocks,
780
    // e.g. during IBD or a sync after a node going offline
781
305k
    if (!fFinalize || finalize_undo) {
  Branch (781:9): [True: 305k, False: 0]
  Branch (781:23): [True: 0, False: 0]
782
305k
        if (!FlushUndoFile(blockfile_num, finalize_undo)) {
  Branch (782:13): [True: 0, False: 305k]
783
0
            success = false;
784
0
        }
785
305k
    }
786
305k
    return success;
787
305k
}
788
789
BlockfileType BlockManager::BlockfileTypeForHeight(int height)
790
419k
{
791
419k
    if (!m_snapshot_height) {
  Branch (791:9): [True: 419k, False: 0]
792
419k
        return BlockfileType::NORMAL;
793
419k
    }
794
0
    return (height >= *m_snapshot_height) ? BlockfileType::ASSUMED : BlockfileType::NORMAL;
  Branch (794:12): [True: 0, False: 0]
795
419k
}
796
797
bool BlockManager::FlushChainstateBlockFile(int tip_height)
798
305k
{
799
305k
    AssertLockHeld(::cs_main);
800
305k
    auto& cursor = m_blockfile_cursors[BlockfileTypeForHeight(tip_height)];
801
    // If the cursor does not exist, it means an assumeutxo snapshot is loaded,
802
    // but no blocks past the snapshot height have been written yet, so there
803
    // is no data associated with the chainstate, and it is safe not to flush.
804
305k
    if (cursor) {
  Branch (804:9): [True: 305k, False: 0]
805
305k
        return FlushBlockFile(cursor->file_num, /*fFinalize=*/false, /*finalize_undo=*/false);
806
305k
    }
807
    // No need to log warnings in this case.
808
0
    return true;
809
305k
}
810
811
uint64_t BlockManager::CalculateCurrentUsage()
812
0
{
813
0
    AssertLockHeld(::cs_main);
814
0
    uint64_t retval = 0;
815
0
    for (const CBlockFileInfo& file : m_blockfile_info) {
  Branch (815:37): [True: 0, False: 0]
816
0
        retval += file.nSize + file.nUndoSize;
817
0
    }
818
0
    return retval;
819
0
}
820
821
void BlockManager::UnlinkPrunedFiles(const std::set<int>& setFilesToPrune) const
822
0
{
823
0
    std::error_code ec;
824
0
    for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
  Branch (824:64): [True: 0, False: 0]
825
0
        FlatFilePos pos(*it, 0);
826
0
        const bool removed_blockfile{fs::remove(m_block_file_seq.FileName(pos), ec)};
827
0
        const bool removed_undofile{fs::remove(m_undo_file_seq.FileName(pos), ec)};
828
0
        if (removed_blockfile || removed_undofile) {
  Branch (828:13): [True: 0, False: 0]
  Branch (828:34): [True: 0, False: 0]
829
0
            LogDebug(BCLog::BLOCKSTORAGE, "Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
830
0
        }
831
0
    }
832
0
}
833
834
AutoFile BlockManager::OpenBlockFile(const FlatFilePos& pos, bool fReadOnly) const
835
149k
{
836
149k
    return AutoFile{m_block_file_seq.Open(pos, fReadOnly), m_obfuscation};
837
149k
}
838
839
/** Open an undo file (rev?????.dat) */
840
AutoFile BlockManager::OpenUndoFile(const FlatFilePos& pos, bool fReadOnly) const
841
98.0k
{
842
98.0k
    return AutoFile{m_undo_file_seq.Open(pos, fReadOnly), m_obfuscation};
843
98.0k
}
844
845
fs::path BlockManager::GetBlockPosFilename(const FlatFilePos& pos) const
846
0
{
847
0
    return m_block_file_seq.FileName(pos);
848
0
}
849
850
FlatFilePos BlockManager::FindNextBlockPos(unsigned int nAddSize, unsigned int nHeight, uint64_t nTime)
851
70.9k
{
852
70.9k
    AssertLockHeld(::cs_main);
853
70.9k
    const BlockfileType chain_type = BlockfileTypeForHeight(nHeight);
854
855
70.9k
    if (!m_blockfile_cursors[chain_type]) {
  Branch (855:9): [True: 0, False: 70.9k]
856
        // If a snapshot is loaded during runtime, we may not have initialized this cursor yet.
857
0
        assert(chain_type == BlockfileType::ASSUMED);
  Branch (857:9): [True: 0, False: 0]
858
0
        const auto new_cursor = BlockfileCursor{this->MaxBlockfileNum() + 1};
859
0
        m_blockfile_cursors[chain_type] = new_cursor;
860
0
        LogDebug(BCLog::BLOCKSTORAGE, "[%s] initializing blockfile cursor to %s\n", chain_type, new_cursor);
861
0
    }
862
70.9k
    const int last_blockfile = m_blockfile_cursors[chain_type]->file_num;
863
864
70.9k
    int nFile = last_blockfile;
865
70.9k
    if (static_cast<int>(m_blockfile_info.size()) <= nFile) {
  Branch (865:9): [True: 0, False: 70.9k]
866
0
        m_blockfile_info.resize(nFile + 1);
867
0
    }
868
869
70.9k
    bool finalize_undo = false;
870
70.9k
    unsigned int max_blockfile_size{MAX_BLOCKFILE_SIZE};
871
    // Use smaller blockfiles in test-only -fastprune mode - but avoid
872
    // the possibility of having a block not fit into the block file.
873
70.9k
    if (m_opts.fast_prune) {
  Branch (873:9): [True: 0, False: 70.9k]
874
0
        max_blockfile_size = 0x10000; // 64kiB
875
0
        if (nAddSize >= max_blockfile_size) {
  Branch (875:13): [True: 0, False: 0]
876
            // dynamically adjust the blockfile size to be larger than the added size
877
0
            max_blockfile_size = nAddSize + 1;
878
0
        }
879
0
    }
880
70.9k
    assert(nAddSize < max_blockfile_size);
  Branch (880:5): [True: 70.9k, False: 0]
881
882
70.9k
    while (m_blockfile_info[nFile].nSize + nAddSize >= max_blockfile_size) {
  Branch (882:12): [True: 0, False: 70.9k]
883
        // when the undo file is keeping up with the block file, we want to flush it explicitly
884
        // when it is lagging behind (more blocks arrive than are being connected), we let the
885
        // undo block write case handle it
886
0
        finalize_undo = (static_cast<int>(m_blockfile_info[nFile].nHeightLast) ==
887
0
                         Assert(m_blockfile_cursors[chain_type])->undo_height);
888
889
        // Try the next unclaimed blockfile number
890
0
        nFile = this->MaxBlockfileNum() + 1;
891
        // Set to increment MaxBlockfileNum() for next iteration
892
0
        m_blockfile_cursors[chain_type] = BlockfileCursor{nFile};
893
894
0
        if (static_cast<int>(m_blockfile_info.size()) <= nFile) {
  Branch (894:13): [True: 0, False: 0]
895
0
            m_blockfile_info.resize(nFile + 1);
896
0
        }
897
0
    }
898
70.9k
    FlatFilePos pos;
899
70.9k
    pos.nFile = nFile;
900
70.9k
    pos.nPos = m_blockfile_info[nFile].nSize;
901
902
70.9k
    if (nFile != last_blockfile) {
  Branch (902:9): [True: 0, False: 70.9k]
903
0
        LogDebug(BCLog::BLOCKSTORAGE, "Leaving block file %i: %s (onto %i) (height %i)\n",
904
0
                 last_blockfile, m_blockfile_info[last_blockfile].ToString(), nFile, nHeight);
905
906
        // Do not propagate the return code. The flush concerns a previous block
907
        // and undo file that has already been written to. If a flush fails
908
        // here, and we crash, there is no expected additional block data
909
        // inconsistency arising from the flush failure here. However, the undo
910
        // data may be inconsistent after a crash if the flush is called during
911
        // a reindex. A flush error might also leave some of the data files
912
        // untrimmed.
913
0
        if (!FlushBlockFile(last_blockfile, /*fFinalize=*/true, finalize_undo)) {
  Branch (913:13): [True: 0, False: 0]
914
0
            LogWarning(
915
0
                          "Failed to flush previous block file %05i (finalize=1, finalize_undo=%i) before opening new block file %05i\n",
916
0
                          last_blockfile, finalize_undo, nFile);
917
0
        }
918
        // No undo data yet in the new file, so reset our undo-height tracking.
919
0
        m_blockfile_cursors[chain_type] = BlockfileCursor{nFile};
920
0
    }
921
922
70.9k
    m_blockfile_info[nFile].AddBlock(nHeight, nTime);
923
70.9k
    m_blockfile_info[nFile].nSize += nAddSize;
924
925
70.9k
    bool out_of_space;
926
70.9k
    size_t bytes_allocated = m_block_file_seq.Allocate(pos, nAddSize, out_of_space);
927
70.9k
    if (out_of_space) {
  Branch (927:9): [True: 0, False: 70.9k]
928
0
        m_opts.notifications.fatalError(_("Disk space is too low!"));
929
0
        return {};
930
0
    }
931
70.9k
    if (bytes_allocated != 0 && IsPruneMode()) {
  Branch (931:9): [True: 27, False: 70.9k]
  Branch (931:33): [True: 0, False: 27]
932
0
        m_check_for_pruning = true;
933
0
    }
934
935
70.9k
    m_dirty_fileinfo.insert(nFile);
936
70.9k
    return pos;
937
70.9k
}
938
939
void BlockManager::UpdateBlockInfo(const CBlock& block, unsigned int nHeight, const FlatFilePos& pos)
940
0
{
941
0
    AssertLockHeld(::cs_main);
942
    // Update the cursor so it points to the last file.
943
0
    const BlockfileType chain_type{BlockfileTypeForHeight(nHeight)};
944
0
    auto& cursor{m_blockfile_cursors[chain_type]};
945
0
    if (!cursor || cursor->file_num < pos.nFile) {
  Branch (945:9): [True: 0, False: 0]
  Branch (945:20): [True: 0, False: 0]
946
0
        m_blockfile_cursors[chain_type] = BlockfileCursor{pos.nFile};
947
0
    }
948
949
    // Update the file information with the current block.
950
0
    const unsigned int added_size = ::GetSerializeSize(TX_WITH_WITNESS(block));
951
0
    const int nFile = pos.nFile;
952
0
    if (static_cast<int>(m_blockfile_info.size()) <= nFile) {
  Branch (952:9): [True: 0, False: 0]
953
0
        m_blockfile_info.resize(nFile + 1);
954
0
    }
955
0
    m_blockfile_info[nFile].AddBlock(nHeight, block.GetBlockTime());
956
0
    m_blockfile_info[nFile].nSize = std::max(pos.nPos + added_size, m_blockfile_info[nFile].nSize);
957
0
    m_dirty_fileinfo.insert(nFile);
958
0
}
959
960
bool BlockManager::FindUndoPos(BlockValidationState& state, int nFile, FlatFilePos& pos, unsigned int nAddSize)
961
33.5k
{
962
33.5k
    AssertLockHeld(::cs_main);
963
33.5k
    pos.nFile = nFile;
964
965
33.5k
    pos.nPos = m_blockfile_info[nFile].nUndoSize;
966
33.5k
    m_blockfile_info[nFile].nUndoSize += nAddSize;
967
33.5k
    m_dirty_fileinfo.insert(nFile);
968
969
33.5k
    bool out_of_space;
970
33.5k
    size_t bytes_allocated = m_undo_file_seq.Allocate(pos, nAddSize, out_of_space);
971
33.5k
    if (out_of_space) {
  Branch (971:9): [True: 0, False: 33.5k]
972
0
        return FatalError(m_opts.notifications, state, _("Disk space is too low!"));
973
0
    }
974
33.5k
    if (bytes_allocated != 0 && IsPruneMode()) {
  Branch (974:9): [True: 0, False: 33.5k]
  Branch (974:33): [True: 0, False: 0]
975
0
        m_check_for_pruning = true;
976
0
    }
977
978
33.5k
    return true;
979
33.5k
}
980
981
bool BlockManager::WriteBlockUndo(const CBlockUndo& blockundo, BlockValidationState& state, CBlockIndex& block)
982
42.9k
{
983
42.9k
    AssertLockHeld(::cs_main);
984
42.9k
    const BlockfileType type = BlockfileTypeForHeight(block.nHeight);
985
42.9k
    auto& cursor = *Assert(m_blockfile_cursors[type]);
986
987
    // Write undo information to disk
988
42.9k
    if (block.GetUndoPos().IsNull()) {
  Branch (988:9): [True: 33.5k, False: 9.41k]
989
33.5k
        FlatFilePos pos;
990
33.5k
        const auto blockundo_size{static_cast<uint32_t>(GetSerializeSize(blockundo))};
991
33.5k
        if (!FindUndoPos(state, block.nFile, pos, blockundo_size + UNDO_DATA_DISK_OVERHEAD)) {
  Branch (991:13): [True: 0, False: 33.5k]
992
0
            LogError("FindUndoPos failed for %s while writing block undo", pos.ToString());
993
0
            return false;
994
0
        }
995
996
        // Open history file to append
997
33.5k
        AutoFile file{OpenUndoFile(pos)};
998
33.5k
        if (file.IsNull()) {
  Branch (998:13): [True: 0, False: 33.5k]
999
0
            LogError("OpenUndoFile failed for %s while writing block undo", pos.ToString());
1000
0
            return FatalError(m_opts.notifications, state, _("Failed to write undo data."));
1001
0
        }
1002
33.5k
        {
1003
33.5k
            BufferedWriter fileout{file};
1004
1005
            // Write index header
1006
33.5k
            fileout << GetParams().MessageStart() << blockundo_size;
1007
33.5k
            pos.nPos += STORAGE_HEADER_BYTES;
1008
33.5k
            {
1009
                // Calculate checksum
1010
33.5k
                HashWriter hasher{};
1011
33.5k
                hasher << block.pprev->GetBlockHash() << blockundo;
1012
                // Write undo data & checksum
1013
33.5k
                fileout << blockundo << hasher.GetHash();
1014
33.5k
            }
1015
            // BufferedWriter will flush pending data to file when fileout goes out of scope.
1016
33.5k
        }
1017
1018
        // Make sure that the file is closed before we call `FlushUndoFile`.
1019
33.5k
        if (file.fclose() != 0) {
  Branch (1019:13): [True: 0, False: 33.5k]
1020
0
            LogError("Failed to close block undo file %s: %s", pos.ToString(), SysErrorString(errno));
1021
0
            return FatalError(m_opts.notifications, state, _("Failed to close block undo file."));
1022
0
        }
1023
1024
        // rev files are written in block height order, whereas blk files are written as blocks come in (often out of order)
1025
        // we want to flush the rev (undo) file once we've written the last block, which is indicated by the last height
1026
        // in the block file info as below; note that this does not catch the case where the undo writes are keeping up
1027
        // with the block writes (usually when a synced up node is getting newly mined blocks) -- this case is caught in
1028
        // the FindNextBlockPos function
1029
33.5k
        if (pos.nFile < cursor.file_num && static_cast<uint32_t>(block.nHeight) == m_blockfile_info[pos.nFile].nHeightLast) {
  Branch (1029:13): [True: 0, False: 33.5k]
  Branch (1029:44): [True: 0, False: 0]
1030
            // Do not propagate the return code, a failed flush here should not
1031
            // be an indication for a failed write. If it were propagated here,
1032
            // the caller would assume the undo data not to be written, when in
1033
            // fact it is. Note though, that a failed flush might leave the data
1034
            // file untrimmed.
1035
0
            if (!FlushUndoFile(pos.nFile, true)) {
  Branch (1035:17): [True: 0, False: 0]
1036
0
                LogWarning("Failed to flush undo file %05i\n", pos.nFile);
1037
0
            }
1038
33.5k
        } else if (pos.nFile == cursor.file_num && block.nHeight > cursor.undo_height) {
  Branch (1038:20): [True: 33.5k, False: 18.4E]
  Branch (1038:52): [True: 21.4k, False: 12.0k]
1039
21.4k
            cursor.undo_height = block.nHeight;
1040
21.4k
        }
1041
        // update nUndoPos in block index
1042
33.5k
        block.nUndoPos = pos.nPos;
1043
33.5k
        block.nStatus |= BLOCK_HAVE_UNDO;
1044
33.5k
        m_dirty_blockindex.insert(&block);
1045
33.5k
    }
1046
1047
42.9k
    return true;
1048
42.9k
}
1049
1050
bool BlockManager::ReadBlock(CBlock& block, const FlatFilePos& pos, const std::optional<uint256>& expected_hash) const
1051
78.4k
{
1052
78.4k
    block.SetNull();
1053
1054
    // Open history file to read
1055
78.4k
    const auto block_data{ReadRawBlock(pos)};
1056
78.4k
    if (!block_data) {
  Branch (1056:9): [True: 0, False: 78.4k]
1057
0
        return false;
1058
0
    }
1059
1060
78.4k
    try {
1061
        // Read block
1062
78.4k
        SpanReader{*block_data} >> TX_WITH_WITNESS(block);
1063
78.4k
    } catch (const std::exception& e) {
1064
0
        LogError("Deserialize or I/O error - %s at %s while reading block", e.what(), pos.ToString());
1065
0
        return false;
1066
0
    }
1067
1068
78.4k
    const auto block_hash{block.GetHash()};
1069
1070
    // Check the header
1071
78.4k
    if (!CheckProofOfWork(block_hash, block.nBits, GetConsensus())) {
  Branch (1071:9): [True: 0, False: 78.4k]
1072
0
        LogError("Errors in block header at %s while reading block", pos.ToString());
1073
0
        return false;
1074
0
    }
1075
1076
    // Signet only: check block solution
1077
78.4k
    if (GetConsensus().signet_blocks && !CheckSignetBlockSolution(block, GetConsensus())) {
  Branch (1077:9): [True: 0, False: 78.4k]
  Branch (1077:41): [True: 0, False: 0]
1078
0
        LogError("Errors in block solution at %s while reading block", pos.ToString());
1079
0
        return false;
1080
0
    }
1081
1082
78.4k
    if (expected_hash && block_hash != *expected_hash) {
  Branch (1082:9): [True: 78.4k, False: 0]
  Branch (1082:26): [True: 0, False: 78.4k]
1083
0
        LogError("GetHash() doesn't match index at %s while reading block (%s != %s)",
1084
0
                 pos.ToString(), block_hash.ToString(), expected_hash->ToString());
1085
0
        return false;
1086
0
    }
1087
1088
78.4k
    return true;
1089
78.4k
}
1090
1091
bool BlockManager::ReadBlock(CBlock& block, const CBlockIndex& index) const
1092
63.4k
{
1093
63.4k
    const FlatFilePos block_pos{WITH_LOCK(cs_main, return index.GetBlockPos())};
1094
63.4k
    return ReadBlock(block, block_pos, index.GetBlockHash());
1095
63.4k
}
1096
1097
BlockManager::ReadRawBlockResult BlockManager::ReadRawBlock(const FlatFilePos& pos, std::optional<std::pair<size_t, size_t>> block_part) const
1098
78.7k
{
1099
78.7k
    if (pos.nPos < STORAGE_HEADER_BYTES) {
  Branch (1099:9): [True: 0, False: 78.7k]
1100
        // If nPos is less than STORAGE_HEADER_BYTES, we can't read the header that precedes the block data
1101
        // This would cause an unsigned integer underflow when trying to position the file cursor
1102
        // This can happen after pruning or default constructed positions
1103
0
        LogError("Failed for %s while reading raw block storage header", pos.ToString());
1104
0
        return util::Unexpected{ReadRawError::IO};
1105
0
    }
1106
78.7k
    AutoFile filein{OpenBlockFile({pos.nFile, pos.nPos - STORAGE_HEADER_BYTES}, /*fReadOnly=*/true)};
1107
78.7k
    if (filein.IsNull()) {
  Branch (1107:9): [True: 0, False: 78.7k]
1108
0
        LogError("OpenBlockFile failed for %s while reading raw block", pos.ToString());
1109
0
        return util::Unexpected{ReadRawError::IO};
1110
0
    }
1111
1112
78.7k
    try {
1113
78.7k
        MessageStartChars blk_start;
1114
78.7k
        unsigned int blk_size;
1115
1116
78.7k
        filein >> blk_start >> blk_size;
1117
1118
78.7k
        if (blk_start != GetParams().MessageStart()) {
  Branch (1118:13): [True: 0, False: 78.7k]
1119
0
            LogError("Block magic mismatch for %s: %s versus expected %s while reading raw block",
1120
0
                pos.ToString(), HexStr(blk_start), HexStr(GetParams().MessageStart()));
1121
0
            return util::Unexpected{ReadRawError::IO};
1122
0
        }
1123
1124
78.7k
        if (blk_size > MAX_SIZE) {
  Branch (1124:13): [True: 0, False: 78.7k]
1125
0
            LogError("Block data is larger than maximum deserialization size for %s: %s versus %s while reading raw block",
1126
0
                pos.ToString(), blk_size, MAX_SIZE);
1127
0
            return util::Unexpected{ReadRawError::IO};
1128
0
        }
1129
1130
78.7k
        if (block_part) {
  Branch (1130:13): [True: 0, False: 78.7k]
1131
0
            const auto [offset, size]{*block_part};
1132
0
            if (size == 0 || SaturatingAdd(offset, size) > blk_size) {
  Branch (1132:17): [True: 0, False: 0]
  Branch (1132:30): [True: 0, False: 0]
1133
0
                return util::Unexpected{ReadRawError::BadPartRange}; // Avoid logging - offset/size come from untrusted REST input
1134
0
            }
1135
0
            filein.seek(offset, SEEK_CUR);
1136
0
            blk_size = size;
1137
0
        }
1138
1139
78.7k
        std::vector<std::byte> data(blk_size); // Zeroing of memory is intentional here
1140
78.7k
        filein.read(data);
1141
78.7k
        return data;
1142
78.7k
    } catch (const std::exception& e) {
1143
0
        LogError("Read from block file failed: %s for %s while reading raw block", e.what(), pos.ToString());
1144
0
        return util::Unexpected{ReadRawError::IO};
1145
0
    }
1146
78.7k
}
1147
1148
FlatFilePos BlockManager::WriteBlock(const CBlock& block, int nHeight)
1149
70.9k
{
1150
70.9k
    AssertLockHeld(::cs_main);
1151
70.9k
    const unsigned int block_size{static_cast<unsigned int>(GetSerializeSize(TX_WITH_WITNESS(block)))};
1152
70.9k
    FlatFilePos pos{FindNextBlockPos(block_size + STORAGE_HEADER_BYTES, nHeight, block.GetBlockTime())};
1153
70.9k
    if (pos.IsNull()) {
  Branch (1153:9): [True: 0, False: 70.9k]
1154
0
        LogError("FindNextBlockPos failed for %s while writing block", pos.ToString());
1155
0
        return FlatFilePos();
1156
0
    }
1157
70.9k
    AutoFile file{OpenBlockFile(pos, /*fReadOnly=*/false)};
1158
70.9k
    if (file.IsNull()) {
  Branch (1158:9): [True: 0, False: 70.9k]
1159
0
        LogError("OpenBlockFile failed for %s while writing block", pos.ToString());
1160
0
        m_opts.notifications.fatalError(_("Failed to write block."));
1161
0
        return FlatFilePos();
1162
0
    }
1163
70.9k
    {
1164
70.9k
        BufferedWriter fileout{file};
1165
1166
        // Write index header
1167
70.9k
        fileout << GetParams().MessageStart() << block_size;
1168
70.9k
        pos.nPos += STORAGE_HEADER_BYTES;
1169
        // Write block
1170
70.9k
        fileout << TX_WITH_WITNESS(block);
1171
70.9k
    }
1172
1173
70.9k
    if (file.fclose() != 0) {
  Branch (1173:9): [True: 0, False: 70.9k]
1174
0
        LogError("Failed to close block file %s: %s", pos.ToString(), SysErrorString(errno));
1175
0
        m_opts.notifications.fatalError(_("Failed to close file when writing block."));
1176
0
        return FlatFilePos();
1177
0
    }
1178
1179
70.9k
    return pos;
1180
70.9k
}
1181
1182
static auto InitBlocksdirXorKey(const BlockManager::Options& opts)
1183
27
{
1184
    // Bytes are serialized without length indicator, so this is also the exact
1185
    // size of the XOR-key file.
1186
27
    std::array<std::byte, Obfuscation::KEY_SIZE> obfuscation{};
1187
1188
    // Consider this to be the first run if the blocksdir contains only hidden
1189
    // files (those which start with a .). Checking for a fully-empty dir would
1190
    // be too aggressive as a .lock file may have already been written.
1191
27
    bool first_run = true;
1192
27
    for (const auto& entry : fs::directory_iterator(opts.blocks_dir)) {
  Branch (1192:28): [True: 27, False: 27]
1193
27
        const std::string path = fs::PathToString(entry.path().filename());
1194
27
        if (!entry.is_regular_file() || !path.starts_with('.')) {
  Branch (1194:13): [True: 0, False: 27]
  Branch (1194:41): [True: 0, False: 27]
1195
0
            first_run = false;
1196
0
            break;
1197
0
        }
1198
27
    }
1199
1200
27
    if (opts.use_xor && first_run) {
  Branch (1200:9): [True: 27, False: 0]
  Branch (1200:25): [True: 27, False: 0]
1201
        // Only use random fresh key when the boolean option is set and on the
1202
        // very first start of the program.
1203
27
        FastRandomContext{}.fillrand(obfuscation);
1204
27
    }
1205
1206
27
    const fs::path xor_key_path{opts.blocks_dir / "xor.dat"};
1207
27
    if (fs::exists(xor_key_path)) {
  Branch (1207:9): [True: 0, False: 27]
1208
        // A pre-existing xor key file has priority.
1209
0
        AutoFile xor_key_file{fsbridge::fopen(xor_key_path, "rb")};
1210
0
        xor_key_file >> obfuscation;
1211
27
    } else {
1212
        // Create initial or missing xor key file
1213
27
        AutoFile xor_key_file{fsbridge::fopen(xor_key_path,
1214
#ifdef __MINGW64__
1215
            "wb" // Temporary workaround for https://github.com/bitcoin/bitcoin/issues/30210
1216
#else
1217
27
            "wbx"
1218
27
#endif
1219
27
        )};
1220
27
        xor_key_file << obfuscation;
1221
27
        if (xor_key_file.fclose() != 0) {
  Branch (1221:13): [True: 0, False: 27]
1222
0
            throw std::runtime_error{strprintf("Error closing XOR key file %s: %s",
1223
0
                                               fs::PathToString(xor_key_path),
1224
0
                                               SysErrorString(errno))};
1225
0
        }
1226
27
    }
1227
    // If the user disabled the key, it must be zero.
1228
27
    if (!opts.use_xor && obfuscation != decltype(obfuscation){}) {
  Branch (1228:9): [True: 0, False: 27]
  Branch (1228:9): [True: 0, False: 27]
  Branch (1228:26): [True: 0, False: 0]
1229
0
        throw std::runtime_error{
1230
0
            strprintf("The blocksdir XOR-key can not be disabled when a random key was already stored! "
1231
0
                      "Stored key: '%s', stored path: '%s'.",
1232
0
                      HexStr(obfuscation), fs::PathToString(xor_key_path)),
1233
0
        };
1234
0
    }
1235
27
    LogInfo("Using obfuscation key for blocksdir *.dat files (%s): '%s'\n", fs::PathToString(opts.blocks_dir), HexStr(obfuscation));
1236
27
    return Obfuscation{obfuscation};
1237
27
}
1238
1239
BlockManager::BlockManager(const util::SignalInterrupt& interrupt, Options opts)
1240
27
    : m_prune_mode{opts.prune_target > 0},
1241
27
      m_obfuscation{InitBlocksdirXorKey(opts)},
1242
27
      m_opts{std::move(opts)},
1243
27
      m_block_file_seq{FlatFileSeq{m_opts.blocks_dir, "blk", m_opts.fast_prune ? 0x4000 /* 16kB */ : BLOCKFILE_CHUNK_SIZE}},
  Branch (1243:62): [True: 0, False: 27]
1244
27
      m_undo_file_seq{FlatFileSeq{m_opts.blocks_dir, "rev", UNDOFILE_CHUNK_SIZE}},
1245
27
      m_interrupt{interrupt}
1246
27
{
1247
27
    m_block_tree_db = std::make_unique<BlockTreeDB>(m_opts.block_tree_db_params);
1248
1249
27
    if (m_opts.block_tree_db_params.wipe_data) {
  Branch (1249:9): [True: 0, False: 27]
1250
0
        m_block_tree_db->WriteReindexing(true);
1251
0
        m_blockfiles_indexed = false;
1252
        // If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1253
0
        if (m_prune_mode) {
  Branch (1253:13): [True: 0, False: 0]
1254
0
            CleanupBlockRevFiles();
1255
0
        }
1256
0
    }
1257
27
}
1258
1259
class ImportingNow
1260
{
1261
    std::atomic<bool>& m_importing;
1262
1263
public:
1264
27
    ImportingNow(std::atomic<bool>& importing) : m_importing{importing}
1265
27
    {
1266
27
        assert(m_importing == false);
  Branch (1266:9): [True: 27, False: 0]
1267
27
        m_importing = true;
1268
27
    }
1269
    ~ImportingNow()
1270
27
    {
1271
27
        assert(m_importing == true);
  Branch (1271:9): [True: 27, False: 0]
1272
27
        m_importing = false;
1273
27
    }
1274
};
1275
1276
void ImportBlocks(ChainstateManager& chainman, std::span<const fs::path> import_paths)
1277
27
{
1278
27
    ImportingNow imp{chainman.m_blockman.m_importing};
1279
1280
    // -reindex
1281
27
    if (!chainman.m_blockman.m_blockfiles_indexed) {
  Branch (1281:9): [True: 0, False: 27]
1282
0
        int total_files{0};
1283
0
        while (fs::exists(chainman.m_blockman.GetBlockPosFilename(FlatFilePos(total_files, 0)))) {
  Branch (1283:16): [True: 0, False: 0]
1284
0
            total_files++;
1285
0
        }
1286
1287
        // Map of disk positions for blocks with unknown parent (only used for reindex);
1288
        // parent hash -> child disk position, multiple children can have the same parent.
1289
0
        std::multimap<uint256, FlatFilePos> blocks_with_unknown_parent;
1290
1291
0
        for (int nFile{0}; nFile < total_files; ++nFile) {
  Branch (1291:28): [True: 0, False: 0]
1292
0
            FlatFilePos pos(nFile, 0);
1293
0
            AutoFile file{chainman.m_blockman.OpenBlockFile(pos, /*fReadOnly=*/true)};
1294
0
            if (file.IsNull()) {
  Branch (1294:17): [True: 0, False: 0]
1295
0
                break; // This error is logged in OpenBlockFile
1296
0
            }
1297
0
            LogInfo("Reindexing block file blk%05u.dat (%d%% complete)...", (unsigned int)nFile, nFile * 100 / total_files);
1298
0
            chainman.LoadExternalBlockFile(file, &pos, &blocks_with_unknown_parent);
1299
0
            if (chainman.m_interrupt) {
  Branch (1299:17): [True: 0, False: 0]
1300
0
                LogInfo("Interrupt requested. Exit reindexing.");
1301
0
                return;
1302
0
            }
1303
0
        }
1304
0
        WITH_LOCK(::cs_main, chainman.m_blockman.m_block_tree_db->WriteReindexing(false));
1305
0
        chainman.m_blockman.m_blockfiles_indexed = true;
1306
0
        LogInfo("Reindexing finished");
1307
        // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
1308
0
        chainman.ActiveChainstate().LoadGenesisBlock();
1309
0
    }
1310
1311
    // -loadblock=
1312
27
    for (const fs::path& path : import_paths) {
  Branch (1312:31): [True: 0, False: 27]
1313
0
        AutoFile file{fsbridge::fopen(path, "rb")};
1314
0
        if (!file.IsNull()) {
  Branch (1314:13): [True: 0, False: 0]
1315
0
            LogInfo("Importing blocks file %s...", fs::PathToString(path));
1316
0
            chainman.LoadExternalBlockFile(file);
1317
0
            if (chainman.m_interrupt) {
  Branch (1317:17): [True: 0, False: 0]
1318
0
                LogInfo("Interrupt requested. Exit block importing.");
1319
0
                return;
1320
0
            }
1321
0
        } else {
1322
0
            LogWarning("Could not open blocks file %s", fs::PathToString(path));
1323
0
        }
1324
0
    }
1325
1326
    // scan for better chains in the block chain database, that are not yet connected in the active best chain
1327
27
    if (auto result = chainman.ActivateBestChains(); !result) {
  Branch (1327:54): [True: 0, False: 27]
1328
0
        chainman.GetNotifications().fatalError(util::ErrorString(result));
1329
0
    }
1330
    // End scope of ImportingNow
1331
27
}
1332
1333
0
std::ostream& operator<<(std::ostream& os, const BlockfileType& type) {
1334
0
    switch(type) {
1335
0
        case BlockfileType::NORMAL: os << "normal"; break;
  Branch (1335:9): [True: 0, False: 0]
1336
0
        case BlockfileType::ASSUMED: os << "assumed"; break;
  Branch (1336:9): [True: 0, False: 0]
1337
0
        default: os.setstate(std::ios_base::failbit);
  Branch (1337:9): [True: 0, False: 0]
1338
0
    }
1339
0
    return os;
1340
0
}
1341
1342
0
std::ostream& operator<<(std::ostream& os, const BlockfileCursor& cursor) {
1343
0
    os << strprintf("BlockfileCursor(file_num=%d, undo_height=%d)", cursor.file_num, cursor.undo_height);
1344
0
    return os;
1345
0
}
1346
} // namespace node