Bitcoin ABC 0.31.0
P2P Digital Currency
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
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 <shutdown.h>
22#include <streams.h>
23#include <undo.h>
24#include <util/batchpriority.h>
25#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 return false;
267 }
268
269 if (snapshot_blockhash) {
270 const AssumeutxoData au_data =
271 *Assert(GetParams().AssumeutxoForBlockhash(*snapshot_blockhash));
272 m_snapshot_height = au_data.height;
273 CBlockIndex *base{LookupBlockIndex(*snapshot_blockhash)};
274
275 // Since nChainTx (responsible for estimated progress) isn't persisted
276 // to disk, we must bootstrap the value for assumedvalid chainstates
277 // from the hardcoded assumeutxo chainparams.
278 base->nChainTx = au_data.nChainTx;
279 LogPrintf("[snapshot] set nChainTx=%d for %s\n", au_data.nChainTx,
280 snapshot_blockhash->ToString());
281 } else {
282 // If this isn't called with a snapshot blockhash, make sure the cached
283 // snapshot height is null. This is relevant during snapshot
284 // completion, when the blockman may be loaded with a height that then
285 // needs to be cleared after the snapshot is fully validated.
286 m_snapshot_height.reset();
287 }
288
289 Assert(m_snapshot_height.has_value() == snapshot_blockhash.has_value());
290
291 // Calculate nChainWork
292 std::vector<CBlockIndex *> vSortedByHeight{GetAllBlockIndices()};
293 std::sort(vSortedByHeight.begin(), vSortedByHeight.end(),
295
296 for (CBlockIndex *pindex : vSortedByHeight) {
297 if (ShutdownRequested()) {
298 return false;
299 }
300 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) +
301 GetBlockProof(*pindex);
302 pindex->nTimeMax =
303 (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime)
304 : pindex->nTime);
305
306 // We can link the chain of blocks for which we've received
307 // transactions at some point, or blocks that are assumed-valid on the
308 // basis of snapshot load (see PopulateAndValidateSnapshot()).
309 // Pruned nodes may have deleted the block.
310 if (pindex->nTx > 0) {
311 if (m_snapshot_height && pindex->nHeight == *m_snapshot_height &&
312 pindex->GetBlockHash() == *snapshot_blockhash) {
313 Assert(pindex->pprev);
314 // Should have been set above; don't disturb it with code below.
315 Assert(pindex->nChainTx > 0);
316 } else if (!pindex->UpdateChainStats() && pindex->pprev) {
317 m_blocks_unlinked.insert(std::make_pair(pindex->pprev, pindex));
318 pindex->ResetChainStats();
319 }
320 }
321
322 if (!pindex->nStatus.hasFailed() && pindex->pprev &&
323 pindex->pprev->nStatus.hasFailed()) {
324 pindex->nStatus = pindex->nStatus.withFailedParent();
325 m_dirty_blockindex.insert(pindex);
326 }
327
328 if (pindex->pprev) {
329 pindex->BuildSkip();
330 }
331 }
332
333 return true;
334}
335
336bool BlockManager::WriteBlockIndexDB() {
337 std::vector<std::pair<int, const CBlockFileInfo *>> vFiles;
338 vFiles.reserve(m_dirty_fileinfo.size());
339 for (int i : m_dirty_fileinfo) {
340 vFiles.push_back(std::make_pair(i, &m_blockfile_info[i]));
341 }
342
343 m_dirty_fileinfo.clear();
344
345 std::vector<const CBlockIndex *> vBlocks;
346 vBlocks.reserve(m_dirty_blockindex.size());
347 for (const CBlockIndex *cbi : m_dirty_blockindex) {
348 vBlocks.push_back(cbi);
349 }
350
351 m_dirty_blockindex.clear();
352
353 int max_blockfile =
355 if (!m_block_tree_db->WriteBatchSync(vFiles, max_blockfile, vBlocks)) {
356 return false;
357 }
358 return true;
359}
360
361bool BlockManager::LoadBlockIndexDB(
362 const std::optional<BlockHash> &snapshot_blockhash) {
363 if (!LoadBlockIndex(snapshot_blockhash)) {
364 return false;
365 }
366 int max_blockfile_num{0};
367
368 // Load block file info
369 m_block_tree_db->ReadLastBlockFile(max_blockfile_num);
370 m_blockfile_info.resize(max_blockfile_num + 1);
371 LogPrintf("%s: last block file = %i\n", __func__, max_blockfile_num);
372 for (int nFile = 0; nFile <= max_blockfile_num; nFile++) {
373 m_block_tree_db->ReadBlockFileInfo(nFile, m_blockfile_info[nFile]);
374 }
375 LogPrintf("%s: last block file info: %s\n", __func__,
376 m_blockfile_info[max_blockfile_num].ToString());
377 for (int nFile = max_blockfile_num + 1; true; nFile++) {
378 CBlockFileInfo info;
379 if (m_block_tree_db->ReadBlockFileInfo(nFile, info)) {
380 m_blockfile_info.push_back(info);
381 } else {
382 break;
383 }
384 }
385
386 // Check presence of blk files
387 LogPrintf("Checking all blk files are present...\n");
388 std::set<int> setBlkDataFiles;
389 for (const auto &[_, block_index] : m_block_index) {
390 if (block_index.nStatus.hasData()) {
391 setBlkDataFiles.insert(block_index.nFile);
392 }
393 }
394
395 for (const int i : setBlkDataFiles) {
396 FlatFilePos pos(i, 0);
398 .IsNull()) {
399 return false;
400 }
401 }
402
403 {
404 // Initialize the blockfile cursors.
406 for (size_t i = 0; i < m_blockfile_info.size(); ++i) {
407 const auto last_height_in_file = m_blockfile_info[i].nHeightLast;
408 m_blockfile_cursors[BlockfileTypeForHeight(last_height_in_file)] = {
409 static_cast<int>(i), 0};
410 }
411 }
412
413 // Check whether we have ever pruned block & undo files
414 m_block_tree_db->ReadFlag("prunedblockfiles", m_have_pruned);
415 if (m_have_pruned) {
416 LogPrintf(
417 "LoadBlockIndexDB(): Block files have previously been pruned\n");
418 }
419
420 // Check whether we need to continue reindexing
421 if (m_block_tree_db->IsReindexing()) {
422 fReindex = true;
423 }
424
425 return true;
426}
427
428void BlockManager::ScanAndUnlinkAlreadyPrunedFiles() {
430 int max_blockfile =
432 if (!m_have_pruned) {
433 return;
434 }
435
436 std::set<int> block_files_to_prune;
437 for (int file_number = 0; file_number < max_blockfile; file_number++) {
438 if (m_blockfile_info[file_number].nSize == 0) {
439 block_files_to_prune.insert(file_number);
440 }
441 }
442
443 UnlinkPrunedFiles(block_files_to_prune);
444}
445
446const CBlockIndex *
448 const MapCheckpoints &checkpoints = data.mapCheckpoints;
449
450 for (const MapCheckpoints::value_type &i : reverse_iterate(checkpoints)) {
451 const BlockHash &hash = i.second;
452 const CBlockIndex *pindex = LookupBlockIndex(hash);
453 if (pindex) {
454 return pindex;
455 }
456 }
457
458 return nullptr;
459}
460
461bool BlockManager::IsBlockPruned(const CBlockIndex *pblockindex) {
463 return (m_have_pruned && !pblockindex->nStatus.hasData() &&
464 pblockindex->nTx > 0);
465}
466
467const CBlockIndex *
468BlockManager::GetFirstStoredBlock(const CBlockIndex &upper_block,
469 const CBlockIndex *lower_block) {
471 const CBlockIndex *last_block = &upper_block;
472 // 'upper_block' must have data
473 assert(last_block->nStatus.hasData());
474 while (last_block->pprev && (last_block->pprev->nStatus.hasData())) {
475 if (lower_block) {
476 // Return if we reached the lower_block
477 if (last_block == lower_block) {
478 return lower_block;
479 }
480 // if range was surpassed, means that 'lower_block' is not part of
481 // the 'upper_block' chain and so far this is not allowed.
482 assert(last_block->nHeight >= lower_block->nHeight);
483 }
484 last_block = last_block->pprev;
485 }
486 assert(last_block != nullptr);
487 return last_block;
488}
489
490bool BlockManager::CheckBlockDataAvailability(const CBlockIndex &upper_block,
491 const CBlockIndex &lower_block) {
492 if (!(upper_block.nStatus.hasData())) {
493 return false;
494 }
495 return GetFirstStoredBlock(upper_block, &lower_block) == &lower_block;
496}
497
498// If we're using -prune with -reindex, then delete block files that will be
499// ignored by the reindex. Since reindexing works by starting at block file 0
500// and looping until a blockfile is missing, do the same here to delete any
501// later block files after a gap. Also delete all rev files since they'll be
502// rewritten by the reindex anyway. This ensures that m_blockfile_info is in
503// sync with what's actually on disk by the time we start downloading, so that
504// pruning works correctly.
506 std::map<std::string, fs::path> mapBlockFiles;
507
508 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
509 // Remove the rev files immediately and insert the blk file paths into an
510 // ordered map keyed by block file index.
511 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for "
512 "-reindex with -prune\n");
513 for (const auto &file : fs::directory_iterator{m_opts.blocks_dir}) {
514 const std::string path = fs::PathToString(file.path().filename());
515 if (fs::is_regular_file(file) && path.length() == 12 &&
516 path.substr(8, 4) == ".dat") {
517 if (path.substr(0, 3) == "blk") {
518 mapBlockFiles[path.substr(3, 5)] = file.path();
519 } else if (path.substr(0, 3) == "rev") {
520 remove(file.path());
521 }
522 }
523 }
524
525 // Remove all block files that aren't part of a contiguous set starting at
526 // zero by walking the ordered map (keys are block file indices) by keeping
527 // a separate counter. Once we hit a gap (or if 0 doesn't exist) start
528 // removing block files.
529 int contiguousCounter = 0;
530 for (const auto &item : mapBlockFiles) {
531 if (atoi(item.first) == contiguousCounter) {
532 contiguousCounter++;
533 continue;
534 }
535 remove(item.second);
536 }
537}
538
541
542 return &m_blockfile_info.at(n);
543}
544
546 const CBlockUndo &blockundo, FlatFilePos &pos, const BlockHash &hashBlock,
547 const CMessageHeader::MessageMagic &messageStart) const {
548 // Open history file to append
550 if (fileout.IsNull()) {
551 return error("%s: OpenUndoFile failed", __func__);
552 }
553
554 // Write index header
555 unsigned int nSize = GetSerializeSize(blockundo, fileout.GetVersion());
556 fileout << messageStart << nSize;
557
558 // Write undo data
559 long fileOutPos = ftell(fileout.Get());
560 if (fileOutPos < 0) {
561 return error("%s: ftell failed", __func__);
562 }
563 pos.nPos = (unsigned int)fileOutPos;
564 fileout << blockundo;
565
566 // calculate & write checksum
567 HashWriter hasher{};
568 hasher << hashBlock;
569 hasher << blockundo;
570 fileout << hasher.GetHash();
571
572 return true;
573}
574
576 const CBlockIndex &index) const {
577 const FlatFilePos pos{WITH_LOCK(::cs_main, return index.GetUndoPos())};
578
579 if (pos.IsNull()) {
580 return error("%s: no undo data available", __func__);
581 }
582
583 // Open history file to read
584 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
585 if (filein.IsNull()) {
586 return error("%s: OpenUndoFile failed", __func__);
587 }
588
589 // Read block
590 uint256 hashChecksum;
591 // We need a CHashVerifier as reserializing may lose data
592 CHashVerifier<CAutoFile> verifier(&filein);
593 try {
594 verifier << index.pprev->GetBlockHash();
595 verifier >> blockundo;
596 filein >> hashChecksum;
597 } catch (const std::exception &e) {
598 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
599 }
600
601 // Verify checksum
602 if (hashChecksum != verifier.GetHash()) {
603 return error("%s: Checksum mismatch", __func__);
604 }
605
606 return true;
607}
608
609bool BlockManager::FlushUndoFile(int block_file, bool finalize) {
610 FlatFilePos undo_pos_old(block_file,
611 m_blockfile_info[block_file].nUndoSize);
612 if (!UndoFileSeq().Flush(undo_pos_old, finalize)) {
613 return AbortNode(
614 "Flushing undo file to disk failed. This is likely the "
615 "result of an I/O error.");
616 }
617 return true;
618}
619
620bool BlockManager::FlushBlockFile(int blockfile_num, bool fFinalize,
621 bool finalize_undo) {
622 bool success = true;
624
625 if (m_blockfile_info.empty()) {
626 // Return if we haven't loaded any blockfiles yet. This happens during
627 // chainstate init, when we call
628 // ChainstateManager::MaybeRebalanceCaches() (which then calls
629 // FlushStateToDisk()), resulting in a call to this function before we
630 // have populated `m_blockfile_info` via LoadBlockIndexDB().
631 return true;
632 }
633 assert(static_cast<int>(m_blockfile_info.size()) > blockfile_num);
634
635 FlatFilePos block_pos_old(blockfile_num,
636 m_blockfile_info[blockfile_num].nSize);
637 if (!BlockFileSeq().Flush(block_pos_old, fFinalize)) {
638 AbortNode("Flushing block file to disk failed. This is likely the "
639 "result of an I/O error.");
640 success = false;
641 }
642 // we do not always flush the undo file, as the chain tip may be lagging
643 // behind the incoming blocks,
644 // e.g. during IBD or a sync after a node going offline
645 if (!fFinalize || finalize_undo) {
646 if (!FlushUndoFile(blockfile_num, finalize_undo)) {
647 success = false;
648 }
649 }
650 return success;
651}
652
654 if (!m_snapshot_height) {
655 return BlockfileType::NORMAL;
656 }
657 return (height >= *m_snapshot_height) ? BlockfileType::ASSUMED
658 : BlockfileType::NORMAL;
659}
660
663 auto &cursor = m_blockfile_cursors[BlockfileTypeForHeight(tip_height)];
664 // If the cursor does not exist, it means an assumeutxo snapshot is loaded,
665 // but no blocks past the snapshot height have been written yet, so there
666 // is no data associated with the chainstate, and it is safe not to flush.
667 if (cursor) {
668 return FlushBlockFile(cursor->file_num, /*fFinalize=*/false,
669 /*finalize_undo=*/false);
670 }
671 // No need to log warnings in this case.
672 return true;
673}
674
677
678 uint64_t retval = 0;
679 for (const CBlockFileInfo &file : m_blockfile_info) {
680 retval += file.nSize + file.nUndoSize;
681 }
682
683 return retval;
684}
685
687 const std::set<int> &setFilesToPrune) const {
688 std::error_code error_code;
689 for (const int i : setFilesToPrune) {
690 FlatFilePos pos(i, 0);
691 const bool removed_blockfile{
692 fs::remove(BlockFileSeq().FileName(pos), error_code)};
693 const bool removed_undofile{
694 fs::remove(UndoFileSeq().FileName(pos), error_code)};
695 if (removed_blockfile || removed_undofile) {
696 LogPrint(BCLog::BLOCKSTORE, "Prune: %s deleted blk/rev (%05u)\n",
697 __func__, i);
698 }
699 }
700}
701
703 return FlatFileSeq(m_opts.blocks_dir, "blk",
704 m_opts.fast_prune ? 0x4000 /* 16kb */
706}
707
710}
711
713 bool fReadOnly) const {
714 return BlockFileSeq().Open(pos, fReadOnly);
715}
716
718FILE *BlockManager::OpenUndoFile(const FlatFilePos &pos, bool fReadOnly) const {
719 return UndoFileSeq().Open(pos, fReadOnly);
720}
721
723 return BlockFileSeq().FileName(pos);
724}
725
726bool BlockManager::FindBlockPos(FlatFilePos &pos, unsigned int nAddSize,
727 unsigned int nHeight, uint64_t nTime,
728 bool fKnown) {
730
731 const BlockfileType chain_type = BlockfileTypeForHeight(nHeight);
732
733 if (!m_blockfile_cursors[chain_type]) {
734 // If a snapshot is loaded during runtime, we may not have initialized
735 // this cursor yet.
736 assert(chain_type == BlockfileType::ASSUMED);
737 const auto new_cursor = BlockfileCursor{this->MaxBlockfileNum() + 1};
738 m_blockfile_cursors[chain_type] = new_cursor;
740 "[%s] initializing blockfile cursor to %s\n", chain_type,
741 new_cursor);
742 }
743 const int last_blockfile = m_blockfile_cursors[chain_type]->file_num;
744
745 int nFile = fKnown ? pos.nFile : last_blockfile;
746 if (static_cast<int>(m_blockfile_info.size()) <= nFile) {
747 m_blockfile_info.resize(nFile + 1);
748 }
749
750 bool finalize_undo = false;
751 if (!fKnown) {
752 unsigned int max_blockfile_size{MAX_BLOCKFILE_SIZE};
753 // Use smaller blockfiles in test-only -fastprune mode - but avoid
754 // the possibility of having a block not fit into the block file.
755 if (m_opts.fast_prune) {
756 max_blockfile_size = 0x10000; // 64kiB
757 if (nAddSize >= max_blockfile_size) {
758 // dynamically adjust the blockfile size to be larger than the
759 // added size
760 max_blockfile_size = nAddSize + 1;
761 }
762 }
763 // TODO: we will also need to dynamically adjust the blockfile size
764 // or raise MAX_BLOCKFILE_SIZE when we reach block sizes larger than
765 // 128 MiB
766 assert(nAddSize < max_blockfile_size);
767
768 while (m_blockfile_info[nFile].nSize + nAddSize >= max_blockfile_size) {
769 // when the undo file is keeping up with the block file, we want to
770 // flush it explicitly when it is lagging behind (more blocks arrive
771 // than are being connected), we let the undo block write case
772 // handle it
773 finalize_undo =
774 (static_cast<int>(m_blockfile_info[nFile].nHeightLast) ==
775 Assert(m_blockfile_cursors[chain_type])->undo_height);
776
777 // Try the next unclaimed blockfile number
778 nFile = this->MaxBlockfileNum() + 1;
779 // Set to increment MaxBlockfileNum() for next iteration
780 m_blockfile_cursors[chain_type] = BlockfileCursor{nFile};
781
782 if (static_cast<int>(m_blockfile_info.size()) <= nFile) {
783 m_blockfile_info.resize(nFile + 1);
784 }
785 }
786 pos.nFile = nFile;
787 pos.nPos = m_blockfile_info[nFile].nSize;
788 }
789
790 if (nFile != last_blockfile) {
791 if (!fKnown) {
793 "Leaving block file %i: %s (onto %i) (height %i)\n",
794 last_blockfile,
795 m_blockfile_info[last_blockfile].ToString(), nFile,
796 nHeight);
797 }
798
799 // Do not propagate the return code. The flush concerns a previous block
800 // and undo file that has already been written to. If a flush fails
801 // here, and we crash, there is no expected additional block data
802 // inconsistency arising from the flush failure here. However, the undo
803 // data may be inconsistent after a crash if the flush is called during
804 // a reindex. A flush error might also leave some of the data files
805 // untrimmed.
806 if (!FlushBlockFile(last_blockfile, !fKnown, finalize_undo)) {
809 "Failed to flush previous block file %05i (finalize=%i, "
810 "finalize_undo=%i) before opening new block file %05i\n",
811 last_blockfile, !fKnown, finalize_undo, nFile);
812 }
813 // No undo data yet in the new file, so reset our undo-height tracking.
814 m_blockfile_cursors[chain_type] = BlockfileCursor{nFile};
815 }
816
817 m_blockfile_info[nFile].AddBlock(nHeight, nTime);
818 if (fKnown) {
819 m_blockfile_info[nFile].nSize =
820 std::max(pos.nPos + nAddSize, m_blockfile_info[nFile].nSize);
821 } else {
822 m_blockfile_info[nFile].nSize += nAddSize;
823 }
824
825 if (!fKnown) {
826 bool out_of_space;
827 size_t bytes_allocated =
828 BlockFileSeq().Allocate(pos, nAddSize, out_of_space);
829 if (out_of_space) {
830 return AbortNode("Disk space is too low!",
831 _("Disk space is too low!"));
832 }
833 if (bytes_allocated != 0 && IsPruneMode()) {
834 m_check_for_pruning = true;
835 }
836 }
837
838 m_dirty_fileinfo.insert(nFile);
839 return true;
840}
841
843 FlatFilePos &pos, unsigned int nAddSize) {
844 pos.nFile = nFile;
845
847
848 pos.nPos = m_blockfile_info[nFile].nUndoSize;
849 m_blockfile_info[nFile].nUndoSize += nAddSize;
850 m_dirty_fileinfo.insert(nFile);
851
852 bool out_of_space;
853 size_t bytes_allocated =
854 UndoFileSeq().Allocate(pos, nAddSize, out_of_space);
855 if (out_of_space) {
856 return AbortNode(state, "Disk space is too low!",
857 _("Disk space is too low!"));
858 }
859 if (bytes_allocated != 0 && IsPruneMode()) {
860 m_check_for_pruning = true;
861 }
862
863 return true;
864}
865
867 const CBlock &block, FlatFilePos &pos,
868 const CMessageHeader::MessageMagic &messageStart) const {
869 // Open history file to append
871 if (fileout.IsNull()) {
872 return error("WriteBlockToDisk: OpenBlockFile failed");
873 }
874
875 // Write index header
876 unsigned int nSize = GetSerializeSize(block, fileout.GetVersion());
877 fileout << messageStart << nSize;
878
879 // Write block
880 long fileOutPos = ftell(fileout.Get());
881 if (fileOutPos < 0) {
882 return error("WriteBlockToDisk: ftell failed");
883 }
884
885 pos.nPos = (unsigned int)fileOutPos;
886 fileout << block;
887
888 return true;
889}
890
891bool BlockManager::WriteUndoDataForBlock(const CBlockUndo &blockundo,
893 CBlockIndex &block) {
895 const BlockfileType type = BlockfileTypeForHeight(block.nHeight);
896 auto &cursor =
897 *Assert(WITH_LOCK(cs_LastBlockFile, return m_blockfile_cursors[type]));
898
899 // Write undo information to disk
900 if (block.GetUndoPos().IsNull()) {
901 FlatFilePos _pos;
902 if (!FindUndoPos(state, block.nFile, _pos,
903 ::GetSerializeSize(blockundo, CLIENT_VERSION) + 40)) {
904 return error("ConnectBlock(): FindUndoPos failed");
905 }
906 if (!UndoWriteToDisk(blockundo, _pos, block.pprev->GetBlockHash(),
907 GetParams().DiskMagic())) {
908 return AbortNode(state, "Failed to write undo data");
909 }
910 // rev files are written in block height order, whereas blk files are
911 // written as blocks come in (often out of order) we want to flush the
912 // rev (undo) file once we've written the last block, which is indicated
913 // by the last height in the block file info as below; note that this
914 // does not catch the case where the undo writes are keeping up with the
915 // block writes (usually when a synced up node is getting newly mined
916 // blocks) -- this case is caught in the FindBlockPos function
917 if (_pos.nFile < cursor.file_num &&
918 static_cast<uint32_t>(block.nHeight) ==
919 m_blockfile_info[_pos.nFile].nHeightLast) {
920 // Do not propagate the return code, a failed flush here should not
921 // be an indication for a failed write. If it were propagated here,
922 // the caller would assume the undo data not to be written, when in
923 // fact it is. Note though, that a failed flush might leave the data
924 // file untrimmed.
925 if (!FlushUndoFile(_pos.nFile, true)) {
927 "Failed to flush undo file %05i\n", _pos.nFile);
928 }
929 } else if (_pos.nFile == cursor.file_num &&
930 block.nHeight > cursor.undo_height) {
931 cursor.undo_height = block.nHeight;
932 }
933 // update nUndoPos in block index
934 block.nUndoPos = _pos.nPos;
935 block.nStatus = block.nStatus.withUndo();
936 m_dirty_blockindex.insert(&block);
937 }
938
939 return true;
940}
941
943 const FlatFilePos &pos) const {
944 block.SetNull();
945
946 // Open history file to read
947 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
948 if (filein.IsNull()) {
949 return error("ReadBlockFromDisk: OpenBlockFile failed for %s",
950 pos.ToString());
951 }
952
953 // Read block
954 try {
955 filein >> block;
956 } catch (const std::exception &e) {
957 return error("%s: Deserialize or I/O error - %s at %s", __func__,
958 e.what(), pos.ToString());
959 }
960
961 // Check the header
962 if (!CheckProofOfWork(block.GetHash(), block.nBits, GetConsensus())) {
963 return error("ReadBlockFromDisk: Errors in block header at %s",
964 pos.ToString());
965 }
966
967 return true;
968}
969
971 const CBlockIndex &index) const {
972 const FlatFilePos block_pos{WITH_LOCK(cs_main, return index.GetBlockPos())};
973
974 if (!ReadBlockFromDisk(block, block_pos)) {
975 return false;
976 }
977
978 if (block.GetHash() != index.GetBlockHash()) {
979 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() "
980 "doesn't match index for %s at %s",
981 index.ToString(), block_pos.ToString());
982 }
983
984 return true;
985}
986
988 const FlatFilePos &pos) const {
989 // Open history file to read
990 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
991 if (filein.IsNull()) {
992 return error("ReadTxFromDisk: OpenBlockFile failed for %s",
993 pos.ToString());
994 }
995
996 // Read tx
997 try {
998 filein >> tx;
999 } catch (const std::exception &e) {
1000 return error("%s: Deserialize or I/O error - %s at %s", __func__,
1001 e.what(), pos.ToString());
1002 }
1003
1004 return true;
1005}
1006
1008 const FlatFilePos &pos) const {
1009 // Open undo file to read
1010 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1011 if (filein.IsNull()) {
1012 return error("ReadTxUndoFromDisk: OpenUndoFile failed for %s",
1013 pos.ToString());
1014 }
1015
1016 // Read undo data
1017 try {
1018 filein >> tx_undo;
1019 } catch (const std::exception &e) {
1020 return error("%s: Deserialize or I/O error - %s at %s", __func__,
1021 e.what(), pos.ToString());
1022 }
1023
1024 return true;
1025}
1026
1028 const FlatFilePos *dbp) {
1029 unsigned int nBlockSize = ::GetSerializeSize(block, CLIENT_VERSION);
1030 FlatFilePos blockPos;
1031 const auto position_known{dbp != nullptr};
1032 if (position_known) {
1033 blockPos = *dbp;
1034 } else {
1035 // When known, blockPos.nPos points at the offset of the block data in
1036 // the blk file. That already accounts for the serialization header
1037 // present in the file (the 4 magic message start bytes + the 4 length
1038 // bytes = 8 bytes = BLOCK_SERIALIZATION_HEADER_SIZE). We add
1039 // BLOCK_SERIALIZATION_HEADER_SIZE only for new blocks since they will
1040 // have the serialization header added when written to disk.
1041 nBlockSize +=
1042 static_cast<unsigned int>(BLOCK_SERIALIZATION_HEADER_SIZE);
1043 }
1044 if (!FindBlockPos(blockPos, nBlockSize, nHeight, block.GetBlockTime(),
1045 position_known)) {
1046 error("%s: FindBlockPos failed", __func__);
1047 return FlatFilePos();
1048 }
1049 if (!position_known) {
1050 if (!WriteBlockToDisk(block, blockPos, GetParams().DiskMagic())) {
1051 AbortNode("Failed to write block");
1052 return FlatFilePos();
1053 }
1054 }
1055 return blockPos;
1056}
1057
1059 std::atomic<bool> &m_importing;
1060
1061public:
1062 ImportingNow(std::atomic<bool> &importing) : m_importing{importing} {
1063 assert(m_importing == false);
1064 m_importing = true;
1065 }
1067 assert(m_importing == true);
1068 m_importing = false;
1069 }
1070};
1071
1074 std::vector<fs::path> vImportFiles) {
1076
1077 {
1078 ImportingNow imp{chainman.m_blockman.m_importing};
1079
1080 // -reindex
1081 if (fReindex) {
1082 int nFile = 0;
1083 // Map of disk positions for blocks with unknown parent (only used
1084 // for reindex); parent hash -> child disk position, multiple
1085 // children can have the same parent.
1086 std::multimap<BlockHash, FlatFilePos> blocks_with_unknown_parent;
1087 while (true) {
1088 FlatFilePos pos(nFile, 0);
1089 if (!fs::exists(chainman.m_blockman.GetBlockPosFilename(pos))) {
1090 // No block files left to reindex
1091 break;
1092 }
1093 FILE *file = chainman.m_blockman.OpenBlockFile(pos, true);
1094 if (!file) {
1095 // This error is logged in OpenBlockFile
1096 break;
1097 }
1098 LogPrintf("Reindexing block file blk%05u.dat...\n",
1099 (unsigned int)nFile);
1100 chainman.LoadExternalBlockFile(
1101 file, &pos, &blocks_with_unknown_parent, avalanche);
1102 if (ShutdownRequested()) {
1103 LogPrintf("Shutdown requested. Exit %s\n", __func__);
1104 return;
1105 }
1106 nFile++;
1107 }
1108 WITH_LOCK(
1109 ::cs_main,
1110 chainman.m_blockman.m_block_tree_db->WriteReindexing(false));
1111 fReindex = false;
1112 LogPrintf("Reindexing finished\n");
1113 // To avoid ending up in a situation without genesis block, re-try
1114 // initializing (no-op if reindexing worked):
1115 chainman.ActiveChainstate().LoadGenesisBlock();
1116 }
1117
1118 // -loadblock=
1119 for (const fs::path &path : vImportFiles) {
1120 FILE *file = fsbridge::fopen(path, "rb");
1121 if (file) {
1122 LogPrintf("Importing blocks file %s...\n",
1123 fs::PathToString(path));
1124 chainman.LoadExternalBlockFile(
1125 file, /*dbp=*/nullptr,
1126 /*blocks_with_unknown_parent=*/nullptr, avalanche);
1127 if (ShutdownRequested()) {
1128 LogPrintf("Shutdown requested. Exit %s\n", __func__);
1129 return;
1130 }
1131 } else {
1132 LogPrintf("Warning: Could not open blocks file %s\n",
1133 fs::PathToString(path));
1134 }
1135 }
1136
1137 // Reconsider blocks we know are valid. They may have been marked
1138 // invalid by, for instance, running an outdated version of the node
1139 // software.
1140 const MapCheckpoints &checkpoints =
1142 for (const MapCheckpoints::value_type &i : checkpoints) {
1143 const BlockHash &hash = i.second;
1144
1145 LOCK(cs_main);
1146 CBlockIndex *pblockindex =
1147 chainman.m_blockman.LookupBlockIndex(hash);
1148 if (pblockindex && !pblockindex->nStatus.isValid()) {
1149 LogPrintf("Reconsidering checkpointed block %s ...\n",
1150 hash.GetHex());
1151 chainman.ActiveChainstate().ResetBlockFailureFlags(pblockindex);
1152 }
1153
1154 if (pblockindex && pblockindex->nStatus.isOnParkedChain()) {
1155 LogPrintf("Unparking checkpointed block %s ...\n",
1156 hash.GetHex());
1157 chainman.ActiveChainstate().UnparkBlockAndChildren(pblockindex);
1158 }
1159 }
1160
1161 // scan for better chains in the block chain database, that are not yet
1162 // connected in the active best chain
1163
1164 // We can't hold cs_main during ActivateBestChain even though we're
1165 // accessing the chainman unique_ptrs since ABC requires us not to be
1166 // holding cs_main, so retrieve the relevant pointers before the ABC
1167 // call.
1168 for (Chainstate *chainstate :
1169 WITH_LOCK(::cs_main, return chainman.GetAll())) {
1171 if (!chainstate->ActivateBestChain(state, nullptr, avalanche)) {
1172 LogPrintf("Failed to connect best block (%s)\n",
1173 state.ToString());
1174 StartShutdown();
1175 return;
1176 }
1177 }
1178
1179 if (chainman.m_blockman.StopAfterBlockImport()) {
1180 LogPrintf("Stopping after block import\n");
1181 StartShutdown();
1182 return;
1183 }
1184 } // End scope of ImportingNow
1185}
1186
1187std::ostream &operator<<(std::ostream &os, const BlockfileType &type) {
1188 switch (type) {
1189 case BlockfileType::NORMAL:
1190 os << "normal";
1191 break;
1193 os << "assumed";
1194 break;
1195 default:
1196 os.setstate(std::ios_base::failbit);
1197 }
1198 return os;
1199}
1200
1201std::ostream &operator<<(std::ostream &os, const BlockfileCursor &cursor) {
1202 os << strprintf("BlockfileCursor(file_num=%d, undo_height=%d)",
1203 cursor.file_num, cursor.undo_height);
1204 return os;
1205}
1206} // 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
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
Definition: streams.h:570
FILE * Get() const
Get wrapped FILE* without transfer of ownership.
Definition: streams.h:567
int GetVersion() const
Definition: streams.h:640
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:80
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:107
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:218
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:119
const CCheckpointData & Checkpoints() const
Definition: chainparams.h:139
Reads data from an underlying stream, while hashing the read data.
Definition: hash.h:170
std::array< uint8_t, MESSAGE_START_SIZE > MessageMagic
Definition: protocol.h:46
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:700
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:799
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1147
SnapshotCompletionResult MaybeCompleteSnapshotValidation(std::function< void(bilingual_str)> shutdown_fnc=[](bilingual_str msg) { AbortNode(msg.original, msg);}) 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:1389
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 CChainParams & GetParams() const
Definition: validation.h:1233
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1353
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1279
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:51
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
const kernel::BlockManagerOpts m_opts
Definition: blockstorage.h:236
std::set< int > m_dirty_fileinfo
Dirty block file entries.
Definition: blockstorage.h:222
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
FlatFileSeq UndoFileSeq() const
RecursiveMutex cs_LastBlockFile
Definition: blockstorage.h:181
bool CheckBlockDataAvailability(const CBlockIndex &upper_block LIFETIMEBOUND, const CBlockIndex &lower_block LIFETIMEBOUND) EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetFirstStoredBlock(const CBlockIndex &start_block LIFETIMEBOUND, const CBlockIndex *lower_block=nullptr) EXCLUSIVE_LOCKS_REQUIRED(boo m_have_pruned)
Check if all blocks in the [upper_block, lower_block] range have data available.
Definition: blockstorage.h:357
const CChainParams & GetParams() const
Definition: blockstorage.h:108
bool WriteUndoDataForBlock(const CBlockUndo &blockundo, BlockValidationState &state, CBlockIndex &block) EXCLUSIVE_LOCKS_REQUIRED(FlatFilePos SaveBlockToDisk(const CBlock &block, int nHeight, const FlatFilePos *dbp)
Store block on disk.
Definition: blockstorage.h:312
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...
FlatFileSeq BlockFileSeq() const
FILE * OpenUndoFile(const FlatFilePos &pos, bool fReadOnly=false) const
Open an undo file (rev?????.dat)
bool StopAfterBlockImport() const
Definition: blockstorage.h:327
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 ReadTxFromDisk(CMutableTransaction &tx, const FlatFilePos &pos) const
Functions for disk access for txs.
const Consensus::Params & GetConsensus() const
Definition: blockstorage.h:109
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 FindBlockPos(FlatFilePos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown)
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:319
int MaxBlockfileNum() const EXCLUSIVE_LOCKS_REQUIRED(cs_LastBlockFile)
Definition: blockstorage.h:200
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune) const
Actually unlink the specified files.
bool WriteBlockIndexDB() EXCLUSIVE_LOCKS_REQUIRED(bool LoadBlockIndexDB(const std::optional< BlockHash > &snapshot_blockhash) EXCLUSIVE_LOCKS_REQUIRED(void ScanAndUnlinkAlreadyPrunedFiles() EXCLUSIVE_LOCKS_REQUIRED(CBlockIndex * AddToBlockIndex(const CBlockHeader &block, CBlockIndex *&best_header) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove any pruned block & undo files that are still on disk.
Definition: blockstorage.h:285
bool FlushUndoFile(int block_file, bool finalize=false)
Return false if undo file flushing fails.
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
bool 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:219
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:214
bool FindUndoPos(BlockValidationState &state, int nFile, FlatFilePos &pos, unsigned int nAddSize)
bool IsPruneMode() const
Whether running in -prune mode.
Definition: blockstorage.h:316
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:244
std::vector< CBlockFileInfo > m_blockfile_info
Definition: blockstorage.h:182
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
bool IsBlockPruned(const CBlockIndex *pblockindex) 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:370
std::optional< int > m_snapshot_height
The height of the base block of an assumeutxo snapshot, if one is in use.
Definition: blockstorage.h:260
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:262
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:32
bool error(const char *fmt, const Args &...args)
Definition: logging.h:263
#define LogPrintLevel(category, level,...)
Definition: logging.h:247
#define LogPrint(category,...)
Definition: logging.h:238
#define LogPrintf(...)
Definition: logging.h:227
unsigned int nHeight
@ PRUNE
Definition: logging.h:54
@ BLOCKSTORE
Definition: logging.h:68
static bool exists(const path &p)
Definition: fs.h:102
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:142
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:47
BlockfileType
Definition: blockstorage.h:68
@ ASSUMED
Definition: blockstorage.h:71
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:45
static constexpr size_t BLOCK_SERIALIZATION_HEADER_SIZE
Size of header written by WriteBlockToDisk before a serialized CBlock.
Definition: blockstorage.h:52
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: blockstorage.h:49
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)
@ SER_DISK
Definition: serialize.h:153
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1258
bool AbortNode(const std::string &strMessage, bilingual_str user_message)
Abort with a message.
Definition: shutdown.cpp:20
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
Definition: shutdown.cpp:85
void StartShutdown()
Request shutdown of the application.
Definition: shutdown.cpp:55
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:100
Holds configuration for use during UTXO snapshot load and validation.
Definition: chainparams.h:47
unsigned int nChainTx
Used to populate the nChainTx value, which is used during BlockManager::LoadBlockIndex().
Definition: chainparams.h:59
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
MapCheckpoints mapCheckpoints
Definition: chainparams.h:35
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
#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:109
#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
int atoi(const std::string &str)
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:112