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