Bitcoin ABC 0.32.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
348bool 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 if (!m_block_tree_db->WriteBatchSync(vFiles, max_blockfile, vBlocks)) {
368 return false;
369 }
370 return true;
371}
372
373bool BlockManager::LoadBlockIndexDB(
374 const std::optional<BlockHash> &snapshot_blockhash) {
375 if (!LoadBlockIndex(snapshot_blockhash)) {
376 return false;
377 }
378 int max_blockfile_num{0};
379
380 // Load block file info
381 m_block_tree_db->ReadLastBlockFile(max_blockfile_num);
382 m_blockfile_info.resize(max_blockfile_num + 1);
383 LogPrintf("%s: last block file = %i\n", __func__, max_blockfile_num);
384 for (int nFile = 0; nFile <= max_blockfile_num; nFile++) {
385 m_block_tree_db->ReadBlockFileInfo(nFile, m_blockfile_info[nFile]);
386 }
387 LogPrintf("%s: last block file info: %s\n", __func__,
388 m_blockfile_info[max_blockfile_num].ToString());
389 for (int nFile = max_blockfile_num + 1; true; nFile++) {
390 CBlockFileInfo info;
391 if (m_block_tree_db->ReadBlockFileInfo(nFile, info)) {
392 m_blockfile_info.push_back(info);
393 } else {
394 break;
395 }
396 }
397
398 // Check presence of blk files
399 LogPrintf("Checking all blk files are present...\n");
400 std::set<int> setBlkDataFiles;
401 for (const auto &[_, block_index] : m_block_index) {
402 if (block_index.nStatus.hasData()) {
403 setBlkDataFiles.insert(block_index.nFile);
404 }
405 }
406
407 for (const int i : setBlkDataFiles) {
408 FlatFilePos pos(i, 0);
409 if (OpenBlockFile(pos, true).IsNull()) {
410 return false;
411 }
412 }
413
414 {
415 // Initialize the blockfile cursors.
417 for (size_t i = 0; i < m_blockfile_info.size(); ++i) {
418 const auto last_height_in_file = m_blockfile_info[i].nHeightLast;
419 m_blockfile_cursors[BlockfileTypeForHeight(last_height_in_file)] = {
420 static_cast<int>(i), 0};
421 }
422 }
423
424 // Check whether we have ever pruned block & undo files
425 m_block_tree_db->ReadFlag("prunedblockfiles", m_have_pruned);
426 if (m_have_pruned) {
427 LogPrintf(
428 "LoadBlockIndexDB(): Block files have previously been pruned\n");
429 }
430
431 // Check whether we need to continue reindexing
432 if (m_block_tree_db->IsReindexing()) {
433 fReindex = true;
434 }
435
436 return true;
437}
438
439void BlockManager::ScanAndUnlinkAlreadyPrunedFiles() {
441 int max_blockfile =
443 if (!m_have_pruned) {
444 return;
445 }
446
447 std::set<int> block_files_to_prune;
448 for (int file_number = 0; file_number < max_blockfile; file_number++) {
449 if (m_blockfile_info[file_number].nSize == 0) {
450 block_files_to_prune.insert(file_number);
451 }
452 }
453
454 UnlinkPrunedFiles(block_files_to_prune);
455}
456
457const CBlockIndex *
459 const MapCheckpoints &checkpoints = data.mapCheckpoints;
460
461 for (const MapCheckpoints::value_type &i : reverse_iterate(checkpoints)) {
462 const BlockHash &hash = i.second;
463 const CBlockIndex *pindex = LookupBlockIndex(hash);
464 if (pindex) {
465 return pindex;
466 }
467 }
468
469 return nullptr;
470}
471
472bool BlockManager::IsBlockPruned(const CBlockIndex &block) const {
474 return (m_have_pruned && !block.nStatus.hasData() && block.nTx > 0);
475}
476
477const CBlockIndex *
478BlockManager::GetFirstBlock(const CBlockIndex &upper_block,
479 std::function<bool(BlockStatus)> status_test,
480 const CBlockIndex *lower_block) const {
482 const CBlockIndex *last_block = &upper_block;
483 // 'upper_block' satisfy the test
484 assert(status_test(last_block->nStatus));
485 while (last_block->pprev && status_test(last_block->pprev->nStatus)) {
486 if (lower_block) {
487 // Return if we reached the lower_block
488 if (last_block == lower_block) {
489 return lower_block;
490 }
491 // if range was surpassed, means that 'lower_block' is not part of
492 // the 'upper_block' chain and so far this is not allowed.
493 assert(last_block->nHeight >= lower_block->nHeight);
494 }
495 last_block = last_block->pprev;
496 }
497 assert(last_block != nullptr);
498 return last_block;
499}
500
501bool BlockManager::CheckBlockDataAvailability(const CBlockIndex &upper_block,
502 const CBlockIndex &lower_block) {
503 if (!(upper_block.nStatus.hasData())) {
504 return false;
505 }
506 return GetFirstBlock(
507 upper_block,
508 [](const BlockStatus &status) { return status.hasData(); },
509 &lower_block) == &lower_block;
510}
511
512// If we're using -prune with -reindex, then delete block files that will be
513// ignored by the reindex. Since reindexing works by starting at block file 0
514// and looping until a blockfile is missing, do the same here to delete any
515// later block files after a gap. Also delete all rev files since they'll be
516// rewritten by the reindex anyway. This ensures that m_blockfile_info is in
517// sync with what's actually on disk by the time we start downloading, so that
518// pruning works correctly.
520 std::map<std::string, fs::path> mapBlockFiles;
521
522 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
523 // Remove the rev files immediately and insert the blk file paths into an
524 // ordered map keyed by block file index.
525 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for "
526 "-reindex with -prune\n");
527 for (const auto &file : fs::directory_iterator{m_opts.blocks_dir}) {
528 const std::string path = fs::PathToString(file.path().filename());
529 if (fs::is_regular_file(file) && path.length() == 12 &&
530 path.substr(8, 4) == ".dat") {
531 if (path.substr(0, 3) == "blk") {
532 mapBlockFiles[path.substr(3, 5)] = file.path();
533 } else if (path.substr(0, 3) == "rev") {
534 remove(file.path());
535 }
536 }
537 }
538
539 // Remove all block files that aren't part of a contiguous set starting at
540 // zero by walking the ordered map (keys are block file indices) by keeping
541 // a separate counter. Once we hit a gap (or if 0 doesn't exist) start
542 // removing block files.
543 int contiguousCounter = 0;
544 for (const auto &item : mapBlockFiles) {
545 if (LocaleIndependentAtoi<int>(item.first) == contiguousCounter) {
546 contiguousCounter++;
547 continue;
548 }
549 remove(item.second);
550 }
551}
552
555
556 return &m_blockfile_info.at(n);
557}
558
560 const CBlockIndex &index) const {
561 const FlatFilePos pos{WITH_LOCK(::cs_main, return index.GetUndoPos())};
562
563 if (pos.IsNull()) {
564 LogError("%s: no undo data available\n", __func__);
565 return false;
566 }
567
568 // Open history file to read
569 AutoFile filein{OpenUndoFile(pos, true)};
570 if (filein.IsNull()) {
571 LogError("OpenUndoFile failed for %s\n", pos.ToString());
572 return false;
573 }
574
575 // Read block
576 uint256 hashChecksum;
577 // Use HashVerifier as reserializing may lose data
578 // c.f. commit 80df982ab2f63e60edc1033d1ef8929c837d00c5
579 HashVerifier verifier{filein};
580 try {
581 verifier << index.pprev->GetBlockHash();
582 verifier >> blockundo;
583 filein >> hashChecksum;
584 } catch (const std::exception &e) {
585 LogError("%s: Deserialize or I/O error - %s\n", __func__, e.what());
586 return false;
587 }
588
589 // Verify checksum
590 if (hashChecksum != verifier.GetHash()) {
591 LogError("%s: Checksum mismatch\n", __func__);
592 return false;
593 }
594
595 return true;
596}
597
598bool BlockManager::FlushUndoFile(int block_file, bool finalize) {
599 FlatFilePos undo_pos_old(block_file,
600 m_blockfile_info[block_file].nUndoSize);
601 if (!UndoFileSeq().Flush(undo_pos_old, finalize)) {
603 "Flushing undo file to disk failed. This is likely the "
604 "result of an I/O error.");
605 return false;
606 }
607 return true;
608}
609
610bool BlockManager::FlushBlockFile(int blockfile_num, bool fFinalize,
611 bool finalize_undo) {
612 bool success = true;
614
615 if (m_blockfile_info.empty()) {
616 // Return if we haven't loaded any blockfiles yet. This happens during
617 // chainstate init, when we call
618 // ChainstateManager::MaybeRebalanceCaches() (which then calls
619 // FlushStateToDisk()), resulting in a call to this function before we
620 // have populated `m_blockfile_info` via LoadBlockIndexDB().
621 return true;
622 }
623 assert(static_cast<int>(m_blockfile_info.size()) > blockfile_num);
624
625 FlatFilePos block_pos_old(blockfile_num,
626 m_blockfile_info[blockfile_num].nSize);
627 if (!BlockFileSeq().Flush(block_pos_old, fFinalize)) {
629 "Flushing block file to disk failed. This is likely the "
630 "result of an I/O error.");
631 success = false;
632 }
633 // we do not always flush the undo file, as the chain tip may be lagging
634 // behind the incoming blocks,
635 // e.g. during IBD or a sync after a node going offline
636 if (!fFinalize || finalize_undo) {
637 if (!FlushUndoFile(blockfile_num, finalize_undo)) {
638 success = false;
639 }
640 }
641 return success;
642}
643
645 if (!m_snapshot_height) {
646 return BlockfileType::NORMAL;
647 }
648 return (height >= *m_snapshot_height) ? BlockfileType::ASSUMED
649 : BlockfileType::NORMAL;
650}
651
654 auto &cursor = m_blockfile_cursors[BlockfileTypeForHeight(tip_height)];
655 // If the cursor does not exist, it means an assumeutxo snapshot is loaded,
656 // but no blocks past the snapshot height have been written yet, so there
657 // is no data associated with the chainstate, and it is safe not to flush.
658 if (cursor) {
659 return FlushBlockFile(cursor->file_num, /*fFinalize=*/false,
660 /*finalize_undo=*/false);
661 }
662 // No need to log warnings in this case.
663 return true;
664}
665
668
669 uint64_t retval = 0;
670 for (const CBlockFileInfo &file : m_blockfile_info) {
671 retval += file.nSize + file.nUndoSize;
672 }
673
674 return retval;
675}
676
678 const std::set<int> &setFilesToPrune) const {
679 std::error_code error_code;
680 for (const int i : setFilesToPrune) {
681 FlatFilePos pos(i, 0);
682 const bool removed_blockfile{
683 fs::remove(BlockFileSeq().FileName(pos), error_code)};
684 const bool removed_undofile{
685 fs::remove(UndoFileSeq().FileName(pos), error_code)};
686 if (removed_blockfile || removed_undofile) {
687 LogPrint(BCLog::BLOCKSTORE, "Prune: %s deleted blk/rev (%05u)\n",
688 __func__, i);
689 }
690 }
691}
692
694 return FlatFileSeq(m_opts.blocks_dir, "blk",
695 m_opts.fast_prune ? 0x4000 /* 16kb */
697}
698
701}
702
704 bool fReadOnly) const {
705 return AutoFile{BlockFileSeq().Open(pos, fReadOnly)};
706}
707
710 bool fReadOnly) const {
711 return AutoFile{UndoFileSeq().Open(pos, fReadOnly)};
712}
713
715 return BlockFileSeq().FileName(pos);
716}
717
719 unsigned int nHeight,
720 uint64_t nTime) {
722
723 const BlockfileType chain_type = BlockfileTypeForHeight(nHeight);
724
725 if (!m_blockfile_cursors[chain_type]) {
726 // If a snapshot is loaded during runtime, we may not have initialized
727 // this cursor yet.
728 assert(chain_type == BlockfileType::ASSUMED);
729 const auto new_cursor = BlockfileCursor{this->MaxBlockfileNum() + 1};
730 m_blockfile_cursors[chain_type] = new_cursor;
732 "[%s] initializing blockfile cursor to %s\n", chain_type,
733 new_cursor);
734 }
735 const int last_blockfile = m_blockfile_cursors[chain_type]->file_num;
736
737 int nFile = last_blockfile;
738 if (static_cast<int>(m_blockfile_info.size()) <= nFile) {
739 m_blockfile_info.resize(nFile + 1);
740 }
741
742 bool finalize_undo = false;
743 unsigned int max_blockfile_size{MAX_BLOCKFILE_SIZE};
744 // Use smaller blockfiles in test-only -fastprune mode - but avoid
745 // the possibility of having a block not fit into the block file.
746 if (m_opts.fast_prune) {
747 max_blockfile_size = 0x10000; // 64kiB
748 if (nAddSize >= max_blockfile_size) {
749 // dynamically adjust the blockfile size to be larger than the
750 // added size
751 max_blockfile_size = nAddSize + 1;
752 }
753 }
754 // TODO: we will also need to dynamically adjust the blockfile size
755 // or raise MAX_BLOCKFILE_SIZE when we reach block sizes larger than
756 // 128 MiB
757 assert(nAddSize < max_blockfile_size);
758
759 while (m_blockfile_info[nFile].nSize + nAddSize >= max_blockfile_size) {
760 // when the undo file is keeping up with the block file, we want to
761 // flush it explicitly when it is lagging behind (more blocks arrive
762 // than are being connected), we let the undo block write case
763 // handle it
764 finalize_undo =
765 (static_cast<int>(m_blockfile_info[nFile].nHeightLast) ==
766 Assert(m_blockfile_cursors[chain_type])->undo_height);
767
768 // Try the next unclaimed blockfile number
769 nFile = this->MaxBlockfileNum() + 1;
770 // Set to increment MaxBlockfileNum() for next iteration
771 m_blockfile_cursors[chain_type] = BlockfileCursor{nFile};
772
773 if (static_cast<int>(m_blockfile_info.size()) <= nFile) {
774 m_blockfile_info.resize(nFile + 1);
775 }
776 }
777 FlatFilePos pos;
778 pos.nFile = nFile;
779 pos.nPos = m_blockfile_info[nFile].nSize;
780
781 if (nFile != last_blockfile) {
783 "Leaving block file %i: %s (onto %i) (height %i)\n",
784 last_blockfile, m_blockfile_info[last_blockfile].ToString(),
785 nFile, nHeight);
786
787 // Do not propagate the return code. The flush concerns a previous
788 // block and undo file that has already been written to. If a flush
789 // fails here, and we crash, there is no expected additional block
790 // data inconsistency arising from the flush failure here. However,
791 // the undo data may be inconsistent after a crash if the flush is
792 // called during a reindex. A flush error might also leave some of
793 // the data files untrimmed.
794 if (!FlushBlockFile(last_blockfile, /*fFinalize=*/true,
795 finalize_undo)) {
798 "Failed to flush previous block file %05i (finalize=1, "
799 "finalize_undo=%i) before opening new block file %05i\n",
800 last_blockfile, finalize_undo, nFile);
801 }
802 // No undo data yet in the new file, so reset our undo-height tracking.
803 m_blockfile_cursors[chain_type] = BlockfileCursor{nFile};
804 }
805
806 m_blockfile_info[nFile].AddBlock(nHeight, nTime);
807 m_blockfile_info[nFile].nSize += nAddSize;
808
809 bool out_of_space;
810 size_t bytes_allocated =
811 BlockFileSeq().Allocate(pos, nAddSize, out_of_space);
812 if (out_of_space) {
813 m_opts.notifications.fatalError("Disk space is too low!",
814 _("Disk space is too low!"));
815 return {};
816 }
817 if (bytes_allocated != 0 && IsPruneMode()) {
818 m_check_for_pruning = true;
819 }
820
821 m_dirty_fileinfo.insert(nFile);
822 return pos;
823}
824
825void BlockManager::UpdateBlockInfo(const CBlock &block, unsigned int nHeight,
826 const FlatFilePos &pos) {
828
829 // Update the cursor so it points to the last file.
831 auto &cursor{m_blockfile_cursors[chain_type]};
832 if (!cursor || cursor->file_num < pos.nFile) {
833 m_blockfile_cursors[chain_type] = BlockfileCursor{pos.nFile};
834 }
835
836 // Update the file information with the current block.
837 const unsigned int added_size = ::GetSerializeSize(block);
838 const int nFile = pos.nFile;
839 if (static_cast<int>(m_blockfile_info.size()) <= nFile) {
840 m_blockfile_info.resize(nFile + 1);
841 }
842 m_blockfile_info[nFile].AddBlock(nHeight, block.GetBlockTime());
843 m_blockfile_info[nFile].nSize =
844 std::max(pos.nPos + added_size, m_blockfile_info[nFile].nSize);
845 m_dirty_fileinfo.insert(nFile);
846}
847
849 FlatFilePos &pos, unsigned int nAddSize) {
850 pos.nFile = nFile;
851
853
854 pos.nPos = m_blockfile_info[nFile].nUndoSize;
855 m_blockfile_info[nFile].nUndoSize += nAddSize;
856 m_dirty_fileinfo.insert(nFile);
857
858 bool out_of_space;
859 size_t bytes_allocated =
860 UndoFileSeq().Allocate(pos, nAddSize, out_of_space);
861 if (out_of_space) {
862 return FatalError(m_opts.notifications, state, "Disk space is too low!",
863 _("Disk space is too low!"));
864 }
865 if (bytes_allocated != 0 && IsPruneMode()) {
866 m_check_for_pruning = true;
867 }
868
869 return true;
870}
871
872bool BlockManager::WriteBlockUndo(const CBlockUndo &blockundo,
874 CBlockIndex &block) {
876 const BlockfileType type = BlockfileTypeForHeight(block.nHeight);
877 auto &cursor =
878 *Assert(WITH_LOCK(cs_LastBlockFile, return m_blockfile_cursors[type]));
879
880 // Write undo information to disk
881 if (block.GetUndoPos().IsNull()) {
882 FlatFilePos pos;
883 const unsigned int blockundo_size{
884 static_cast<unsigned int>(GetSerializeSize(blockundo))};
885 if (!FindUndoPos(state, block.nFile, pos,
886 blockundo_size + UNDO_DATA_DISK_OVERHEAD)) {
887 LogError("FindUndoPos failed\n");
888 return false;
889 }
890 // Open history file to append
891 AutoFile fileout{OpenUndoFile(pos)};
892 if (fileout.IsNull()) {
893 LogError("OpenUndoFile failed\n");
894 return FatalError(m_opts.notifications, state,
895 "Failed to write undo data");
896 }
897 // Write index header
898 fileout << GetParams().DiskMagic() << blockundo_size;
899
900 // Write undo data
902 fileout << blockundo;
903
904 // calculate & write checksum
905 HashWriter hasher{};
906 hasher << block.pprev->GetBlockHash();
907 hasher << blockundo;
908 fileout << hasher.GetHash();
909
910 // rev files are written in block height order, whereas blk files are
911 // written as blocks come in (often out of order) we want to flush the
912 // rev (undo) file once we've written the last block, which is indicated
913 // by the last height in the block file info as below; note that this
914 // does not catch the case where the undo writes are keeping up with the
915 // block writes (usually when a synced up node is getting newly mined
916 // blocks) -- this case is caught in the FindNextBlockPos function
917 if (pos.nFile < cursor.file_num &&
918 static_cast<uint32_t>(block.nHeight) ==
919 m_blockfile_info[pos.nFile].nHeightLast) {
920 // Do not propagate the return code, a failed flush here should not
921 // be an indication for a failed write. If it were propagated here,
922 // the caller would assume the undo data not to be written, when in
923 // fact it is. Note though, that a failed flush might leave the data
924 // file untrimmed.
925 if (!FlushUndoFile(pos.nFile, true)) {
927 "Failed to flush undo file %05i\n", pos.nFile);
928 }
929 } else if (pos.nFile == cursor.file_num &&
930 block.nHeight > cursor.undo_height) {
931 cursor.undo_height = block.nHeight;
932 }
933 // update nUndoPos in block index
934 block.nUndoPos = pos.nPos;
935 block.nStatus = block.nStatus.withUndo();
936 m_dirty_blockindex.insert(&block);
937 }
938
939 return true;
940}
941
942bool BlockManager::ReadBlock(CBlock &block, const FlatFilePos &pos) const {
943 block.SetNull();
944
945 // Open history file to read
946 AutoFile filein{OpenBlockFile(pos, true)};
947 if (filein.IsNull()) {
948 LogError("ReadBlock: OpenBlockFile failed for %s\n", pos.ToString());
949 return false;
950 }
951
952 // Read block
953 try {
954 filein >> block;
955 } catch (const std::exception &e) {
956 LogError("%s: Deserialize or I/O error - %s at %s\n", __func__,
957 e.what(), pos.ToString());
958 return false;
959 }
960
961 // Check the header
962 if (!CheckProofOfWork(block.GetHash(), block.nBits, GetConsensus())) {
963 LogError("ReadBlock: Errors in block header at %s\n", pos.ToString());
964 return false;
965 }
966
967 return true;
968}
969
970bool BlockManager::ReadBlock(CBlock &block, const CBlockIndex &index) const {
971 const FlatFilePos block_pos{WITH_LOCK(cs_main, return index.GetBlockPos())};
972
973 if (!ReadBlock(block, block_pos)) {
974 return false;
975 }
976
977 if (block.GetHash() != index.GetBlockHash()) {
978 LogError("ReadBlock(CBlock&, CBlockIndex*): GetHash() "
979 "doesn't match index for %s at %s\n",
980 index.ToString(), block_pos.ToString());
981 return false;
982 }
983
984 return true;
985}
986
987bool BlockManager::ReadRawBlock(std::vector<uint8_t> &block,
988 const FlatFilePos &pos) const {
989 FlatFilePos hpos = pos;
990 // If nPos is less than 8 the pos is null and we don't have the block data
991 // Return early to prevent undefined behavior of unsigned int underflow
992 if (hpos.nPos < 8) {
993 LogError("%s: OpenBlockFile failed for %s\n", __func__, pos.ToString());
994 return false;
995 }
996 hpos.nPos -= 8; // Seek back 8 bytes for meta header
997 AutoFile filein{OpenBlockFile(hpos, true)};
998 if (filein.IsNull()) {
999 LogError("%s: OpenBlockFile failed for %s\n", __func__, pos.ToString());
1000 return false;
1001 }
1002
1003 try {
1005 unsigned int blk_size;
1006
1007 filein >> blk_start >> blk_size;
1008
1009 if (blk_start != GetParams().DiskMagic()) {
1010 LogError("%s: Block magic mismatch for %s: %s versus expected %s\n",
1011 __func__, pos.ToString(), HexStr(blk_start),
1012 HexStr(GetParams().DiskMagic()));
1013 return false;
1014 }
1015
1016 if (blk_size > MAX_SIZE) {
1017 LogError("%s: Block data is larger than maximum deserialization "
1018 "size for %s: %s versus %s\n",
1019 __func__, pos.ToString(), blk_size, MAX_SIZE);
1020 return false;
1021 }
1022
1023 // Zeroing of memory is intentional here
1024 block.resize(blk_size);
1025 filein.read(MakeWritableByteSpan(block));
1026 } catch (const std::exception &e) {
1027 LogError("%s: Read from block file failed: %s for %s\n", __func__,
1028 e.what(), pos.ToString());
1029 return false;
1030 }
1031
1032 return true;
1033}
1034
1036 const FlatFilePos &pos) const {
1037 // Open history file to read
1038 AutoFile filein{OpenBlockFile(pos, true)};
1039 if (filein.IsNull()) {
1040 LogError("ReadTxFromDisk: OpenBlockFile failed for %s\n",
1041 pos.ToString());
1042 return false;
1043 }
1044
1045 // Read tx
1046 try {
1047 filein >> tx;
1048 } catch (const std::exception &e) {
1049 LogError("%s: Deserialize or I/O error - %s at %s\n", __func__,
1050 e.what(), pos.ToString());
1051 return false;
1052 }
1053
1054 return true;
1055}
1056
1058 const FlatFilePos &pos) const {
1059 // Open undo file to read
1060 AutoFile filein{
1061 OpenUndoFile(pos, true),
1062 };
1063 if (filein.IsNull()) {
1064 LogError("ReadTxUndoFromDisk: OpenUndoFile failed for %s\n",
1065 pos.ToString());
1066 return false;
1067 }
1068
1069 // Read undo data
1070 try {
1071 filein >> tx_undo;
1072 } catch (const std::exception &e) {
1073 LogError("%s: Deserialize or I/O error - %s at %s\n", __func__,
1074 e.what(), pos.ToString());
1075 return false;
1076 }
1077
1078 return true;
1079}
1080
1082 const unsigned int block_size{
1083 static_cast<unsigned int>(GetSerializeSize(block))};
1084 FlatFilePos pos{
1086 block.GetBlockTime())};
1087 if (pos.IsNull()) {
1088 LogError("FindNextBlockPos failed\n");
1089 return FlatFilePos();
1090 }
1091 AutoFile fileout{OpenBlockFile(pos)};
1092 if (fileout.IsNull()) {
1093 LogError("OpenBlockFile failed\n");
1094 m_opts.notifications.fatalError("Failed to write block");
1095 return FlatFilePos();
1096 }
1097
1098 // Write index header
1099 fileout << GetParams().DiskMagic() << block_size;
1100 // Write block
1102 fileout << block;
1103 return pos;
1104}
1105
1107 std::atomic<bool> &m_importing;
1108
1109public:
1110 ImportingNow(std::atomic<bool> &importing) : m_importing{importing} {
1111 assert(m_importing == false);
1112 m_importing = true;
1113 }
1115 assert(m_importing == true);
1116 m_importing = false;
1117 }
1118};
1119
1122 std::vector<fs::path> vImportFiles) {
1124
1125 {
1126 ImportingNow imp{chainman.m_blockman.m_importing};
1127
1128 // -reindex
1129 if (fReindex) {
1130 int nFile = 0;
1131 // Map of disk positions for blocks with unknown parent (only used
1132 // for reindex); parent hash -> child disk position, multiple
1133 // children can have the same parent.
1134 std::multimap<BlockHash, FlatFilePos> blocks_with_unknown_parent;
1135 while (true) {
1136 FlatFilePos pos(nFile, 0);
1137 if (!fs::exists(chainman.m_blockman.GetBlockPosFilename(pos))) {
1138 // No block files left to reindex
1139 break;
1140 }
1141 AutoFile file{chainman.m_blockman.OpenBlockFile(pos, true)};
1142 if (file.IsNull()) {
1143 // This error is logged in OpenBlockFile
1144 break;
1145 }
1146 LogPrintf("Reindexing block file blk%05u.dat...\n",
1147 (unsigned int)nFile);
1148 chainman.LoadExternalBlockFile(
1149 file, &pos, &blocks_with_unknown_parent, avalanche);
1150 if (chainman.m_interrupt) {
1151 LogPrintf("Interrupt requested. Exit %s\n", __func__);
1152 return;
1153 }
1154 nFile++;
1155 }
1156 WITH_LOCK(
1157 ::cs_main,
1158 chainman.m_blockman.m_block_tree_db->WriteReindexing(false));
1159 fReindex = false;
1160 LogPrintf("Reindexing finished\n");
1161 // To avoid ending up in a situation without genesis block, re-try
1162 // initializing (no-op if reindexing worked):
1163 chainman.ActiveChainstate().LoadGenesisBlock();
1164 }
1165
1166 // -loadblock=
1167 for (const fs::path &path : vImportFiles) {
1168 AutoFile file{fsbridge::fopen(path, "rb")};
1169 if (!file.IsNull()) {
1170 LogPrintf("Importing blocks file %s...\n",
1171 fs::PathToString(path));
1172 chainman.LoadExternalBlockFile(
1173 file, /*dbp=*/nullptr,
1174 /*blocks_with_unknown_parent=*/nullptr, avalanche);
1175 if (chainman.m_interrupt) {
1176 LogPrintf("Interrupt requested. Exit %s\n", __func__);
1177 return;
1178 }
1179 } else {
1180 LogPrintf("Warning: Could not open blocks file %s\n",
1181 fs::PathToString(path));
1182 }
1183 }
1184
1185 // Reconsider blocks we know are valid. They may have been marked
1186 // invalid by, for instance, running an outdated version of the node
1187 // software.
1188 const MapCheckpoints &checkpoints =
1190 for (const MapCheckpoints::value_type &i : checkpoints) {
1191 const BlockHash &hash = i.second;
1192
1193 LOCK(cs_main);
1194 CBlockIndex *pblockindex =
1195 chainman.m_blockman.LookupBlockIndex(hash);
1196 if (pblockindex && !pblockindex->nStatus.isValid()) {
1197 LogPrintf("Reconsidering checkpointed block %s ...\n",
1198 hash.GetHex());
1199 chainman.ActiveChainstate().ResetBlockFailureFlags(pblockindex);
1200 }
1201
1202 if (pblockindex && pblockindex->nStatus.isOnParkedChain()) {
1203 LogPrintf("Unparking checkpointed block %s ...\n",
1204 hash.GetHex());
1205 chainman.ActiveChainstate().UnparkBlockAndChildren(pblockindex);
1206 }
1207 }
1208
1209 // scan for better chains in the block chain database, that are not yet
1210 // connected in the active best chain
1211
1212 // We can't hold cs_main during ActivateBestChain even though we're
1213 // accessing the chainman unique_ptrs since ABC requires us not to be
1214 // holding cs_main, so retrieve the relevant pointers before the ABC
1215 // call.
1216 for (Chainstate *chainstate :
1217 WITH_LOCK(::cs_main, return chainman.GetAll())) {
1219 if (!chainstate->ActivateBestChain(state, nullptr, avalanche)) {
1221 "Failed to connect best block (%s)", state.ToString()));
1222 return;
1223 }
1224 }
1225
1226 if (chainman.m_blockman.StopAfterBlockImport()) {
1227 LogPrintf("Stopping after block import\n");
1228 StartShutdown();
1229 return;
1230 }
1231 } // End scope of ImportingNow
1232}
1233
1234std::ostream &operator<<(std::ostream &os, const BlockfileType &type) {
1235 switch (type) {
1236 case BlockfileType::NORMAL:
1237 os << "normal";
1238 break;
1240 os << "assumed";
1241 break;
1242 default:
1243 os.setstate(std::ios_base::failbit);
1244 }
1245 return os;
1246}
1247
1248std::ostream &operator<<(std::ostream &os, const BlockfileCursor &cursor) {
1249 os << strprintf("BlockfileCursor(file_num=%d, undo_height=%d)",
1250 cursor.file_num, cursor.undo_height);
1251 return os;
1252}
1253} // 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:733
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:832
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1185
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:1436
kernel::Notifications & GetNotifications() const
Definition: validation.h:1293
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:1321
const CChainParams & GetParams() const
Definition: validation.h:1278
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1402
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:1326
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.
bool 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::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: init.h:31
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:46
reverse_range< T > reverse_iterate(T &x)
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
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:108
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
Definition: tests.c:31
#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:105
#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
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
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