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