Bitcoin Core Fuzz Coverage Report

Coverage Report

Created: 2026-03-24 13:57

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