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