Coverage Report

Created: 2026-06-09 19:51

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