Coverage Report

Created: 2026-04-29 19:21

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