Bitcoin ABC 0.33.6
P2P Digital Currency
blockstorage.cpp
Go to the documentation of this file.
1// Copyright (c) 2011-2022 The Bitcoin 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
9#include <chain.h>
10#include <common/system.h>
11#include <config.h>
13#include <flatfile.h>
14#include <hash.h>
15#include <kernel/chain.h>
16#include <kernel/chainparams.h>
17#include <logging.h>
18#include <pow/pow.h>
19#include <reverse_iterator.h>
20#include <streams.h>
21#include <undo.h>
22#include <util/batchpriority.h>
23#include <util/fs.h>
25#include <validation.h>
26
27#include <map>
28#include <unordered_map>
29
30namespace node {
31std::atomic_bool fReindex(false);
32
33std::vector<CBlockIndex *> BlockManager::GetAllBlockIndices() {
35 std::vector<CBlockIndex *> rv;
36 rv.reserve(m_block_index.size());
37 for (auto &[_, block_index] : m_block_index) {
38 rv.push_back(&block_index);
39 }
40 return rv;
41}
42
45 BlockMap::iterator it = m_block_index.find(hash);
46 return it == m_block_index.end() ? nullptr : &it->second;
47}
48
51 BlockMap::const_iterator it = m_block_index.find(hash);
52 return it == m_block_index.end() ? nullptr : &it->second;
53}
54
56 CBlockIndex *&best_header) {
58
59 const auto [mi, inserted] =
60 m_block_index.try_emplace(block.GetHash(), block);
61 if (!inserted) {
62 return &mi->second;
63 }
64 CBlockIndex *pindexNew = &(*mi).second;
65
66 // We assign the sequence id to blocks only when the full data is available,
67 // to avoid miners withholding blocks but broadcasting headers, to get a
68 // competitive advantage.
69 pindexNew->nSequenceId = 0;
70
71 pindexNew->phashBlock = &((*mi).first);
72 BlockMap::iterator miPrev = m_block_index.find(block.hashPrevBlock);
73 if (miPrev != m_block_index.end()) {
74 pindexNew->pprev = &(*miPrev).second;
75 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
76 pindexNew->BuildSkip();
77 }
78 pindexNew->nTimeReceived = GetTime();
79 pindexNew->nTimeMax =
80 (pindexNew->pprev
81 ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime)
82 : pindexNew->nTime);
83 pindexNew->nChainWork =
84 (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) +
85 GetBlockProof(*pindexNew);
87 if (best_header == nullptr ||
88 best_header->nChainWork < pindexNew->nChainWork) {
89 best_header = pindexNew;
90 }
91
92 m_dirty_blockindex.insert(pindexNew);
93 return pindexNew;
94}
95
96void BlockManager::PruneOneBlockFile(const int fileNumber) {
99
100 for (auto &entry : m_block_index) {
101 CBlockIndex *pindex = &entry.second;
102 if (pindex->nFile == fileNumber) {
103 pindex->nStatus = pindex->nStatus.withData(false).withUndo(false);
104 pindex->nFile = 0;
105 pindex->nDataPos = 0;
106 pindex->nUndoPos = 0;
107 m_dirty_blockindex.insert(pindex);
108
109 // Prune from m_blocks_unlinked -- any block we prune would have
110 // to be downloaded again in order to consider its chain, at which
111 // point it would be considered as a candidate for
112 // m_blocks_unlinked or setBlockIndexCandidates.
113 auto range = m_blocks_unlinked.equal_range(pindex->pprev);
114 while (range.first != range.second) {
115 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it =
116 range.first;
117 range.first++;
118 if (_it->second == pindex) {
119 m_blocks_unlinked.erase(_it);
120 }
121 }
122 }
123 }
124
125 m_blockfile_info[fileNumber].SetNull();
126 m_dirty_fileinfo.insert(fileNumber);
127}
128
129void BlockManager::FindFilesToPruneManual(std::set<int> &setFilesToPrune,
130 int nManualPruneHeight,
131 const Chainstate &chain,
132 ChainstateManager &chainman) {
133 assert(IsPruneMode() && nManualPruneHeight > 0);
134
136 if (chain.m_chain.Height() < 0) {
137 return;
138 }
139
140 // last block to prune is the lesser of (user-specified height,
141 // MIN_BLOCKS_TO_KEEP from the tip)
142 const auto [min_block_to_prune, last_block_can_prune] =
143 chainman.GetPruneRange(chain, nManualPruneHeight);
144 int count = 0;
145 for (int fileNumber = 0; fileNumber < this->MaxBlockfileNum();
146 fileNumber++) {
147 const auto &fileinfo = m_blockfile_info[fileNumber];
148 if (fileinfo.nSize == 0 ||
149 fileinfo.nHeightLast > (unsigned)last_block_can_prune ||
150 fileinfo.nHeightFirst < (unsigned)min_block_to_prune) {
151 continue;
152 }
153
154 PruneOneBlockFile(fileNumber);
155 setFilesToPrune.insert(fileNumber);
156 count++;
157 }
158 LogPrintf("[%s] Prune (Manual): prune_height=%d removed %d blk/rev pairs\n",
159 chain.GetRole(), last_block_can_prune, count);
160}
161
162void BlockManager::FindFilesToPrune(std::set<int> &setFilesToPrune,
163 int last_prune, const Chainstate &chain,
164 ChainstateManager &chainman) {
166 // Distribute our -prune budget over all chainstates.
167 const auto target = std::max(MIN_DISK_SPACE_FOR_BLOCK_FILES,
168 GetPruneTarget() / chainman.GetAll().size());
169
170 if (chain.m_chain.Height() < 0 || target == 0) {
171 return;
172 }
173 if (static_cast<uint64_t>(chain.m_chain.Height()) <=
174 chainman.GetParams().PruneAfterHeight()) {
175 return;
176 }
177
178 const auto [min_block_to_prune, last_block_can_prune] =
179 chainman.GetPruneRange(chain, last_prune);
180
181 uint64_t nCurrentUsage = CalculateCurrentUsage();
182 // We don't check to prune until after we've allocated new space for files,
183 // so we should leave a buffer under our target to account for another
184 // allocation before the next pruning.
185 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
186 uint64_t nBytesToPrune;
187 int count = 0;
188
189 if (nCurrentUsage + nBuffer >= target) {
190 // On a prune event, the chainstate DB is flushed.
191 // To avoid excessive prune events negating the benefit of high dbcache
192 // values, we should not prune too rapidly.
193 // So when pruning in IBD, increase the buffer a bit to avoid a re-prune
194 // too soon.
195 if (chainman.IsInitialBlockDownload()) {
196 // Since this is only relevant during IBD, we use a fixed 10%
197 nBuffer += target / 10;
198 }
199
200 for (int fileNumber = 0; fileNumber < this->MaxBlockfileNum();
201 fileNumber++) {
202 const auto &fileinfo = m_blockfile_info[fileNumber];
203 nBytesToPrune = fileinfo.nSize + fileinfo.nUndoSize;
204
205 if (fileinfo.nSize == 0) {
206 continue;
207 }
208
209 if (nCurrentUsage + nBuffer < target) { // are we below our target?
210 break;
211 }
212
213 // don't prune files that could have a block that's not within the
214 // allowable prune range for the chain being pruned.
215 if (fileinfo.nHeightLast > (unsigned)last_block_can_prune ||
216 fileinfo.nHeightFirst < (unsigned)min_block_to_prune) {
217 continue;
218 }
219
220 PruneOneBlockFile(fileNumber);
221 // Queue up the files for removal
222 setFilesToPrune.insert(fileNumber);
223 nCurrentUsage -= nBytesToPrune;
224 count++;
225 }
226 }
227
229 "[%s] target=%dMiB actual=%dMiB diff=%dMiB min_height=%d "
230 "max_prune_height=%d removed %d blk/rev pairs\n",
231 chain.GetRole(), target / 1024 / 1024, nCurrentUsage / 1024 / 1024,
232 (int64_t(target) - int64_t(nCurrentUsage)) / 1024 / 1024,
233 min_block_to_prune, last_block_can_prune, count);
234}
235
236void BlockManager::UpdatePruneLock(const std::string &name,
237 const PruneLockInfo &lock_info) {
239 m_prune_locks[name] = lock_info;
240}
241
244
245 if (hash.IsNull()) {
246 return nullptr;
247 }
248
249 const auto [mi, inserted] = m_block_index.try_emplace(hash);
250 CBlockIndex *pindex = &(*mi).second;
251 if (inserted) {
252 pindex->phashBlock = &((*mi).first);
253 }
254 return pindex;
255}
256
258 const std::optional<BlockHash> &snapshot_blockhash) {
260 if (!m_block_tree_db->LoadBlockIndexGuts(
261 GetConsensus(),
262 [this](const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
263 return this->InsertBlockIndex(hash);
264 },
265 m_interrupt)) {
266 return false;
267 }
268
269 if (snapshot_blockhash) {
270 const AssumeutxoData au_data =
271 *Assert(GetParams().AssumeutxoForBlockhash(*snapshot_blockhash));
272 m_snapshot_height = au_data.height;
273 CBlockIndex *base{LookupBlockIndex(*snapshot_blockhash)};
274
275 // Since nChainTx (responsible for estimated progress) isn't persisted
276 // to disk, we must bootstrap the value for assumedvalid chainstates
277 // from the hardcoded assumeutxo chainparams.
278 base->nChainTx = au_data.nChainTx;
279 LogPrintf("[snapshot] set nChainTx=%d for %s\n", au_data.nChainTx,
280 snapshot_blockhash->ToString());
281 } else {
282 // If this isn't called with a snapshot blockhash, make sure the cached
283 // snapshot height is null. This is relevant during snapshot
284 // completion, when the blockman may be loaded with a height that then
285 // needs to be cleared after the snapshot is fully validated.
286 m_snapshot_height.reset();
287 }
288
289 Assert(m_snapshot_height.has_value() == snapshot_blockhash.has_value());
290
291 // Calculate nChainWork
292 std::vector<CBlockIndex *> vSortedByHeight{GetAllBlockIndices()};
293 std::sort(vSortedByHeight.begin(), vSortedByHeight.end(),
295
296 CBlockIndex *previous_index{nullptr};
297 for (CBlockIndex *pindex : vSortedByHeight) {
298 if (m_interrupt) {
299 return false;
300 }
301 if (previous_index && pindex->nHeight > previous_index->nHeight + 1) {
302 LogError("%s: block index is non-contiguous, index of height %d "
303 "missing\n",
304 __func__, previous_index->nHeight + 1);
305 return false;
306 }
307 previous_index = pindex;
308
309 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) +
310 GetBlockProof(*pindex);
311 pindex->nTimeMax =
312 (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime)
313 : pindex->nTime);
314
315 // We can link the chain of blocks for which we've received
316 // transactions at some point, or blocks that are assumed-valid on the
317 // basis of snapshot load (see PopulateAndValidateSnapshot()).
318 // Pruned nodes may have deleted the block.
319 if (pindex->nTx > 0) {
320 const unsigned int prevNChainTx =
321 pindex->pprev ? pindex->pprev->nChainTx : 0;
322 if (m_snapshot_height && pindex->nHeight == *m_snapshot_height &&
323 pindex->GetBlockHash() == *snapshot_blockhash) {
324 // Should have been set above; don't disturb it with code below.
325 Assert(pindex->nChainTx > 0);
326 } else if (prevNChainTx == 0 && pindex->pprev) {
327 pindex->nChainTx = 0;
328 m_blocks_unlinked.insert(std::make_pair(pindex->pprev, pindex));
329 } else {
330 pindex->nChainTx = prevNChainTx + pindex->nTx;
331 }
332 }
333
334 if (!pindex->nStatus.hasFailed() && pindex->pprev &&
335 pindex->pprev->nStatus.hasFailed()) {
336 pindex->nStatus = pindex->nStatus.withFailedParent();
337 m_dirty_blockindex.insert(pindex);
338 }
339
340 if (pindex->pprev) {
341 pindex->BuildSkip();
342 }
343 }
344
345 return true;
346}
347
348void BlockManager::WriteBlockIndexDB() {
349 std::vector<std::pair<int, const CBlockFileInfo *>> vFiles;
350 vFiles.reserve(m_dirty_fileinfo.size());
351 for (int i : m_dirty_fileinfo) {
352 vFiles.push_back(std::make_pair(i, &m_blockfile_info[i]));
353 }
354
355 m_dirty_fileinfo.clear();
356
357 std::vector<const CBlockIndex *> vBlocks;
358 vBlocks.reserve(m_dirty_blockindex.size());
359 for (const CBlockIndex *cbi : m_dirty_blockindex) {
360 vBlocks.push_back(cbi);
361 }
362
363 m_dirty_blockindex.clear();
364
365 int max_blockfile =
367 m_block_tree_db->WriteBatchSync(vFiles, max_blockfile, vBlocks);
368}
369
370bool BlockManager::LoadBlockIndexDB(
371 const std::optional<BlockHash> &snapshot_blockhash) {
372 if (!LoadBlockIndex(snapshot_blockhash)) {
373 return false;
374 }
375 int max_blockfile_num{0};
376
377 // Load block file info
378 m_block_tree_db->ReadLastBlockFile(max_blockfile_num);
379 m_blockfile_info.resize(max_blockfile_num + 1);
380 LogPrintf("%s: last block file = %i\n", __func__, max_blockfile_num);
381 for (int nFile = 0; nFile <= max_blockfile_num; nFile++) {
382 m_block_tree_db->ReadBlockFileInfo(nFile, m_blockfile_info[nFile]);
383 }
384 LogPrintf("%s: last block file info: %s\n", __func__,
385 m_blockfile_info[max_blockfile_num].ToString());
386 for (int nFile = max_blockfile_num + 1; true; nFile++) {
387 CBlockFileInfo info;
388 if (m_block_tree_db->ReadBlockFileInfo(nFile, info)) {
389 m_blockfile_info.push_back(info);
390 } else {
391 break;
392 }
393 }
394
395 // Check presence of blk files
396 LogPrintf("Checking all blk files are present...\n");
397 std::set<int> setBlkDataFiles;
398 for (const auto &[_, block_index] : m_block_index) {
399 if (block_index.nStatus.hasData()) {
400 setBlkDataFiles.insert(block_index.nFile);
401 }
402 }
403
404 for (const int i : setBlkDataFiles) {
405 FlatFilePos pos(i, 0);
406 if (OpenBlockFile(pos, true).IsNull()) {
407 return false;
408 }
409 }
410
411 {
412 // Initialize the blockfile cursors.
414 for (size_t i = 0; i < m_blockfile_info.size(); ++i) {
415 const auto last_height_in_file = m_blockfile_info[i].nHeightLast;
416 m_blockfile_cursors[BlockfileTypeForHeight(last_height_in_file)] = {
417 static_cast<int>(i), 0};
418 }
419 }
420
421 // Check whether we have ever pruned block & undo files
422 m_block_tree_db->ReadFlag("prunedblockfiles", m_have_pruned);
423 if (m_have_pruned) {
424 LogPrintf(
425 "LoadBlockIndexDB(): Block files have previously been pruned\n");
426 }
427
428 // Check whether we need to continue reindexing
429 if (m_block_tree_db->IsReindexing()) {
430 fReindex = true;
431 }
432
433 return true;
434}
435
436void BlockManager::ScanAndUnlinkAlreadyPrunedFiles() {
438 int max_blockfile =
440 if (!m_have_pruned) {
441 return;
442 }
443
444 std::set<int> block_files_to_prune;
445 for (int file_number = 0; file_number < max_blockfile; file_number++) {
446 if (m_blockfile_info[file_number].nSize == 0) {
447 block_files_to_prune.insert(file_number);
448 }
449 }
450
451 UnlinkPrunedFiles(block_files_to_prune);
452}
453
454const CBlockIndex *
456 const MapCheckpoints &checkpoints = data.mapCheckpoints;
457
458 for (const MapCheckpoints::value_type &i : reverse_iterate(checkpoints)) {
459 const BlockHash &hash = i.second;
460 const CBlockIndex *pindex = LookupBlockIndex(hash);
461 if (pindex) {
462 return pindex;
463 }
464 }
465
466 return nullptr;
467}
468
469bool BlockManager::IsBlockPruned(const CBlockIndex &block) const {
471 return (m_have_pruned && !block.nStatus.hasData() && block.nTx > 0);
472}
473
474const CBlockIndex *
475BlockManager::GetFirstBlock(const CBlockIndex &upper_block,
476 std::function<bool(BlockStatus)> status_test,
477 const CBlockIndex *lower_block) const {
479 const CBlockIndex *last_block = &upper_block;
480 // 'upper_block' satisfy the test
481 assert(status_test(last_block->nStatus));
482 while (last_block->pprev && status_test(last_block->pprev->nStatus)) {
483 if (lower_block) {
484 // Return if we reached the lower_block
485 if (last_block == lower_block) {
486 return lower_block;
487 }
488 // if range was surpassed, means that 'lower_block' is not part of
489 // the 'upper_block' chain and so far this is not allowed.
490 assert(last_block->nHeight >= lower_block->nHeight);
491 }
492 last_block = last_block->pprev;
493 }
494 assert(last_block != nullptr);
495 return last_block;
496}
497
498bool BlockManager::CheckBlockDataAvailability(const CBlockIndex &upper_block,
499 const CBlockIndex &lower_block) {
500 if (!(upper_block.nStatus.hasData())) {
501 return false;
502 }
503 return GetFirstBlock(
504 upper_block,
505 [](const BlockStatus &status) { return status.hasData(); },
506 &lower_block) == &lower_block;
507}
508
509// If we're using -prune with -reindex, then delete block files that will be
510// ignored by the reindex. Since reindexing works by starting at block file 0
511// and looping until a blockfile is missing, do the same here to delete any
512// later block files after a gap. Also delete all rev files since they'll be
513// rewritten by the reindex anyway. This ensures that m_blockfile_info is in
514// sync with what's actually on disk by the time we start downloading, so that
515// pruning works correctly.
517 std::map<std::string, fs::path> mapBlockFiles;
518
519 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
520 // Remove the rev files immediately and insert the blk file paths into an
521 // ordered map keyed by block file index.
522 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for "
523 "-reindex with -prune\n");
524 for (const auto &file : fs::directory_iterator{m_opts.blocks_dir}) {
525 const std::string path = fs::PathToString(file.path().filename());
526 if (fs::is_regular_file(file) && path.length() == 12 &&
527 path.substr(8, 4) == ".dat") {
528 if (path.substr(0, 3) == "blk") {
529 mapBlockFiles[path.substr(3, 5)] = file.path();
530 } else if (path.substr(0, 3) == "rev") {
531 remove(file.path());
532 }
533 }
534 }
535
536 // Remove all block files that aren't part of a contiguous set starting at
537 // zero by walking the ordered map (keys are block file indices) by keeping
538 // a separate counter. Once we hit a gap (or if 0 doesn't exist) start
539 // removing block files.
540 int contiguousCounter = 0;
541 for (const auto &item : mapBlockFiles) {
542 if (LocaleIndependentAtoi<int>(item.first) == contiguousCounter) {
543 contiguousCounter++;
544 continue;
545 }
546 remove(item.second);
547 }
548}
549
552
553 return &m_blockfile_info.at(n);
554}
555
557 const CBlockIndex &index) const {
558 const FlatFilePos pos{WITH_LOCK(::cs_main, return index.GetUndoPos())};
559
560 if (pos.IsNull()) {
561 LogError("%s: no undo data available\n", __func__);
562 return false;
563 }
564
565 // Open history file to read
566 AutoFile filein{OpenUndoFile(pos, true)};
567 if (filein.IsNull()) {
568 LogError("OpenUndoFile failed for %s\n", pos.ToString());
569 return false;
570 }
571
572 // Read block
573 uint256 hashChecksum;
574 // Use HashVerifier as reserializing may lose data
575 // c.f. commit 80df982ab2f63e60edc1033d1ef8929c837d00c5
576 HashVerifier verifier{filein};
577 try {
578 verifier << index.pprev->GetBlockHash();
579 verifier >> blockundo;
580 filein >> hashChecksum;
581 } catch (const std::exception &e) {
582 LogError("%s: Deserialize or I/O error - %s\n", __func__, e.what());
583 return false;
584 }
585
586 // Verify checksum
587 if (hashChecksum != verifier.GetHash()) {
588 LogError("%s: Checksum mismatch\n", __func__);
589 return false;
590 }
591
592 return true;
593}
594
595bool BlockManager::FlushUndoFile(int block_file, bool finalize) {
596 FlatFilePos undo_pos_old(block_file,
597 m_blockfile_info[block_file].nUndoSize);
598 if (!UndoFileSeq().Flush(undo_pos_old, finalize)) {
600 "Flushing undo file to disk failed. This is likely the "
601 "result of an I/O error.");
602 return false;
603 }
604 return true;
605}
606
607bool BlockManager::FlushBlockFile(int blockfile_num, bool fFinalize,
608 bool finalize_undo) {
609 bool success = true;
611
612 if (m_blockfile_info.empty()) {
613 // Return if we haven't loaded any blockfiles yet. This happens during
614 // chainstate init, when we call
615 // ChainstateManager::MaybeRebalanceCaches() (which then calls
616 // FlushStateToDisk()), resulting in a call to this function before we
617 // have populated `m_blockfile_info` via LoadBlockIndexDB().
618 return true;
619 }
620 assert(static_cast<int>(m_blockfile_info.size()) > blockfile_num);
621
622 FlatFilePos block_pos_old(blockfile_num,
623 m_blockfile_info[blockfile_num].nSize);
624 if (!BlockFileSeq().Flush(block_pos_old, fFinalize)) {
626 "Flushing block file to disk failed. This is likely the "
627 "result of an I/O error.");
628 success = false;
629 }
630 // we do not always flush the undo file, as the chain tip may be lagging
631 // behind the incoming blocks,
632 // e.g. during IBD or a sync after a node going offline
633 if (!fFinalize || finalize_undo) {
634 if (!FlushUndoFile(blockfile_num, finalize_undo)) {
635 success = false;
636 }
637 }
638 return success;
639}
640
642 if (!m_snapshot_height) {
643 return BlockfileType::NORMAL;
644 }
645 return (height >= *m_snapshot_height) ? BlockfileType::ASSUMED
646 : BlockfileType::NORMAL;
647}
648
651 auto &cursor = m_blockfile_cursors[BlockfileTypeForHeight(tip_height)];
652 // If the cursor does not exist, it means an assumeutxo snapshot is loaded,
653 // but no blocks past the snapshot height have been written yet, so there
654 // is no data associated with the chainstate, and it is safe not to flush.
655 if (cursor) {
656 return FlushBlockFile(cursor->file_num, /*fFinalize=*/false,
657 /*finalize_undo=*/false);
658 }
659 // No need to log warnings in this case.
660 return true;
661}
662
665
666 uint64_t retval = 0;
667 for (const CBlockFileInfo &file : m_blockfile_info) {
668 retval += file.nSize + file.nUndoSize;
669 }
670
671 return retval;
672}
673
675 const std::set<int> &setFilesToPrune) const {
676 std::error_code error_code;
677 for (const int i : setFilesToPrune) {
678 FlatFilePos pos(i, 0);
679 const bool removed_blockfile{
680 fs::remove(BlockFileSeq().FileName(pos), error_code)};
681 const bool removed_undofile{
682 fs::remove(UndoFileSeq().FileName(pos), error_code)};
683 if (removed_blockfile || removed_undofile) {
684 LogPrint(BCLog::BLOCKSTORE, "Prune: %s deleted blk/rev (%05u)\n",
685 __func__, i);
686 }
687 }
688}
689
691 return FlatFileSeq(m_opts.blocks_dir, "blk",
692 m_opts.fast_prune ? 0x4000 /* 16kb */
694}
695
698}
699
701 bool fReadOnly) const {
702 return AutoFile{BlockFileSeq().Open(pos, fReadOnly)};
703}
704
707 bool fReadOnly) const {
708 return AutoFile{UndoFileSeq().Open(pos, fReadOnly)};
709}
710
712 return BlockFileSeq().FileName(pos);
713}
714
716 unsigned int nHeight,
717 uint64_t nTime) {
719
720 const BlockfileType chain_type = BlockfileTypeForHeight(nHeight);
721
722 if (!m_blockfile_cursors[chain_type]) {
723 // If a snapshot is loaded during runtime, we may not have initialized
724 // this cursor yet.
725 assert(chain_type == BlockfileType::ASSUMED);
726 const auto new_cursor = BlockfileCursor{this->MaxBlockfileNum() + 1};
727 m_blockfile_cursors[chain_type] = new_cursor;
729 "[%s] initializing blockfile cursor to %s\n", chain_type,
730 new_cursor);
731 }
732 const int last_blockfile = m_blockfile_cursors[chain_type]->file_num;
733
734 int nFile = last_blockfile;
735 if (static_cast<int>(m_blockfile_info.size()) <= nFile) {
736 m_blockfile_info.resize(nFile + 1);
737 }
738
739 bool finalize_undo = false;
740 unsigned int max_blockfile_size{MAX_BLOCKFILE_SIZE};
741 // Use smaller blockfiles in test-only -fastprune mode - but avoid
742 // the possibility of having a block not fit into the block file.
743 if (m_opts.fast_prune) {
744 max_blockfile_size = 0x10000; // 64kiB
745 if (nAddSize >= max_blockfile_size) {
746 // dynamically adjust the blockfile size to be larger than the
747 // added size
748 max_blockfile_size = nAddSize + 1;
749 }
750 }
751 // TODO: we will also need to dynamically adjust the blockfile size
752 // or raise MAX_BLOCKFILE_SIZE when we reach block sizes larger than
753 // 128 MiB
754 assert(nAddSize < max_blockfile_size);
755
756 while (m_blockfile_info[nFile].nSize + nAddSize >= max_blockfile_size) {
757 // when the undo file is keeping up with the block file, we want to
758 // flush it explicitly when it is lagging behind (more blocks arrive
759 // than are being connected), we let the undo block write case
760 // handle it
761 finalize_undo =
762 (static_cast<int>(m_blockfile_info[nFile].nHeightLast) ==
763 Assert(m_blockfile_cursors[chain_type])->undo_height);
764
765 // Try the next unclaimed blockfile number
766 nFile = this->MaxBlockfileNum() + 1;
767 // Set to increment MaxBlockfileNum() for next iteration
768 m_blockfile_cursors[chain_type] = BlockfileCursor{nFile};
769
770 if (static_cast<int>(m_blockfile_info.size()) <= nFile) {
771 m_blockfile_info.resize(nFile + 1);
772 }
773 }
774 FlatFilePos pos;
775 pos.nFile = nFile;
776 pos.nPos = m_blockfile_info[nFile].nSize;
777
778 if (nFile != last_blockfile) {
780 "Leaving block file %i: %s (onto %i) (height %i)\n",
781 last_blockfile, m_blockfile_info[last_blockfile].ToString(),
782 nFile, nHeight);
783
784 // Do not propagate the return code. The flush concerns a previous
785 // block and undo file that has already been written to. If a flush
786 // fails here, and we crash, there is no expected additional block
787 // data inconsistency arising from the flush failure here. However,
788 // the undo data may be inconsistent after a crash if the flush is
789 // called during a reindex. A flush error might also leave some of
790 // the data files untrimmed.
791 if (!FlushBlockFile(last_blockfile, /*fFinalize=*/true,
792 finalize_undo)) {
795 "Failed to flush previous block file %05i (finalize=1, "
796 "finalize_undo=%i) before opening new block file %05i\n",
797 last_blockfile, finalize_undo, nFile);
798 }
799 // No undo data yet in the new file, so reset our undo-height tracking.
800 m_blockfile_cursors[chain_type] = BlockfileCursor{nFile};
801 }
802
803 m_blockfile_info[nFile].AddBlock(nHeight, nTime);
804 m_blockfile_info[nFile].nSize += nAddSize;
805
806 bool out_of_space;
807 size_t bytes_allocated =
808 BlockFileSeq().Allocate(pos, nAddSize, out_of_space);
809 if (out_of_space) {
810 m_opts.notifications.fatalError("Disk space is too low!",
811 _("Disk space is too low!"));
812 return {};
813 }
814 if (bytes_allocated != 0 && IsPruneMode()) {
815 m_check_for_pruning = true;
816 }
817
818 m_dirty_fileinfo.insert(nFile);
819 return pos;
820}
821
822void BlockManager::UpdateBlockInfo(const CBlock &block, unsigned int nHeight,
823 const FlatFilePos &pos) {
825
826 // Update the cursor so it points to the last file.
828 auto &cursor{m_blockfile_cursors[chain_type]};
829 if (!cursor || cursor->file_num < pos.nFile) {
830 m_blockfile_cursors[chain_type] = BlockfileCursor{pos.nFile};
831 }
832
833 // Update the file information with the current block.
834 const unsigned int added_size = ::GetSerializeSize(block);
835 const int nFile = pos.nFile;
836 if (static_cast<int>(m_blockfile_info.size()) <= nFile) {
837 m_blockfile_info.resize(nFile + 1);
838 }
839 m_blockfile_info[nFile].AddBlock(nHeight, block.GetBlockTime());
840 m_blockfile_info[nFile].nSize =
841 std::max(pos.nPos + added_size, m_blockfile_info[nFile].nSize);
842 m_dirty_fileinfo.insert(nFile);
843}
844
846 FlatFilePos &pos, unsigned int nAddSize) {
847 pos.nFile = nFile;
848
850
851 pos.nPos = m_blockfile_info[nFile].nUndoSize;
852 m_blockfile_info[nFile].nUndoSize += nAddSize;
853 m_dirty_fileinfo.insert(nFile);
854
855 bool out_of_space;
856 size_t bytes_allocated =
857 UndoFileSeq().Allocate(pos, nAddSize, out_of_space);
858 if (out_of_space) {
859 return FatalError(m_opts.notifications, state, "Disk space is too low!",
860 _("Disk space is too low!"));
861 }
862 if (bytes_allocated != 0 && IsPruneMode()) {
863 m_check_for_pruning = true;
864 }
865
866 return true;
867}
868
869bool BlockManager::WriteBlockUndo(const CBlockUndo &blockundo,
871 CBlockIndex &block) {
873 const BlockfileType type = BlockfileTypeForHeight(block.nHeight);
874 auto &cursor =
875 *Assert(WITH_LOCK(cs_LastBlockFile, return m_blockfile_cursors[type]));
876
877 // Write undo information to disk
878 if (block.GetUndoPos().IsNull()) {
879 FlatFilePos pos;
880 const unsigned int blockundo_size{
881 static_cast<unsigned int>(GetSerializeSize(blockundo))};
882 if (!FindUndoPos(state, block.nFile, pos,
883 blockundo_size + UNDO_DATA_DISK_OVERHEAD)) {
884 LogError("FindUndoPos failed\n");
885 return false;
886 }
887 // Open history file to append
888 AutoFile fileout{OpenUndoFile(pos)};
889 if (fileout.IsNull()) {
890 LogError("OpenUndoFile failed\n");
891 return FatalError(m_opts.notifications, state,
892 "Failed to write undo data");
893 }
894 // Write index header
895 fileout << GetParams().DiskMagic() << blockundo_size;
896
897 // Write undo data
899 fileout << blockundo;
900
901 // calculate & write checksum
902 HashWriter hasher{};
903 hasher << block.pprev->GetBlockHash();
904 hasher << blockundo;
905 fileout << hasher.GetHash();
906
907 // rev files are written in block height order, whereas blk files are
908 // written as blocks come in (often out of order) we want to flush the
909 // rev (undo) file once we've written the last block, which is indicated
910 // by the last height in the block file info as below; note that this
911 // does not catch the case where the undo writes are keeping up with the
912 // block writes (usually when a synced up node is getting newly mined
913 // blocks) -- this case is caught in the FindNextBlockPos function
914 if (pos.nFile < cursor.file_num &&
915 static_cast<uint32_t>(block.nHeight) ==
916 m_blockfile_info[pos.nFile].nHeightLast) {
917 // Do not propagate the return code, a failed flush here should not
918 // be an indication for a failed write. If it were propagated here,
919 // the caller would assume the undo data not to be written, when in
920 // fact it is. Note though, that a failed flush might leave the data
921 // file untrimmed.
922 if (!FlushUndoFile(pos.nFile, true)) {
924 "Failed to flush undo file %05i\n", pos.nFile);
925 }
926 } else if (pos.nFile == cursor.file_num &&
927 block.nHeight > cursor.undo_height) {
928 cursor.undo_height = block.nHeight;
929 }
930 // update nUndoPos in block index
931 block.nUndoPos = pos.nPos;
932 block.nStatus = block.nStatus.withUndo();
933 m_dirty_blockindex.insert(&block);
934 }
935
936 return true;
937}
938
939bool BlockManager::ReadBlock(CBlock &block, const FlatFilePos &pos) const {
940 block.SetNull();
941
942 // Open history file to read
943 AutoFile filein{OpenBlockFile(pos, true)};
944 if (filein.IsNull()) {
945 LogError("ReadBlock: OpenBlockFile failed for %s\n", pos.ToString());
946 return false;
947 }
948
949 // Read block
950 try {
951 filein >> block;
952 } catch (const std::exception &e) {
953 LogError("%s: Deserialize or I/O error - %s at %s\n", __func__,
954 e.what(), pos.ToString());
955 return false;
956 }
957
958 // Check the header
959 if (!CheckProofOfWork(block.GetHash(), block.nBits, GetConsensus())) {
960 LogError("ReadBlock: Errors in block header at %s\n", pos.ToString());
961 return false;
962 }
963
964 return true;
965}
966
967bool BlockManager::ReadBlock(CBlock &block, const CBlockIndex &index) const {
968 const FlatFilePos block_pos{WITH_LOCK(cs_main, return index.GetBlockPos())};
969
970 if (!ReadBlock(block, block_pos)) {
971 return false;
972 }
973
974 if (block.GetHash() != index.GetBlockHash()) {
975 LogError("ReadBlock(CBlock&, CBlockIndex*): GetHash() "
976 "doesn't match index for %s at %s\n",
977 index.ToString(), block_pos.ToString());
978 return false;
979 }
980
981 return true;
982}
983
984bool BlockManager::ReadRawBlock(std::vector<uint8_t> &block,
985 const FlatFilePos &pos) const {
986 FlatFilePos hpos = pos;
987 // If nPos is less than 8 the pos is null and we don't have the block data
988 // Return early to prevent undefined behavior of unsigned int underflow
989 if (hpos.nPos < 8) {
990 LogError("%s: OpenBlockFile failed for %s\n", __func__, pos.ToString());
991 return false;
992 }
993 hpos.nPos -= 8; // Seek back 8 bytes for meta header
994 AutoFile filein{OpenBlockFile(hpos, true)};
995 if (filein.IsNull()) {
996 LogError("%s: OpenBlockFile failed for %s\n", __func__, pos.ToString());
997 return false;
998 }
999
1000 try {
1002 unsigned int blk_size;
1003
1004 filein >> blk_start >> blk_size;
1005
1006 if (blk_start != GetParams().DiskMagic()) {
1007 LogError("%s: Block magic mismatch for %s: %s versus expected %s\n",
1008 __func__, pos.ToString(), HexStr(blk_start),
1009 HexStr(GetParams().DiskMagic()));
1010 return false;
1011 }
1012
1013 if (blk_size > MAX_SIZE) {
1014 LogError("%s: Block data is larger than maximum deserialization "
1015 "size for %s: %s versus %s\n",
1016 __func__, pos.ToString(), blk_size, MAX_SIZE);
1017 return false;
1018 }
1019
1020 // Zeroing of memory is intentional here
1021 block.resize(blk_size);
1022 filein.read(MakeWritableByteSpan(block));
1023 } catch (const std::exception &e) {
1024 LogError("%s: Read from block file failed: %s for %s\n", __func__,
1025 e.what(), pos.ToString());
1026 return false;
1027 }
1028
1029 return true;
1030}
1031
1033 const FlatFilePos &pos) const {
1034 // Open history file to read
1035 AutoFile filein{OpenBlockFile(pos, true)};
1036 if (filein.IsNull()) {
1037 LogError("ReadTxFromDisk: OpenBlockFile failed for %s\n",
1038 pos.ToString());
1039 return false;
1040 }
1041
1042 // Read tx
1043 try {
1044 filein >> tx;
1045 } catch (const std::exception &e) {
1046 LogError("%s: Deserialize or I/O error - %s at %s\n", __func__,
1047 e.what(), pos.ToString());
1048 return false;
1049 }
1050
1051 return true;
1052}
1053
1055 const FlatFilePos &pos) const {
1056 // Open undo file to read
1057 AutoFile filein{
1058 OpenUndoFile(pos, true),
1059 };
1060 if (filein.IsNull()) {
1061 LogError("ReadTxUndoFromDisk: OpenUndoFile failed for %s\n",
1062 pos.ToString());
1063 return false;
1064 }
1065
1066 // Read undo data
1067 try {
1068 filein >> tx_undo;
1069 } catch (const std::exception &e) {
1070 LogError("%s: Deserialize or I/O error - %s at %s\n", __func__,
1071 e.what(), pos.ToString());
1072 return false;
1073 }
1074
1075 return true;
1076}
1077
1079 const unsigned int block_size{
1080 static_cast<unsigned int>(GetSerializeSize(block))};
1081 FlatFilePos pos{
1083 block.GetBlockTime())};
1084 if (pos.IsNull()) {
1085 LogError("FindNextBlockPos failed\n");
1086 return FlatFilePos();
1087 }
1088 AutoFile fileout{OpenBlockFile(pos)};
1089 if (fileout.IsNull()) {
1090 LogError("OpenBlockFile failed\n");
1091 m_opts.notifications.fatalError("Failed to write block");
1092 return FlatFilePos();
1093 }
1094
1095 // Write index header
1096 fileout << GetParams().DiskMagic() << block_size;
1097 // Write block
1099 fileout << block;
1100 return pos;
1101}
1102
1104 std::atomic<bool> &m_importing;
1105
1106public:
1107 ImportingNow(std::atomic<bool> &importing) : m_importing{importing} {
1108 assert(m_importing == false);
1109 m_importing = true;
1110 }
1112 assert(m_importing == true);
1113 m_importing = false;
1114 }
1115};
1116
1119 std::vector<fs::path> vImportFiles) {
1121
1122 {
1123 ImportingNow imp{chainman.m_blockman.m_importing};
1124
1125 // -reindex
1126 if (fReindex) {
1127 int nFile = 0;
1128 // Map of disk positions for blocks with unknown parent (only used
1129 // for reindex); parent hash -> child disk position, multiple
1130 // children can have the same parent.
1131 std::multimap<BlockHash, FlatFilePos> blocks_with_unknown_parent;
1132 while (true) {
1133 FlatFilePos pos(nFile, 0);
1134 if (!fs::exists(chainman.m_blockman.GetBlockPosFilename(pos))) {
1135 // No block files left to reindex
1136 break;
1137 }
1138 AutoFile file{chainman.m_blockman.OpenBlockFile(pos, true)};
1139 if (file.IsNull()) {
1140 // This error is logged in OpenBlockFile
1141 break;
1142 }
1143 LogPrintf("Reindexing block file blk%05u.dat...\n",
1144 (unsigned int)nFile);
1145 chainman.LoadExternalBlockFile(
1146 file, &pos, &blocks_with_unknown_parent, avalanche);
1147 if (chainman.m_interrupt) {
1148 LogPrintf("Interrupt requested. Exit %s\n", __func__);
1149 return;
1150 }
1151 nFile++;
1152 }
1153 WITH_LOCK(
1154 ::cs_main,
1155 chainman.m_blockman.m_block_tree_db->WriteReindexing(false));
1156 fReindex = false;
1157 LogPrintf("Reindexing finished\n");
1158 // To avoid ending up in a situation without genesis block, re-try
1159 // initializing (no-op if reindexing worked):
1160 chainman.ActiveChainstate().LoadGenesisBlock();
1161 }
1162
1163 // -loadblock=
1164 for (const fs::path &path : vImportFiles) {
1165 AutoFile file{fsbridge::fopen(path, "rb")};
1166 if (!file.IsNull()) {
1167 LogPrintf("Importing blocks file %s...\n",
1168 fs::PathToString(path));
1169 chainman.LoadExternalBlockFile(
1170 file, /*dbp=*/nullptr,
1171 /*blocks_with_unknown_parent=*/nullptr, avalanche);
1172 if (chainman.m_interrupt) {
1173 LogPrintf("Interrupt requested. Exit %s\n", __func__);
1174 return;
1175 }
1176 } else {
1177 LogPrintf("Warning: Could not open blocks file %s\n",
1178 fs::PathToString(path));
1179 }
1180 }
1181
1182 // Reconsider blocks we know are valid. They may have been marked
1183 // invalid by, for instance, running an outdated version of the node
1184 // software.
1185 const MapCheckpoints &checkpoints =
1187 for (const MapCheckpoints::value_type &i : checkpoints) {
1188 const BlockHash &hash = i.second;
1189
1190 LOCK(cs_main);
1191 CBlockIndex *pblockindex =
1192 chainman.m_blockman.LookupBlockIndex(hash);
1193 if (pblockindex && !pblockindex->nStatus.isValid()) {
1194 LogPrintf("Reconsidering checkpointed block %s ...\n",
1195 hash.GetHex());
1196 chainman.ActiveChainstate().ResetBlockFailureFlags(pblockindex);
1197 }
1198
1199 if (pblockindex && pblockindex->nStatus.isOnParkedChain()) {
1200 LogPrintf("Unparking checkpointed block %s ...\n",
1201 hash.GetHex());
1202 chainman.ActiveChainstate().UnparkBlockAndChildren(pblockindex);
1203 }
1204 }
1205
1206 // scan for better chains in the block chain database, that are not yet
1207 // connected in the active best chain
1208
1209 // We can't hold cs_main during ActivateBestChain even though we're
1210 // accessing the chainman unique_ptrs since ABC requires us not to be
1211 // holding cs_main, so retrieve the relevant pointers before the ABC
1212 // call.
1213 for (Chainstate *chainstate :
1214 WITH_LOCK(::cs_main, return chainman.GetAll())) {
1216 if (!chainstate->ActivateBestChain(state, nullptr, avalanche)) {
1218 "Failed to connect best block (%s)", state.ToString()));
1219 return;
1220 }
1221 }
1222
1223 if (chainman.m_blockman.StopAfterBlockImport()) {
1224 LogPrintf("Stopping after block import\n");
1225 StartShutdown();
1226 return;
1227 }
1228 } // End scope of ImportingNow
1229}
1230
1231std::ostream &operator<<(std::ostream &os, const BlockfileType &type) {
1232 switch (type) {
1233 case BlockfileType::NORMAL:
1234 os << "normal";
1235 break;
1237 os << "assumed";
1238 break;
1239 default:
1240 os.setstate(std::ios_base::failbit);
1241 }
1242 return os;
1243}
1244
1245std::ostream &operator<<(std::ostream &os, const BlockfileCursor &cursor) {
1246 os << strprintf("BlockfileCursor(file_num=%d, undo_height=%d)",
1247 cursor.file_num, cursor.undo_height);
1248 return os;
1249}
1250} // namespace node
void ScheduleBatchPriority()
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
@ TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:74
#define Assert(val)
Identity function.
Definition: check.h:84
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:430
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:23
BlockHash GetHash() const
Definition: block.cpp:11
uint32_t nBits
Definition: block.h:30
BlockHash hashPrevBlock
Definition: block.h:27
int64_t GetBlockTime() const
Definition: block.h:57
Definition: block.h:60
void SetNull()
Definition: block.h:82
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
std::string ToString() const
Definition: blockindex.cpp:30
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: blockindex.h:32
void BuildSkip()
Build the skiplist pointer for this entry.
Definition: blockindex.cpp:67
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: blockindex.h:51
const BlockHash * phashBlock
pointer to the hash of the block, if any.
Definition: blockindex.h:29
uint32_t nTime
Definition: blockindex.h:76
unsigned int nTimeMax
(memory only) Maximum nTime in the chain up to and including this block.
Definition: blockindex.h:88
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
Definition: blockindex.h:82
FlatFilePos GetUndoPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: blockindex.h:107
unsigned int nTx
Number of transactions in this block.
Definition: blockindex.h:55
bool RaiseValidity(enum BlockValidity nUpTo) EXCLUSIVE_LOCKS_REQUIRED(
Raise the validity level of this block index entry.
Definition: blockindex.h:199
int64_t nTimeReceived
(memory only) block header metadata
Definition: blockindex.h:85
BlockHash GetBlockHash() const
Definition: blockindex.h:130
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:38
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: blockindex.h:97
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block.
Definition: blockindex.h:68
Undo information for a CBlock.
Definition: undo.h:72
int Height() const
Return the maximal height in the chain.
Definition: chain.h:190
const CMessageHeader::MessageMagic & DiskMagic() const
Definition: chainparams.h:99
uint64_t PruneAfterHeight() const
Definition: chainparams.h:121
const CCheckpointData & Checkpoints() const
Definition: chainparams.h:145
std::array< uint8_t, MESSAGE_START_SIZE > MessageMagic
Definition: protocol.h:47
A mutable version of CTransaction.
Definition: transaction.h:274
Restore the UTXO in a Coin at a given COutPoint.
Definition: undo.h:61
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:739
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:838
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1191
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:1442
kernel::Notifications & GetNotifications() const
Definition: validation.h:1299
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:1327
const CChainParams & GetParams() const
Definition: validation.h:1284
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1408
void LoadExternalBlockFile(AutoFile &file_in, FlatFilePos *dbp=nullptr, std::multimap< BlockHash, FlatFilePos > *blocks_with_unknown_parent=nullptr, avalanche::Processor *const avalanche=nullptr)
Import blocks from an external file.
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1332
FlatFileSeq represents a sequence of numbered files storing raw data.
Definition: flatfile.h:49
fs::path FileName(const FlatFilePos &pos) const
Get the name of the file at the given position.
Definition: flatfile.cpp:24
size_t Allocate(const FlatFilePos &pos, size_t add_size, bool &out_of_space)
Allocate additional space in a file after the given starting position.
Definition: flatfile.cpp:53
FILE * Open(const FlatFilePos &pos, bool read_only=false)
Open a handle to the file at the given position.
Definition: flatfile.cpp:28
Reads data from an underlying stream, while hashing the read data.
Definition: hash.h:150
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:99
std::string ToString() const
Definition: validation.h:125
bool IsNull() const
Definition: uint256.h:32
std::string GetHex() const
Definition: uint256.cpp:16
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
virtual void flushError(const std::string &debug_message)
The flush error notification is sent to notify the user that an error occurred while flushing block d...
virtual void fatalError(const std::string &debug_message, const bilingual_str &user_message={})
The fatal error notification is sent to notify the user when an error occurs in kernel code that can'...
const kernel::BlockManagerOpts m_opts
Definition: blockstorage.h:252
std::set< int > m_dirty_fileinfo
Dirty block file entries.
Definition: blockstorage.h:238
FlatFileSeq UndoFileSeq() const
RecursiveMutex cs_LastBlockFile
Definition: blockstorage.h:197
const CChainParams & GetParams() const
Definition: blockstorage.h:121
bool CheckBlockDataAvailability(const CBlockIndex &upper_block LIFETIMEBOUND, const CBlockIndex &lower_block LIFETIMEBOUND) EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetFirstBlock(const CBlockIndex &upper_block LIFETIMEBOUND, std::function< bool(BlockStatus)> status_test, 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:412
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 undo???.dat) so that the disk space used is less than a us...
void UpdateBlockInfo(const CBlock &block, unsigned int nHeight, const FlatFilePos &pos)
Update blockfile info while processing a block during reindex.
FlatFileSeq BlockFileSeq() const
bool StopAfterBlockImport() const
Definition: blockstorage.h:361
bool LoadBlockIndex(const std::optional< BlockHash > &snapshot_blockhash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the blocktree off disk and into memory.
bool ReadBlockUndo(CBlockUndo &blockundo, const CBlockIndex &index) const
bool ReadRawBlock(std::vector< uint8_t > &block, const FlatFilePos &pos) 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)
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool ReadTxFromDisk(CMutableTransaction &tx, const FlatFilePos &pos) const
Functions for disk access for txs.
const Consensus::Params & GetConsensus() const
Definition: blockstorage.h:122
CBlockIndex * InsertBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Create a new block index entry for a given block hash.
bool ReadTxUndoFromDisk(CTxUndo &tx, const FlatFilePos &pos) const
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:353
int MaxBlockfileNum() const EXCLUSIVE_LOCKS_REQUIRED(cs_LastBlockFile)
Definition: blockstorage.h:216
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune) const
Actually unlink the specified files.
void WriteBlockIndexDB() EXCLUSIVE_LOCKS_REQUIRED(bool LoadBlockIndexDB(const std::optional< BlockHash > &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:303
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...
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.
const util::SignalInterrupt & m_interrupt
Definition: blockstorage.h:261
const CBlockIndex * GetLastCheckpoint(const CCheckpointData &data) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Returns last CBlockIndex* that is a checkpoint.
std::set< CBlockIndex * > m_dirty_blockindex
Dirty block index entries.
Definition: blockstorage.h:235
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:230
bool FindUndoPos(BlockValidationState &state, int nFile, FlatFilePos &pos, unsigned int nAddSize)
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=false) const
Check whether the block associated with this index entry is pruned or not.
Definition: blockstorage.h:425
bool IsPruneMode() const
Whether running in -prune mode.
Definition: blockstorage.h:350
void CleanupBlockRevFiles() const
void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight, const Chainstate &chain, ChainstateManager &chainman)
Calculate the block/rev files to delete based on height specified by user with RPC command pruneblock...
std::atomic< bool > m_importing
Definition: blockstorage.h:262
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:336
std::vector< CBlockFileInfo > m_blockfile_info
Definition: blockstorage.h:198
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
bool ReadBlock(CBlock &block, const FlatFilePos &pos) const
Functions for disk access for blocks.
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:278
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:280
ImportingNow(std::atomic< bool > &importing)
std::atomic< bool > & m_importing
256-bit opaque blob.
Definition: uint256.h:129
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:30
std::map< int, BlockHash > MapCheckpoints
Definition: chainparams.h:33
#define LogPrintLevel(category, level,...)
Definition: logging.h:437
#define LogPrint(category,...)
Definition: logging.h:452
#define LogError(...)
Definition: logging.h:419
#define LogPrintf(...)
Definition: logging.h:424
unsigned int nHeight
@ PRUNE
Definition: logging.h:83
@ BLOCKSTORE
Definition: logging.h:97
static bool exists(const path &p)
Definition: fs.h:107
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:147
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:30
Definition: messages.h:12
static const unsigned int UNDOFILE_CHUNK_SIZE
The pre-allocation chunk size for rev?????.dat files (since 0.8)
Definition: blockstorage.h:53
BlockfileType
Definition: blockstorage.h:81
@ ASSUMED
Definition: blockstorage.h:84
std::ostream & operator<<(std::ostream &os, const BlockfileType &type)
static constexpr size_t UNDO_DATA_DISK_OVERHEAD
Total overhead when writing undo data: header (8 bytes) plus checksum (32 bytes)
Definition: blockstorage.h:65
static constexpr unsigned int BLOCKFILE_CHUNK_SIZE
The pre-allocation chunk size for blk?????.dat files (since 0.8)
Definition: blockstorage.h:51
static constexpr size_t BLOCK_SERIALIZATION_HEADER_SIZE
Size of header written by WriteBlock before a serialized CBlock.
Definition: blockstorage.h:58
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: blockstorage.h:55
std::atomic_bool fReindex
void ImportBlocks(ChainstateManager &chainman, avalanche::Processor *const avalanche, std::vector< fs::path > vImportFiles)
bool CheckProofOfWork(const BlockHash &hash, uint32_t nBits, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:87
const char * name
Definition: rest.cpp:47
reverse_range< T > reverse_iterate(T &x)
static std::string ToString(const CService &ip)
Definition: db.h:36
size_t GetSerializeSize(const T &t)
Definition: serialize.h:1262
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:34
void StartShutdown()
Request shutdown of the application.
Definition: shutdown.cpp:16
Span< std::byte > MakeWritableByteSpan(V &&v) noexcept
Definition: span.h:305
Holds configuration for use during UTXO snapshot load and validation.
Definition: chainparams.h:48
unsigned int nChainTx
Used to populate the nChainTx value, which is used during BlockManager::LoadBlockIndex().
Definition: chainparams.h:60
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
bool hasData() const
Definition: blockstatus.h:59
MapCheckpoints mapCheckpoints
Definition: chainparams.h:36
int nFile
Definition: flatfile.h:15
std::string ToString() const
Definition: flatfile.cpp:20
unsigned int nPos
Definition: flatfile.h:16
bool IsNull() const
Definition: flatfile.h:40
Notifications & notifications
#define LOCK2(cs1, cs2)
Definition: sync.h:309
#define LOCK(cs)
Definition: sync.h:306
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:357
static int count
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition: time.cpp:80
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:68
bool FatalError(Notifications &notifications, BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage)
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev?...
Definition: validation.h:115