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