Coverage Report

Created: 2026-06-16 16:41

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