Bitcoin ABC  0.26.3
P2P Digital Currency
blockstorage.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2022 The Bitcoin developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <node/blockstorage.h>
6 
8 #include <chain.h>
9 #include <chainparams.h>
10 #include <clientversion.h>
11 #include <config.h>
12 #include <consensus/validation.h>
13 #include <flatfile.h>
14 #include <fs.h>
15 #include <hash.h>
16 #include <pow/pow.h>
17 #include <reverse_iterator.h>
18 #include <shutdown.h>
19 #include <streams.h>
20 #include <undo.h>
21 #include <util/system.h>
22 #include <validation.h>
23 
24 namespace node {
25 std::atomic_bool fImporting(false);
26 std::atomic_bool fReindex(false);
27 bool fPruneMode = false;
28 uint64_t nPruneTarget = 0;
29 
30 static FILE *OpenUndoFile(const FlatFilePos &pos, bool fReadOnly = false);
31 
32 static FlatFileSeq BlockFileSeq();
33 static FlatFileSeq UndoFileSeq();
34 
35 std::vector<CBlockIndex *> BlockManager::GetAllBlockIndices() {
37  std::vector<CBlockIndex *> rv;
38  rv.reserve(m_block_index.size());
39  for (auto &[_, block_index] : m_block_index) {
40  rv.push_back(&block_index);
41  }
42  return rv;
43 }
44 
47  BlockMap::iterator it = m_block_index.find(hash);
48  return it == m_block_index.end() ? nullptr : &it->second;
49 }
50 
53  BlockMap::const_iterator it = m_block_index.find(hash);
54  return it == m_block_index.end() ? nullptr : &it->second;
55 }
56 
57 CBlockIndex *BlockManager::AddToBlockIndex(const CBlockHeader &block,
58  CBlockIndex *&best_header) {
60 
61  const auto [mi, inserted] =
62  m_block_index.try_emplace(block.GetHash(), block);
63  if (!inserted) {
64  return &mi->second;
65  }
66  CBlockIndex *pindexNew = &(*mi).second;
67 
68  // We assign the sequence id to blocks only when the full data is available,
69  // to avoid miners withholding blocks but broadcasting headers, to get a
70  // competitive advantage.
71  pindexNew->nSequenceId = 0;
72 
73  pindexNew->phashBlock = &((*mi).first);
74  BlockMap::iterator miPrev = m_block_index.find(block.hashPrevBlock);
75  if (miPrev != m_block_index.end()) {
76  pindexNew->pprev = &(*miPrev).second;
77  pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
78  pindexNew->BuildSkip();
79  }
80  pindexNew->nTimeReceived = GetTime();
81  pindexNew->nTimeMax =
82  (pindexNew->pprev
83  ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime)
84  : pindexNew->nTime);
85  pindexNew->nChainWork =
86  (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) +
87  GetBlockProof(*pindexNew);
89  if (best_header == nullptr ||
90  best_header->nChainWork < pindexNew->nChainWork) {
91  best_header = pindexNew;
92  }
93 
94  m_dirty_blockindex.insert(pindexNew);
95  return pindexNew;
96 }
97 
98 void BlockManager::PruneOneBlockFile(const int fileNumber) {
101 
102  for (auto &entry : m_block_index) {
103  CBlockIndex *pindex = &entry.second;
104  if (pindex->nFile == fileNumber) {
105  pindex->nStatus = pindex->nStatus.withData(false).withUndo(false);
106  pindex->nFile = 0;
107  pindex->nDataPos = 0;
108  pindex->nUndoPos = 0;
109  m_dirty_blockindex.insert(pindex);
110 
111  // Prune from m_blocks_unlinked -- any block we prune would have
112  // to be downloaded again in order to consider its chain, at which
113  // point it would be considered as a candidate for
114  // m_blocks_unlinked or setBlockIndexCandidates.
115  auto range = m_blocks_unlinked.equal_range(pindex->pprev);
116  while (range.first != range.second) {
117  std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it =
118  range.first;
119  range.first++;
120  if (_it->second == pindex) {
121  m_blocks_unlinked.erase(_it);
122  }
123  }
124  }
125  }
126 
127  m_blockfile_info[fileNumber].SetNull();
128  m_dirty_fileinfo.insert(fileNumber);
129 }
130 
131 void BlockManager::FindFilesToPruneManual(std::set<int> &setFilesToPrune,
132  int nManualPruneHeight,
133  int chain_tip_height) {
134  assert(fPruneMode && nManualPruneHeight > 0);
135 
137  if (chain_tip_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  unsigned int nLastBlockWeCanPrune{std::min(
144  (unsigned)nManualPruneHeight, chain_tip_height - MIN_BLOCKS_TO_KEEP)};
145  int count = 0;
146  for (int fileNumber = 0; fileNumber < m_last_blockfile; fileNumber++) {
147  if (m_blockfile_info[fileNumber].nSize == 0 ||
148  m_blockfile_info[fileNumber].nHeightLast > nLastBlockWeCanPrune) {
149  continue;
150  }
151  PruneOneBlockFile(fileNumber);
152  setFilesToPrune.insert(fileNumber);
153  count++;
154  }
155  LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n",
156  nLastBlockWeCanPrune, count);
157 }
158 
159 void BlockManager::FindFilesToPrune(std::set<int> &setFilesToPrune,
160  uint64_t nPruneAfterHeight,
161  int chain_tip_height, int prune_height,
162  bool is_ibd) {
164  if (chain_tip_height < 0 || nPruneTarget == 0) {
165  return;
166  }
167  if (uint64_t(chain_tip_height) <= nPruneAfterHeight) {
168  return;
169  }
170 
171  unsigned int nLastBlockWeCanPrune = std::min(
172  prune_height, chain_tip_height - static_cast<int>(MIN_BLOCKS_TO_KEEP));
173  uint64_t nCurrentUsage = CalculateCurrentUsage();
174  // We don't check to prune until after we've allocated new space for files,
175  // so we should leave a buffer under our target to account for another
176  // allocation before the next pruning.
177  uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
178  uint64_t nBytesToPrune;
179  int count = 0;
180 
181  if (nCurrentUsage + nBuffer >= nPruneTarget) {
182  // On a prune event, the chainstate DB is flushed.
183  // To avoid excessive prune events negating the benefit of high dbcache
184  // values, we should not prune too rapidly.
185  // So when pruning in IBD, increase the buffer a bit to avoid a re-prune
186  // too soon.
187  if (is_ibd) {
188  // Since this is only relevant during IBD, we use a fixed 10%
189  nBuffer += nPruneTarget / 10;
190  }
191 
192  for (int fileNumber = 0; fileNumber < m_last_blockfile; fileNumber++) {
193  nBytesToPrune = m_blockfile_info[fileNumber].nSize +
194  m_blockfile_info[fileNumber].nUndoSize;
195 
196  if (m_blockfile_info[fileNumber].nSize == 0) {
197  continue;
198  }
199 
200  // are we below our target?
201  if (nCurrentUsage + nBuffer < nPruneTarget) {
202  break;
203  }
204 
205  // don't prune files that could have a block within
206  // MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
207  if (m_blockfile_info[fileNumber].nHeightLast >
208  nLastBlockWeCanPrune) {
209  continue;
210  }
211 
212  PruneOneBlockFile(fileNumber);
213  // Queue up the files for removal
214  setFilesToPrune.insert(fileNumber);
215  nCurrentUsage -= nBytesToPrune;
216  count++;
217  }
218  }
219 
221  "Prune: target=%dMiB actual=%dMiB diff=%dMiB "
222  "max_prune_height=%d removed %d blk/rev pairs\n",
223  nPruneTarget / 1024 / 1024, nCurrentUsage / 1024 / 1024,
224  ((int64_t)nPruneTarget - (int64_t)nCurrentUsage) / 1024 / 1024,
225  nLastBlockWeCanPrune, count);
226 }
227 
230 
231  if (hash.IsNull()) {
232  return nullptr;
233  }
234 
235  const auto [mi, inserted] = m_block_index.try_emplace(hash);
236  CBlockIndex *pindex = &(*mi).second;
237  if (inserted) {
238  pindex->phashBlock = &((*mi).first);
239  }
240  return pindex;
241 }
242 
245  if (!m_block_tree_db->LoadBlockIndexGuts(
246  params, [this](const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(
247  cs_main) { return this->InsertBlockIndex(hash); })) {
248  return false;
249  }
250 
251  // Calculate nChainWork
252  std::vector<CBlockIndex *> vSortedByHeight{GetAllBlockIndices()};
253  std::sort(vSortedByHeight.begin(), vSortedByHeight.end(),
255 
256  for (CBlockIndex *pindex : vSortedByHeight) {
257  if (ShutdownRequested()) {
258  return false;
259  }
260  pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) +
261  GetBlockProof(*pindex);
262  pindex->nTimeMax =
263  (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime)
264  : pindex->nTime);
265 
266  // We can link the chain of blocks for which we've received
267  // transactions at some point, or blocks that are assumed-valid on the
268  // basis of snapshot load (see PopulateAndValidateSnapshot()).
269  // Pruned nodes may have deleted the block.
270  if (pindex->nTx > 0) {
271  if (!pindex->UpdateChainStats() && pindex->pprev) {
272  m_blocks_unlinked.insert(std::make_pair(pindex->pprev, pindex));
273  }
274  }
275 
276  if (!pindex->nStatus.hasFailed() && pindex->pprev &&
277  pindex->pprev->nStatus.hasFailed()) {
278  pindex->nStatus = pindex->nStatus.withFailedParent();
279  m_dirty_blockindex.insert(pindex);
280  }
281 
282  if (pindex->pprev) {
283  pindex->BuildSkip();
284  }
285  }
286 
287  return true;
288 }
289 
290 bool BlockManager::WriteBlockIndexDB() {
291  std::vector<std::pair<int, const CBlockFileInfo *>> vFiles;
292  vFiles.reserve(m_dirty_fileinfo.size());
293  for (int i : m_dirty_fileinfo) {
294  vFiles.push_back(std::make_pair(i, &m_blockfile_info[i]));
295  }
296 
297  m_dirty_fileinfo.clear();
298 
299  std::vector<const CBlockIndex *> vBlocks;
300  vBlocks.reserve(m_dirty_blockindex.size());
301  for (const CBlockIndex *cbi : m_dirty_blockindex) {
302  vBlocks.push_back(cbi);
303  }
304 
305  m_dirty_blockindex.clear();
306 
307  if (!m_block_tree_db->WriteBatchSync(vFiles, m_last_blockfile, vBlocks)) {
308  return false;
309  }
310  return true;
311 }
312 
313 bool BlockManager::LoadBlockIndexDB() {
314  if (!LoadBlockIndex(::Params().GetConsensus())) {
315  return false;
316  }
317 
318  // Load block file info
319  m_block_tree_db->ReadLastBlockFile(m_last_blockfile);
321  LogPrintf("%s: last block file = %i\n", __func__, m_last_blockfile);
322  for (int nFile = 0; nFile <= m_last_blockfile; nFile++) {
323  m_block_tree_db->ReadBlockFileInfo(nFile, m_blockfile_info[nFile]);
324  }
325  LogPrintf("%s: last block file info: %s\n", __func__,
327  for (int nFile = m_last_blockfile + 1; true; nFile++) {
328  CBlockFileInfo info;
329  if (m_block_tree_db->ReadBlockFileInfo(nFile, info)) {
330  m_blockfile_info.push_back(info);
331  } else {
332  break;
333  }
334  }
335 
336  // Check presence of blk files
337  LogPrintf("Checking all blk files are present...\n");
338  std::set<int> setBlkDataFiles;
339  for (const auto &[_, block_index] : m_block_index) {
340  if (block_index.nStatus.hasData()) {
341  setBlkDataFiles.insert(block_index.nFile);
342  }
343  }
344 
345  for (const int i : setBlkDataFiles) {
346  FlatFilePos pos(i, 0);
348  .IsNull()) {
349  return false;
350  }
351  }
352 
353  // Check whether we have ever pruned block & undo files
354  m_block_tree_db->ReadFlag("prunedblockfiles", m_have_pruned);
355  if (m_have_pruned) {
356  LogPrintf(
357  "LoadBlockIndexDB(): Block files have previously been pruned\n");
358  }
359 
360  // Check whether we need to continue reindexing
361  if (m_block_tree_db->IsReindexing()) {
362  fReindex = true;
363  }
364 
365  return true;
366 }
367 
368 const CBlockIndex *
370  const MapCheckpoints &checkpoints = data.mapCheckpoints;
371 
372  for (const MapCheckpoints::value_type &i : reverse_iterate(checkpoints)) {
373  const BlockHash &hash = i.second;
374  const CBlockIndex *pindex = LookupBlockIndex(hash);
375  if (pindex) {
376  return pindex;
377  }
378  }
379 
380  return nullptr;
381 }
382 
383 bool BlockManager::IsBlockPruned(const CBlockIndex *pblockindex) {
385  return (m_have_pruned && !pblockindex->nStatus.hasData() &&
386  pblockindex->nTx > 0);
387 }
388 
389 const CBlockIndex *GetFirstStoredBlock(const CBlockIndex *start_block) {
391  assert(start_block);
392  const CBlockIndex *last_block = start_block;
393  while (last_block->pprev && (last_block->pprev->nStatus.hasData())) {
394  last_block = last_block->pprev;
395  }
396  return last_block;
397 }
398 
399 // If we're using -prune with -reindex, then delete block files that will be
400 // ignored by the reindex. Since reindexing works by starting at block file 0
401 // and looping until a blockfile is missing, do the same here to delete any
402 // later block files after a gap. Also delete all rev files since they'll be
403 // rewritten by the reindex anyway. This ensures that m_blockfile_info is in
404 // sync with what's actually on disk by the time we start downloading, so that
405 // pruning works correctly.
406 void CleanupBlockRevFiles() {
407  std::map<std::string, fs::path> mapBlockFiles;
408 
409  // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
410  // Remove the rev files immediately and insert the blk file paths into an
411  // ordered map keyed by block file index.
412  LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for "
413  "-reindex with -prune\n");
414  for (const auto &file : fs::directory_iterator{gArgs.GetBlocksDirPath()}) {
415  const std::string path = fs::PathToString(file.path().filename());
416  if (fs::is_regular_file(file) && path.length() == 12 &&
417  path.substr(8, 4) == ".dat") {
418  if (path.substr(0, 3) == "blk") {
419  mapBlockFiles[path.substr(3, 5)] = file.path();
420  } else if (path.substr(0, 3) == "rev") {
421  remove(file.path());
422  }
423  }
424  }
425 
426  // Remove all block files that aren't part of a contiguous set starting at
427  // zero by walking the ordered map (keys are block file indices) by keeping
428  // a separate counter. Once we hit a gap (or if 0 doesn't exist) start
429  // removing block files.
430  int contiguousCounter = 0;
431  for (const auto &item : mapBlockFiles) {
432  if (atoi(item.first) == contiguousCounter) {
433  contiguousCounter++;
434  continue;
435  }
436  remove(item.second);
437  }
438 }
439 
442 
443  return &m_blockfile_info.at(n);
444 }
445 
446 static bool UndoWriteToDisk(const CBlockUndo &blockundo, FlatFilePos &pos,
447  const BlockHash &hashBlock,
448  const CMessageHeader::MessageMagic &messageStart) {
449  // Open history file to append
451  if (fileout.IsNull()) {
452  return error("%s: OpenUndoFile failed", __func__);
453  }
454 
455  // Write index header
456  unsigned int nSize = GetSerializeSize(blockundo, fileout.GetVersion());
457  fileout << messageStart << nSize;
458 
459  // Write undo data
460  long fileOutPos = ftell(fileout.Get());
461  if (fileOutPos < 0) {
462  return error("%s: ftell failed", __func__);
463  }
464  pos.nPos = (unsigned int)fileOutPos;
465  fileout << blockundo;
466 
467  // calculate & write checksum
469  hasher << hashBlock;
470  hasher << blockundo;
471  fileout << hasher.GetHash();
472 
473  return true;
474 }
475 
476 bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex) {
477  const FlatFilePos pos{WITH_LOCK(::cs_main, return pindex->GetUndoPos())};
478 
479  if (pos.IsNull()) {
480  return error("%s: no undo data available", __func__);
481  }
482 
483  // Open history file to read
484  CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
485  if (filein.IsNull()) {
486  return error("%s: OpenUndoFile failed", __func__);
487  }
488 
489  // Read block
490  uint256 hashChecksum;
491  // We need a CHashVerifier as reserializing may lose data
492  CHashVerifier<CAutoFile> verifier(&filein);
493  try {
494  verifier << pindex->pprev->GetBlockHash();
495  verifier >> blockundo;
496  filein >> hashChecksum;
497  } catch (const std::exception &e) {
498  return error("%s: Deserialize or I/O error - %s", __func__, e.what());
499  }
500 
501  // Verify checksum
502  if (hashChecksum != verifier.GetHash()) {
503  return error("%s: Checksum mismatch", __func__);
504  }
505 
506  return true;
507 }
508 
509 void BlockManager::FlushUndoFile(int block_file, bool finalize) {
510  FlatFilePos undo_pos_old(block_file,
511  m_blockfile_info[block_file].nUndoSize);
512  if (!UndoFileSeq().Flush(undo_pos_old, finalize)) {
513  AbortNode("Flushing undo file to disk failed. This is likely the "
514  "result of an I/O error.");
515  }
516 }
517 
518 void BlockManager::FlushBlockFile(bool fFinalize, bool finalize_undo) {
520  FlatFilePos block_pos_old(m_last_blockfile,
522  if (!BlockFileSeq().Flush(block_pos_old, fFinalize)) {
523  AbortNode("Flushing block file to disk failed. This is likely the "
524  "result of an I/O error.");
525  }
526  // we do not always flush the undo file, as the chain tip may be lagging
527  // behind the incoming blocks,
528  // e.g. during IBD or a sync after a node going offline
529  if (!fFinalize || finalize_undo) {
530  FlushUndoFile(m_last_blockfile, finalize_undo);
531  }
532 }
533 
536 
537  uint64_t retval = 0;
538  for (const CBlockFileInfo &file : m_blockfile_info) {
539  retval += file.nSize + file.nUndoSize;
540  }
541 
542  return retval;
543 }
544 
545 void UnlinkPrunedFiles(const std::set<int> &setFilesToPrune) {
546  for (const int i : setFilesToPrune) {
547  FlatFilePos pos(i, 0);
548  fs::remove(BlockFileSeq().FileName(pos));
549  fs::remove(UndoFileSeq().FileName(pos));
550  LogPrint(BCLog::BLOCKSTORE, "Prune: %s deleted blk/rev (%05u)\n",
551  __func__, i);
552  }
553 }
554 
556  return FlatFileSeq(gArgs.GetBlocksDirPath(), "blk",
557  gArgs.GetBoolArg("-fastprune", false)
558  ? 0x4000 /* 16kb */
560 }
561 
564 }
565 
566 FILE *OpenBlockFile(const FlatFilePos &pos, bool fReadOnly) {
567  return BlockFileSeq().Open(pos, fReadOnly);
568 }
569 
571 static FILE *OpenUndoFile(const FlatFilePos &pos, bool fReadOnly) {
572  return UndoFileSeq().Open(pos, fReadOnly);
573 }
574 
576  return BlockFileSeq().FileName(pos);
577 }
578 
579 bool BlockManager::FindBlockPos(FlatFilePos &pos, unsigned int nAddSize,
580  unsigned int nHeight, CChain &active_chain,
581  uint64_t nTime, bool fKnown) {
583 
584  unsigned int nFile = fKnown ? pos.nFile : m_last_blockfile;
585  if (m_blockfile_info.size() <= nFile) {
586  m_blockfile_info.resize(nFile + 1);
587  }
588 
589  bool finalize_undo = false;
590  if (!fKnown) {
591  while (m_blockfile_info[nFile].nSize + nAddSize >=
592  (gArgs.GetBoolArg("-fastprune", false) ? 0x10000 /* 64kb */
593  : MAX_BLOCKFILE_SIZE)) {
594  // when the undo file is keeping up with the block file, we want to
595  // flush it explicitly when it is lagging behind (more blocks arrive
596  // than are being connected), we let the undo block write case
597  // handle it
598  finalize_undo = (m_blockfile_info[nFile].nHeightLast ==
599  (unsigned int)active_chain.Tip()->nHeight);
600  nFile++;
601  if (m_blockfile_info.size() <= nFile) {
602  m_blockfile_info.resize(nFile + 1);
603  }
604  }
605  pos.nFile = nFile;
606  pos.nPos = m_blockfile_info[nFile].nSize;
607  }
608 
609  if ((int)nFile != m_last_blockfile) {
610  if (!fKnown) {
611  LogPrint(BCLog::BLOCKSTORE, "Leaving block file %i: %s\n",
614  }
615  FlushBlockFile(!fKnown, finalize_undo);
616  m_last_blockfile = nFile;
617  }
618 
619  m_blockfile_info[nFile].AddBlock(nHeight, nTime);
620  if (fKnown) {
621  m_blockfile_info[nFile].nSize =
622  std::max(pos.nPos + nAddSize, m_blockfile_info[nFile].nSize);
623  } else {
624  m_blockfile_info[nFile].nSize += nAddSize;
625  }
626 
627  if (!fKnown) {
628  bool out_of_space;
629  size_t bytes_allocated =
630  BlockFileSeq().Allocate(pos, nAddSize, out_of_space);
631  if (out_of_space) {
632  return AbortNode("Disk space is too low!",
633  _("Disk space is too low!"));
634  }
635  if (bytes_allocated != 0 && fPruneMode) {
636  m_check_for_pruning = true;
637  }
638  }
639 
640  m_dirty_fileinfo.insert(nFile);
641  return true;
642 }
643 
645  FlatFilePos &pos, unsigned int nAddSize) {
646  pos.nFile = nFile;
647 
649 
650  pos.nPos = m_blockfile_info[nFile].nUndoSize;
651  m_blockfile_info[nFile].nUndoSize += nAddSize;
652  m_dirty_fileinfo.insert(nFile);
653 
654  bool out_of_space;
655  size_t bytes_allocated =
656  UndoFileSeq().Allocate(pos, nAddSize, out_of_space);
657  if (out_of_space) {
658  return AbortNode(state, "Disk space is too low!",
659  _("Disk space is too low!"));
660  }
661  if (bytes_allocated != 0 && fPruneMode) {
662  m_check_for_pruning = true;
663  }
664 
665  return true;
666 }
667 
668 static bool WriteBlockToDisk(const CBlock &block, FlatFilePos &pos,
669  const CMessageHeader::MessageMagic &messageStart) {
670  // Open history file to append
672  if (fileout.IsNull()) {
673  return error("WriteBlockToDisk: OpenBlockFile failed");
674  }
675 
676  // Write index header
677  unsigned int nSize = GetSerializeSize(block, fileout.GetVersion());
678  fileout << messageStart << nSize;
679 
680  // Write block
681  long fileOutPos = ftell(fileout.Get());
682  if (fileOutPos < 0) {
683  return error("WriteBlockToDisk: ftell failed");
684  }
685 
686  pos.nPos = (unsigned int)fileOutPos;
687  fileout << block;
688 
689  return true;
690 }
691 
692 bool BlockManager::WriteUndoDataForBlock(const CBlockUndo &blockundo,
693  BlockValidationState &state,
694  CBlockIndex *pindex,
695  const CChainParams &chainparams) {
697  // Write undo information to disk
698  if (pindex->GetUndoPos().IsNull()) {
699  FlatFilePos _pos;
700  if (!FindUndoPos(state, pindex->nFile, _pos,
701  ::GetSerializeSize(blockundo, CLIENT_VERSION) + 40)) {
702  return error("ConnectBlock(): FindUndoPos failed");
703  }
704  if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(),
705  chainparams.DiskMagic())) {
706  return AbortNode(state, "Failed to write undo data");
707  }
708  // rev files are written in block height order, whereas blk files are
709  // written as blocks come in (often out of order) we want to flush the
710  // rev (undo) file once we've written the last block, which is indicated
711  // by the last height in the block file info as below; note that this
712  // does not catch the case where the undo writes are keeping up with the
713  // block writes (usually when a synced up node is getting newly mined
714  // blocks) -- this case is caught in the FindBlockPos function
715  if (_pos.nFile < m_last_blockfile &&
716  static_cast<uint32_t>(pindex->nHeight) ==
717  m_blockfile_info[_pos.nFile].nHeightLast) {
718  FlushUndoFile(_pos.nFile, true);
719  }
720 
721  // update nUndoPos in block index
722  pindex->nUndoPos = _pos.nPos;
723  pindex->nStatus = pindex->nStatus.withUndo();
724  m_dirty_blockindex.insert(pindex);
725  }
726 
727  return true;
728 }
729 
730 bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos,
731  const Consensus::Params &params) {
732  block.SetNull();
733 
734  // Open history file to read
735  CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
736  if (filein.IsNull()) {
737  return error("ReadBlockFromDisk: OpenBlockFile failed for %s",
738  pos.ToString());
739  }
740 
741  // Read block
742  try {
743  filein >> block;
744  } catch (const std::exception &e) {
745  return error("%s: Deserialize or I/O error - %s at %s", __func__,
746  e.what(), pos.ToString());
747  }
748 
749  // Check the header
750  if (!CheckProofOfWork(block.GetHash(), block.nBits, params)) {
751  return error("ReadBlockFromDisk: Errors in block header at %s",
752  pos.ToString());
753  }
754 
755  return true;
756 }
757 
758 bool ReadBlockFromDisk(CBlock &block, const CBlockIndex *pindex,
759  const Consensus::Params &params) {
760  const FlatFilePos block_pos{
761  WITH_LOCK(cs_main, return pindex->GetBlockPos())};
762 
763  if (!ReadBlockFromDisk(block, block_pos, params)) {
764  return false;
765  }
766 
767  if (block.GetHash() != pindex->GetBlockHash()) {
768  return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() "
769  "doesn't match index for %s at %s",
770  pindex->ToString(), block_pos.ToString());
771  }
772 
773  return true;
774 }
775 
777  // Open history file to read
778  CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
779  if (filein.IsNull()) {
780  return error("ReadTxFromDisk: OpenBlockFile failed for %s",
781  pos.ToString());
782  }
783 
784  // Read tx
785  try {
786  filein >> tx;
787  } catch (const std::exception &e) {
788  return error("%s: Deserialize or I/O error - %s at %s", __func__,
789  e.what(), pos.ToString());
790  }
791 
792  return true;
793 }
794 
795 bool ReadTxUndoFromDisk(CTxUndo &tx_undo, const FlatFilePos &pos) {
796  // Open undo file to read
797  CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
798  if (filein.IsNull()) {
799  return error("ReadTxUndoFromDisk: OpenUndoFile failed for %s",
800  pos.ToString());
801  }
802 
803  // Read undo data
804  try {
805  filein >> tx_undo;
806  } catch (const std::exception &e) {
807  return error("%s: Deserialize or I/O error - %s at %s", __func__,
808  e.what(), pos.ToString());
809  }
810 
811  return true;
812 }
813 
819  CChain &active_chain,
820  const CChainParams &chainparams,
821  const FlatFilePos *dbp) {
822  unsigned int nBlockSize = ::GetSerializeSize(block, CLIENT_VERSION);
823  FlatFilePos blockPos;
824  if (dbp != nullptr) {
825  blockPos = *dbp;
826  }
827  if (!FindBlockPos(blockPos, nBlockSize + 8, nHeight, active_chain,
828  block.GetBlockTime(), dbp != nullptr)) {
829  error("%s: FindBlockPos failed", __func__);
830  return FlatFilePos();
831  }
832  if (dbp == nullptr) {
833  if (!WriteBlockToDisk(block, blockPos, chainparams.DiskMagic())) {
834  AbortNode("Failed to write block");
835  return FlatFilePos();
836  }
837  }
838  return blockPos;
839 }
840 
843  assert(fImporting == false);
844  fImporting = true;
845  }
846 
848  assert(fImporting == true);
849  fImporting = false;
850  }
851 };
852 
853 void ThreadImport(const Config &config, ChainstateManager &chainman,
854  std::vector<fs::path> vImportFiles, const ArgsManager &args) {
856 
857  {
858  const CChainParams &chainParams = config.GetChainParams();
859 
860  CImportingNow imp;
861 
862  // -reindex
863  if (fReindex) {
864  int nFile = 0;
865  while (true) {
866  FlatFilePos pos(nFile, 0);
867  if (!fs::exists(GetBlockPosFilename(pos))) {
868  // No block files left to reindex
869  break;
870  }
871  FILE *file = OpenBlockFile(pos, true);
872  if (!file) {
873  // This error is logged in OpenBlockFile
874  break;
875  }
876  LogPrintf("Reindexing block file blk%05u.dat...\n",
877  (unsigned int)nFile);
878  chainman.ActiveChainstate().LoadExternalBlockFile(config, file,
879  &pos);
880  if (ShutdownRequested()) {
881  LogPrintf("Shutdown requested. Exit %s\n", __func__);
882  return;
883  }
884  nFile++;
885  }
886  WITH_LOCK(
887  ::cs_main,
888  chainman.m_blockman.m_block_tree_db->WriteReindexing(false));
889  fReindex = false;
890  LogPrintf("Reindexing finished\n");
891  // To avoid ending up in a situation without genesis block, re-try
892  // initializing (no-op if reindexing worked):
893  chainman.ActiveChainstate().LoadGenesisBlock();
894  }
895 
896  // -loadblock=
897  for (const fs::path &path : vImportFiles) {
898  FILE *file = fsbridge::fopen(path, "rb");
899  if (file) {
900  LogPrintf("Importing blocks file %s...\n",
901  fs::PathToString(path));
902  chainman.ActiveChainstate().LoadExternalBlockFile(config, file);
903  if (ShutdownRequested()) {
904  LogPrintf("Shutdown requested. Exit %s\n", __func__);
905  return;
906  }
907  } else {
908  LogPrintf("Warning: Could not open blocks file %s\n",
909  fs::PathToString(path));
910  }
911  }
912 
913  // Reconsider blocks we know are valid. They may have been marked
914  // invalid by, for instance, running an outdated version of the node
915  // software.
916  const MapCheckpoints &checkpoints =
917  chainParams.Checkpoints().mapCheckpoints;
918  for (const MapCheckpoints::value_type &i : checkpoints) {
919  const BlockHash &hash = i.second;
920 
921  LOCK(cs_main);
922  CBlockIndex *pblockindex =
923  chainman.m_blockman.LookupBlockIndex(hash);
924  if (pblockindex && !pblockindex->nStatus.isValid()) {
925  LogPrintf("Reconsidering checkpointed block %s ...\n",
926  hash.GetHex());
927  chainman.ActiveChainstate().ResetBlockFailureFlags(pblockindex);
928  }
929 
930  if (pblockindex && pblockindex->nStatus.isOnParkedChain()) {
931  LogPrintf("Unparking checkpointed block %s ...\n",
932  hash.GetHex());
933  chainman.ActiveChainstate().UnparkBlockAndChildren(pblockindex);
934  }
935  }
936 
937  // scan for better chains in the block chain database, that are not yet
938  // connected in the active best chain
939 
940  // We can't hold cs_main during ActivateBestChain even though we're
941  // accessing the chainman unique_ptrs since ABC requires us not to be
942  // holding cs_main, so retrieve the relevant pointers before the ABC
943  // call.
944  for (Chainstate *chainstate :
945  WITH_LOCK(::cs_main, return chainman.GetAll())) {
946  BlockValidationState state;
947  if (!chainstate->ActivateBestChain(config, state, nullptr)) {
948  LogPrintf("Failed to connect best block (%s)\n",
949  state.ToString());
950  StartShutdown();
951  return;
952  }
953  }
954 
955  if (args.GetBoolArg("-stopafterblockimport",
957  LogPrintf("Stopping after block import\n");
958  StartShutdown();
959  return;
960  }
961  } // End scope of CImportingNow
962  chainman.ActiveChainstate().LoadMempool(config, args);
963 }
964 } // namespace node
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:113
@ TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:77
const CChainParams & Params()
Return the currently selected parameters.
std::map< int, BlockHash > MapCheckpoints
Definition: chainparams.h:25
const fs::path & GetBlocksDirPath() const
Get blocks directory path.
Definition: system.cpp:402
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:601
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:581
FILE * Get() const
Get wrapped FILE* without transfer of ownership.
Definition: streams.h:624
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
Definition: streams.h:627
int GetVersion() const
Definition: streams.h:633
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:22
BlockHash GetHash() const
Definition: block.cpp:11
uint32_t nBits
Definition: block.h:29
BlockHash hashPrevBlock
Definition: block.h:26
int64_t GetBlockTime() const
Definition: block.h:52
Definition: block.h:55
void SetNull()
Definition: block.h:75
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:26
uint64_t nTimeReceived
(memory only) block header metadata
Definition: blockindex.h:102
std::string ToString() const
Definition: blockindex.h:201
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: blockindex.h:33
void BuildSkip()
Build the skiplist pointer for this entry.
Definition: blockindex.cpp:76
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: blockindex.h:52
const BlockHash * phashBlock
pointer to the hash of the block, if any.
Definition: blockindex.h:30
uint32_t nTime
Definition: blockindex.h:93
unsigned int nTimeMax
(memory only) Maximum nTime in the chain up to and including this block.
Definition: blockindex.h:105
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
Definition: blockindex.h:99
FlatFilePos GetUndoPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: blockindex.h:124
unsigned int nTx
Number of transactions in this block.
Definition: blockindex.h:61
bool RaiseValidity(enum BlockValidity nUpTo) EXCLUSIVE_LOCKS_REQUIRED(
Raise the validity level of this block index entry.
Definition: blockindex.h:224
BlockHash GetBlockHash() const
Definition: blockindex.h:147
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:39
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: blockindex.h:114
Undo information for a CBlock.
Definition: undo.h:73
An in-memory indexed chain of blocks.
Definition: chain.h:141
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:157
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:74
const CCheckpointData & Checkpoints() const
Definition: chainparams.h:128
const CMessageHeader::MessageMagic & DiskMagic() const
Definition: chainparams.h:87
Reads data from an underlying stream, while hashing the read data.
Definition: hash.h:160
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:99
uint256 GetHash()
Compute the double-SHA256 hash of all data written to this object.
Definition: hash.h:122
std::array< uint8_t, MESSAGE_START_SIZE > MessageMagic
Definition: protocol.h:49
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:647
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
void UnparkBlockAndChildren(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove parked status from a block and its descendants.
void LoadMempool(const Config &config, const ArgsManager &args)
Load the persisted mempool from disk.
void ResetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove invalidity status from a block and its descendants.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1062
Chainstate & ActiveChainstate() const
The most-work chain.
Chainstate &InitializeChainstate(CTxMemPool *mempool, const std::optional< BlockHash > &snapshot_blockhash=std::nullopt) LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate and assign it based upon whether it is from a snapshot.
Definition: validation.h:1180
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1129
Definition: config.h:17
virtual const CChainParams & GetChainParams() const =0
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
std::string ToString() const
Definition: validation.h:126
bool IsNull() const
Definition: uint256.h:30
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:29
std::set< int > m_dirty_fileinfo
Dirty block file entries.
Definition: blockstorage.h:134
bool WriteUndoDataForBlock(const CBlockUndo &blockundo, BlockValidationState &state, CBlockIndex *pindex, const CChainParams &chainparams) EXCLUSIVE_LOCKS_REQUIRED(FlatFilePo SaveBlockToDisk)(const CBlock &block, int nHeight, CChain &active_chain, const CChainParams &chainparams, const FlatFilePos *dbp)
Store block on disk.
Definition: blockstorage.h:178
RecursiveMutex cs_LastBlockFile
Definition: blockstorage.h:120
bool LoadBlockIndex(const Consensus::Params &consensus_params) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the blocktree off disk and into memory.
void FindFilesToPrune(std::set< int > &setFilesToPrune, uint64_t nPruneAfterHeight, int chain_tip_height, int prune_height, bool is_ibd)
Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a us...
void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight, int chain_tip_height)
Calculate the block/rev files to delete based on height specified by user with RPC command pruneblock...
void FlushUndoFile(int block_file, bool finalize=false)
bool FindBlockPos(FlatFilePos &pos, unsigned int nAddSize, unsigned int nHeight, CChain &active_chain, uint64_t nTime, bool fKnown)
void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark one block file as pruned (modify associated database entries)
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
CBlockIndex * InsertBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Create a new block index entry for a given block hash.
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
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:131
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:128
bool FindUndoPos(BlockValidationState &state, int nFile, FlatFilePos &pos, unsigned int nAddSize)
std::vector< CBlockFileInfo > m_blockfile_info
Definition: blockstorage.h:121
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
bool m_have_pruned
True if any block files have ever been pruned.
Definition: blockstorage.h:193
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:139
void FlushBlockFile(bool fFinalize=false, bool finalize_undo=false)
256-bit opaque blob.
Definition: uint256.h:127
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:38
#define LogPrint(category,...)
Definition: logging.h:210
#define LogPrintf(...)
Definition: logging.h:206
unsigned int nHeight
@ PRUNE
Definition: logging.h:54
@ BLOCKSTORE
Definition: logging.h:68
static bool exists(const path &p)
Definition: fs.h:89
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:136
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:28
Definition: init.h:28
const CBlockIndex *GetFirstStoredBlock(const CBlockIndex *start_block) EXCLUSIVE_LOCKS_REQUIRED(voi CleanupBlockRevFiles)()
Find the first block that is not pruned.
Definition: blockstorage.h:205
static const unsigned int UNDOFILE_CHUNK_SIZE
The pre-allocation chunk size for rev?????.dat files (since 0.8)
Definition: blockstorage.h:43
const CBlockIndex * GetFirstStoredBlock(const CBlockIndex *start_block)
bool fPruneMode
Pruning-related variables and constants.
std::atomic_bool fImporting
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &params)
Functions for disk access for blocks.
static FILE * OpenUndoFile(const FlatFilePos &pos, bool fReadOnly=false)
Open an undo file (rev?????.dat)
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
static FlatFileSeq UndoFileSeq()
static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT
Definition: blockstorage.h:38
FILE * OpenBlockFile(const FlatFilePos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
static bool WriteBlockToDisk(const CBlock &block, FlatFilePos &pos, const CMessageHeader::MessageMagic &messageStart)
void ThreadImport(const Config &config, ChainstateManager &chainman, std::vector< fs::path > vImportFiles, const ArgsManager &args)
bool ReadTxFromDisk(CMutableTransaction &tx, const FlatFilePos &pos)
Functions for disk access for txs.
static constexpr unsigned int BLOCKFILE_CHUNK_SIZE
The pre-allocation chunk size for blk?????.dat files (since 0.8)
Definition: blockstorage.h:41
fs::path GetBlockPosFilename(const FlatFilePos &pos)
Translation to a filesystem path.
bool ReadTxUndoFromDisk(CTxUndo &tx_undo, const FlatFilePos &pos)
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: blockstorage.h:45
std::atomic_bool fReindex
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex)
static bool UndoWriteToDisk(const CBlockUndo &blockundo, FlatFilePos &pos, const BlockHash &hashBlock, const CMessageHeader::MessageMagic &messageStart)
static FlatFileSeq BlockFileSeq()
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:45
reverse_range< T > reverse_iterate(T &x)
@ SER_DISK
Definition: serialize.h:167
@ SER_GETHASH
Definition: serialize.h:168
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1259
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
int atoi(const std::string &str)
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:87
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
MapCheckpoints mapCheckpoints
Definition: chainparams.h:28
Parameters that influence chain consensus.
Definition: params.h:33
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:247
#define LOCK(cs)
Definition: sync.h:244
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:277
void ScheduleBatchPriority()
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
Definition: system.cpp:1379
ArgsManager gArgs
Definition: system.cpp:79
bool error(const char *fmt, const Args &...args)
Definition: system.h:45
static int count
Definition: tests.c:31
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
T GetTime()
Return system time (or mocked time, if set)
Definition: time.cpp:71
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:55
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
Definition: validation.h:103
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:11