Coverage Report

Created: 2025-06-10 13:21

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