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