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