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