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