Bitcoin ABC 0.26.3
P2P Digital Currency
Loading...
Searching...
No Matches
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
9#include <chain.h>
10#include <clientversion.h>
11#include <common/system.h>
12#include <config.h>
14#include <flatfile.h>
15#include <hash.h>
16#include <kernel/chainparams.h>
17#include <logging.h>
18#include <pow/pow.h>
19#include <reverse_iterator.h>
20#include <shutdown.h>
21#include <streams.h>
22#include <undo.h>
23#include <util/batchpriority.h>
24#include <util/fs.h>
25#include <validation.h>
26
27#include <map>
28#include <unordered_map>
29
30namespace node {
31std::atomic_bool fReindex(false);
32
33std::vector<CBlockIndex *> BlockManager::GetAllBlockIndices() {
35 std::vector<CBlockIndex *> rv;
36 rv.reserve(m_block_index.size());
37 for (auto &[_, block_index] : m_block_index) {
38 rv.push_back(&block_index);
39 }
40 return rv;
41}
42
45 BlockMap::iterator it = m_block_index.find(hash);
46 return it == m_block_index.end() ? nullptr : &it->second;
47}
48
51 BlockMap::const_iterator it = m_block_index.find(hash);
52 return it == m_block_index.end() ? nullptr : &it->second;
53}
54
58
59 const auto [mi, inserted] =
60 m_block_index.try_emplace(block.GetHash(), block);
61 if (!inserted) {
62 return &mi->second;
63 }
64 CBlockIndex *pindexNew = &(*mi).second;
65
66 // We assign the sequence id to blocks only when the full data is available,
67 // to avoid miners withholding blocks but broadcasting headers, to get a
68 // competitive advantage.
70
71 pindexNew->phashBlock = &((*mi).first);
72 BlockMap::iterator miPrev = m_block_index.find(block.hashPrevBlock);
73 if (miPrev != m_block_index.end()) {
74 pindexNew->pprev = &(*miPrev).second;
75 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
76 pindexNew->BuildSkip();
77 }
78 pindexNew->nTimeReceived = GetTime();
79 pindexNew->nTimeMax =
80 (pindexNew->pprev
81 ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime)
82 : pindexNew->nTime);
83 pindexNew->nChainWork =
84 (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) +
86 pindexNew->RaiseValidity(BlockValidity::TREE);
87 if (best_header == nullptr ||
88 best_header->nChainWork < pindexNew->nChainWork) {
90 }
91
93 return pindexNew;
94}
95
99
100 for (auto &entry : m_block_index) {
101 CBlockIndex *pindex = &entry.second;
102 if (pindex->nFile == fileNumber) {
103 pindex->nStatus = pindex->nStatus.withData(false).withUndo(false);
104 pindex->nFile = 0;
105 pindex->nDataPos = 0;
106 pindex->nUndoPos = 0;
107 m_dirty_blockindex.insert(pindex);
108
109 // Prune from m_blocks_unlinked -- any block we prune would have
110 // to be downloaded again in order to consider its chain, at which
111 // point it would be considered as a candidate for
112 // m_blocks_unlinked or setBlockIndexCandidates.
113 auto range = m_blocks_unlinked.equal_range(pindex->pprev);
114 while (range.first != range.second) {
115 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it =
116 range.first;
117 range.first++;
118 if (_it->second == pindex) {
119 m_blocks_unlinked.erase(_it);
120 }
121 }
122 }
123 }
124
125 m_blockfile_info[fileNumber].SetNull();
127}
128
131 int chain_tip_height) {
133
135 if (chain_tip_height < 0) {
136 return;
137 }
138
139 // last block to prune is the lesser of (user-specified height,
140 // MIN_BLOCKS_TO_KEEP from the tip)
141 unsigned int nLastBlockWeCanPrune{std::min(
143 int count = 0;
145 if (m_blockfile_info[fileNumber].nSize == 0 ||
147 continue;
148 }
151 count++;
152 }
153 LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n",
155}
156
158 uint64_t nPruneAfterHeight,
160 bool is_ibd) {
162 if (chain_tip_height < 0 || GetPruneTarget() == 0) {
163 return;
164 }
165 if (uint64_t(chain_tip_height) <= nPruneAfterHeight) {
166 return;
167 }
168
169 unsigned int nLastBlockWeCanPrune = std::min(
172 // We don't check to prune until after we've allocated new space for files,
173 // so we should leave a buffer under our target to account for another
174 // allocation before the next pruning.
177 int count = 0;
178
180 // On a prune event, the chainstate DB is flushed.
181 // To avoid excessive prune events negating the benefit of high dbcache
182 // values, we should not prune too rapidly.
183 // So when pruning in IBD, increase the buffer a bit to avoid a re-prune
184 // too soon.
185 if (is_ibd) {
186 // Since this is only relevant during IBD, we use a fixed 10%
187 nBuffer += GetPruneTarget() / 10;
188 }
189
192 m_blockfile_info[fileNumber].nUndoSize;
193
194 if (m_blockfile_info[fileNumber].nSize == 0) {
195 continue;
196 }
197
198 // are we below our target?
200 break;
201 }
202
203 // don't prune files that could have a block within
204 // MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
205 if (m_blockfile_info[fileNumber].nHeightLast >
207 continue;
208 }
209
211 // Queue up the files for removal
214 count++;
215 }
216 }
217
219 "Prune: target=%dMiB actual=%dMiB diff=%dMiB "
220 "max_prune_height=%d removed %d blk/rev pairs\n",
221 GetPruneTarget() / 1024 / 1024, nCurrentUsage / 1024 / 1024,
222 (int64_t(GetPruneTarget()) - int64_t(nCurrentUsage)) / 1024 / 1024,
224}
225
226void BlockManager::UpdatePruneLock(const std::string &name,
227 const PruneLockInfo &lock_info) {
230}
231
234
235 if (hash.IsNull()) {
236 return nullptr;
237 }
238
239 const auto [mi, inserted] = m_block_index.try_emplace(hash);
240 CBlockIndex *pindex = &(*mi).second;
241 if (inserted) {
242 pindex->phashBlock = &((*mi).first);
243 }
244 return pindex;
245}
246
249 if (!m_block_tree_db->LoadBlockIndexGuts(
250 GetConsensus(),
251 [this](const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
252 return this->InsertBlockIndex(hash);
253 })) {
254 return false;
255 }
256
257 // Calculate nChainWork
258 std::vector<CBlockIndex *> vSortedByHeight{GetAllBlockIndices()};
259 std::sort(vSortedByHeight.begin(), vSortedByHeight.end(),
261
262 for (CBlockIndex *pindex : vSortedByHeight) {
263 if (ShutdownRequested()) {
264 return false;
265 }
266 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) +
267 GetBlockProof(*pindex);
268 pindex->nTimeMax =
269 (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime)
270 : pindex->nTime);
271
272 // We can link the chain of blocks for which we've received
273 // transactions at some point, or blocks that are assumed-valid on the
274 // basis of snapshot load (see PopulateAndValidateSnapshot()).
275 // Pruned nodes may have deleted the block.
276 if (pindex->nTx > 0) {
277 if (!pindex->UpdateChainStats() && pindex->pprev) {
278 m_blocks_unlinked.insert(std::make_pair(pindex->pprev, pindex));
279 }
280 }
281
282 if (!pindex->nStatus.hasFailed() && pindex->pprev &&
283 pindex->pprev->nStatus.hasFailed()) {
284 pindex->nStatus = pindex->nStatus.withFailedParent();
285 m_dirty_blockindex.insert(pindex);
286 }
287
288 if (pindex->pprev) {
289 pindex->BuildSkip();
290 }
291 }
292
293 return true;
294}
295
296bool BlockManager::WriteBlockIndexDB() {
297 std::vector<std::pair<int, const CBlockFileInfo *>> vFiles;
298 vFiles.reserve(m_dirty_fileinfo.size());
299 for (int i : m_dirty_fileinfo) {
300 vFiles.push_back(std::make_pair(i, &m_blockfile_info[i]));
301 }
302
303 m_dirty_fileinfo.clear();
304
305 std::vector<const CBlockIndex *> vBlocks;
306 vBlocks.reserve(m_dirty_blockindex.size());
307 for (const CBlockIndex *cbi : m_dirty_blockindex) {
308 vBlocks.push_back(cbi);
309 }
310
311 m_dirty_blockindex.clear();
312
313 if (!m_block_tree_db->WriteBatchSync(vFiles, m_last_blockfile, vBlocks)) {
314 return false;
315 }
316 return true;
317}
318
319bool BlockManager::LoadBlockIndexDB() {
320 if (!LoadBlockIndex()) {
321 return false;
322 }
323
324 // Load block file info
325 m_block_tree_db->ReadLastBlockFile(m_last_blockfile);
327 LogPrintf("%s: last block file = %i\n", __func__, m_last_blockfile);
328 for (int nFile = 0; nFile <= m_last_blockfile; nFile++) {
329 m_block_tree_db->ReadBlockFileInfo(nFile, m_blockfile_info[nFile]);
330 }
331 LogPrintf("%s: last block file info: %s\n", __func__,
333 for (int nFile = m_last_blockfile + 1; true; nFile++) {
334 CBlockFileInfo info;
335 if (m_block_tree_db->ReadBlockFileInfo(nFile, info)) {
336 m_blockfile_info.push_back(info);
337 } else {
338 break;
339 }
340 }
341
342 // Check presence of blk files
343 LogPrintf("Checking all blk files are present...\n");
344 std::set<int> setBlkDataFiles;
345 for (const auto &[_, block_index] : m_block_index) {
346 if (block_index.nStatus.hasData()) {
347 setBlkDataFiles.insert(block_index.nFile);
348 }
349 }
350
351 for (const int i : setBlkDataFiles) {
352 FlatFilePos pos(i, 0);
354 .IsNull()) {
355 return false;
356 }
357 }
358
359 // Check whether we have ever pruned block & undo files
360 m_block_tree_db->ReadFlag("prunedblockfiles", m_have_pruned);
361 if (m_have_pruned) {
362 LogPrintf(
363 "LoadBlockIndexDB(): Block files have previously been pruned\n");
364 }
365
366 // Check whether we need to continue reindexing
367 if (m_block_tree_db->IsReindexing()) {
368 fReindex = true;
369 }
370
371 return true;
372}
373
374void BlockManager::ScanAndUnlinkAlreadyPrunedFiles() {
376 if (!m_have_pruned) {
377 return;
378 }
379
380 std::set<int> block_files_to_prune;
382 if (m_blockfile_info[file_number].nSize == 0) {
384 }
385 }
386
388}
389
390const CBlockIndex *
393
394 for (const MapCheckpoints::value_type &i : reverse_iterate(checkpoints)) {
395 const BlockHash &hash = i.second;
396 const CBlockIndex *pindex = LookupBlockIndex(hash);
397 if (pindex) {
398 return pindex;
399 }
400 }
401
402 return nullptr;
403}
404
405bool BlockManager::IsBlockPruned(const CBlockIndex *pblockindex) {
407 return (m_have_pruned && !pblockindex->nStatus.hasData() &&
408 pblockindex->nTx > 0);
409}
410
411const CBlockIndex *
412BlockManager::GetFirstStoredBlock(const CBlockIndex &start_block) {
415 while (last_block->pprev && (last_block->pprev->nStatus.hasData())) {
417 }
418 return last_block;
419}
420
421// If we're using -prune with -reindex, then delete block files that will be
422// ignored by the reindex. Since reindexing works by starting at block file 0
423// and looping until a blockfile is missing, do the same here to delete any
424// later block files after a gap. Also delete all rev files since they'll be
425// rewritten by the reindex anyway. This ensures that m_blockfile_info is in
426// sync with what's actually on disk by the time we start downloading, so that
427// pruning works correctly.
429 std::map<std::string, fs::path> mapBlockFiles;
430
431 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
432 // Remove the rev files immediately and insert the blk file paths into an
433 // ordered map keyed by block file index.
434 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for "
435 "-reindex with -prune\n");
436 for (const auto &file : fs::directory_iterator{m_opts.blocks_dir}) {
437 const std::string path = fs::PathToString(file.path().filename());
438 if (fs::is_regular_file(file) && path.length() == 12 &&
439 path.substr(8, 4) == ".dat") {
440 if (path.substr(0, 3) == "blk") {
441 mapBlockFiles[path.substr(3, 5)] = file.path();
442 } else if (path.substr(0, 3) == "rev") {
443 remove(file.path());
444 }
445 }
446 }
447
448 // Remove all block files that aren't part of a contiguous set starting at
449 // zero by walking the ordered map (keys are block file indices) by keeping
450 // a separate counter. Once we hit a gap (or if 0 doesn't exist) start
451 // removing block files.
452 int contiguousCounter = 0;
453 for (const auto &item : mapBlockFiles) {
454 if (atoi(item.first) == contiguousCounter) {
456 continue;
457 }
458 remove(item.second);
459 }
460}
461
467
469 const CBlockUndo &blockundo, FlatFilePos &pos, const BlockHash &hashBlock,
471 // Open history file to append
473 if (fileout.IsNull()) {
474 return error("%s: OpenUndoFile failed", __func__);
475 }
476
477 // Write index header
478 unsigned int nSize = GetSerializeSize(blockundo, fileout.GetVersion());
479 fileout << messageStart << nSize;
480
481 // Write undo data
482 long fileOutPos = ftell(fileout.Get());
483 if (fileOutPos < 0) {
484 return error("%s: ftell failed", __func__);
485 }
486 pos.nPos = (unsigned int)fileOutPos;
488
489 // calculate & write checksum
490 HashWriter hasher{};
491 hasher << hashBlock;
492 hasher << blockundo;
493 fileout << hasher.GetHash();
494
495 return true;
496}
497
499 const CBlockIndex &index) const {
500 const FlatFilePos pos{WITH_LOCK(::cs_main, return index.GetUndoPos())};
501
502 if (pos.IsNull()) {
503 return error("%s: no undo data available", __func__);
504 }
505
506 // Open history file to read
508 if (filein.IsNull()) {
509 return error("%s: OpenUndoFile failed", __func__);
510 }
511
512 // Read block
514 // We need a CHashVerifier as reserializing may lose data
516 try {
517 verifier << index.pprev->GetBlockHash();
520 } catch (const std::exception &e) {
521 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
522 }
523
524 // Verify checksum
525 if (hashChecksum != verifier.GetHash()) {
526 return error("%s: Checksum mismatch", __func__);
527 }
528
529 return true;
530}
531
532void BlockManager::FlushUndoFile(int block_file, bool finalize) {
534 m_blockfile_info[block_file].nUndoSize);
535 if (!UndoFileSeq().Flush(undo_pos_old, finalize)) {
536 AbortNode("Flushing undo file to disk failed. This is likely the "
537 "result of an I/O error.");
538 }
539}
540
543
544 if (m_blockfile_info.empty()) {
545 // Return if we haven't loaded any blockfiles yet. This happens during
546 // chainstate init, when we call
547 // ChainstateManager::MaybeRebalanceCaches() (which then calls
548 // FlushStateToDisk()), resulting in a call to this function before we
549 // have populated `m_blockfile_info` via LoadBlockIndexDB().
550 return;
551 }
552 assert(static_cast<int>(m_blockfile_info.size()) > m_last_blockfile);
553
556 if (!BlockFileSeq().Flush(block_pos_old, fFinalize)) {
557 AbortNode("Flushing block file to disk failed. This is likely the "
558 "result of an I/O error.");
559 }
560 // we do not always flush the undo file, as the chain tip may be lagging
561 // behind the incoming blocks,
562 // e.g. during IBD or a sync after a node going offline
563 if (!fFinalize || finalize_undo) {
565 }
566}
567
570
571 uint64_t retval = 0;
572 for (const CBlockFileInfo &file : m_blockfile_info) {
573 retval += file.nSize + file.nUndoSize;
574 }
575
576 return retval;
577}
578
580 const std::set<int> &setFilesToPrune) const {
581 std::error_code error_code;
582 for (const int i : setFilesToPrune) {
583 FlatFilePos pos(i, 0);
584 const bool removed_blockfile{
585 fs::remove(BlockFileSeq().FileName(pos), error_code)};
586 const bool removed_undofile{
587 fs::remove(UndoFileSeq().FileName(pos), error_code)};
589 LogPrint(BCLog::BLOCKSTORE, "Prune: %s deleted blk/rev (%05u)\n",
590 __func__, i);
591 }
592 }
593}
594
596 return FlatFileSeq(m_opts.blocks_dir, "blk",
597 m_opts.fast_prune ? 0x4000 /* 16kb */
599}
600
604
606 bool fReadOnly) const {
607 return BlockFileSeq().Open(pos, fReadOnly);
608}
609
611FILE *BlockManager::OpenUndoFile(const FlatFilePos &pos, bool fReadOnly) const {
612 return UndoFileSeq().Open(pos, fReadOnly);
613}
614
618
620 unsigned int nHeight, CChain &active_chain,
621 uint64_t nTime, bool fKnown) {
623
624 unsigned int nFile = fKnown ? pos.nFile : m_last_blockfile;
625 if (m_blockfile_info.size() <= nFile) {
626 m_blockfile_info.resize(nFile + 1);
627 }
628
629 bool finalize_undo = false;
630 if (!fKnown) {
632 // Use smaller blockfiles in test-only -fastprune mode - but avoid
633 // the possibility of having a block not fit into the block file.
634 if (m_opts.fast_prune) {
635 max_blockfile_size = 0x10000; // 64kiB
637 // dynamically adjust the blockfile size to be larger than the
638 // added size
640 }
641 }
642 // TODO: we will also need to dynamically adjust the blockfile size
643 // or raise MAX_BLOCKFILE_SIZE when we reach block sizes larger than
644 // 128 MiB
646 while (m_blockfile_info[nFile].nSize + nAddSize >= max_blockfile_size) {
647 // when the undo file is keeping up with the block file, we want to
648 // flush it explicitly when it is lagging behind (more blocks arrive
649 // than are being connected), we let the undo block write case
650 // handle it
651 finalize_undo = (m_blockfile_info[nFile].nHeightLast ==
652 (unsigned int)active_chain.Tip()->nHeight);
653 nFile++;
654 if (m_blockfile_info.size() <= nFile) {
655 m_blockfile_info.resize(nFile + 1);
656 }
657 }
658 pos.nFile = nFile;
659 pos.nPos = m_blockfile_info[nFile].nSize;
660 }
661
662 if ((int)nFile != m_last_blockfile) {
663 if (!fKnown) {
664 LogPrint(BCLog::BLOCKSTORE, "Leaving block file %i: %s\n",
667 }
669 m_last_blockfile = nFile;
670 }
671
672 m_blockfile_info[nFile].AddBlock(nHeight, nTime);
673 if (fKnown) {
674 m_blockfile_info[nFile].nSize =
675 std::max(pos.nPos + nAddSize, m_blockfile_info[nFile].nSize);
676 } else {
677 m_blockfile_info[nFile].nSize += nAddSize;
678 }
679
680 if (!fKnown) {
681 bool out_of_space;
682 size_t bytes_allocated =
684 if (out_of_space) {
685 return AbortNode("Disk space is too low!",
686 _("Disk space is too low!"));
687 }
688 if (bytes_allocated != 0 && IsPruneMode()) {
689 m_check_for_pruning = true;
690 }
691 }
692
693 m_dirty_fileinfo.insert(nFile);
694 return true;
695}
696
698 FlatFilePos &pos, unsigned int nAddSize) {
699 pos.nFile = nFile;
700
702
703 pos.nPos = m_blockfile_info[nFile].nUndoSize;
704 m_blockfile_info[nFile].nUndoSize += nAddSize;
705 m_dirty_fileinfo.insert(nFile);
706
707 bool out_of_space;
708 size_t bytes_allocated =
710 if (out_of_space) {
711 return AbortNode(state, "Disk space is too low!",
712 _("Disk space is too low!"));
713 }
714 if (bytes_allocated != 0 && IsPruneMode()) {
715 m_check_for_pruning = true;
716 }
717
718 return true;
719}
720
722 const CBlock &block, FlatFilePos &pos,
724 // Open history file to append
726 if (fileout.IsNull()) {
727 return error("WriteBlockToDisk: OpenBlockFile failed");
728 }
729
730 // Write index header
731 unsigned int nSize = GetSerializeSize(block, fileout.GetVersion());
732 fileout << messageStart << nSize;
733
734 // Write block
735 long fileOutPos = ftell(fileout.Get());
736 if (fileOutPos < 0) {
737 return error("WriteBlockToDisk: ftell failed");
738 }
739
740 pos.nPos = (unsigned int)fileOutPos;
741 fileout << block;
742
743 return true;
744}
745
746bool BlockManager::WriteUndoDataForBlock(const CBlockUndo &blockundo,
748 CBlockIndex &block) {
750 // Write undo information to disk
751 if (block.GetUndoPos().IsNull()) {
753 if (!FindUndoPos(state, block.nFile, _pos,
755 return error("ConnectBlock(): FindUndoPos failed");
756 }
758 GetParams().DiskMagic())) {
759 return AbortNode(state, "Failed to write undo data");
760 }
761 // rev files are written in block height order, whereas blk files are
762 // written as blocks come in (often out of order) we want to flush the
763 // rev (undo) file once we've written the last block, which is indicated
764 // by the last height in the block file info as below; note that this
765 // does not catch the case where the undo writes are keeping up with the
766 // block writes (usually when a synced up node is getting newly mined
767 // blocks) -- this case is caught in the FindBlockPos function
768 if (_pos.nFile < m_last_blockfile &&
769 static_cast<uint32_t>(block.nHeight) ==
770 m_blockfile_info[_pos.nFile].nHeightLast) {
771 FlushUndoFile(_pos.nFile, true);
772 }
773
774 // update nUndoPos in block index
775 block.nUndoPos = _pos.nPos;
776 block.nStatus = block.nStatus.withUndo();
777 m_dirty_blockindex.insert(&block);
778 }
779
780 return true;
781}
782
784 const FlatFilePos &pos) const {
785 block.SetNull();
786
787 // Open history file to read
789 if (filein.IsNull()) {
790 return error("ReadBlockFromDisk: OpenBlockFile failed for %s",
791 pos.ToString());
792 }
793
794 // Read block
795 try {
796 filein >> block;
797 } catch (const std::exception &e) {
798 return error("%s: Deserialize or I/O error - %s at %s", __func__,
799 e.what(), pos.ToString());
800 }
801
802 // Check the header
803 if (!CheckProofOfWork(block.GetHash(), block.nBits, GetConsensus())) {
804 return error("ReadBlockFromDisk: Errors in block header at %s",
805 pos.ToString());
806 }
807
808 return true;
809}
810
812 const CBlockIndex &index) const {
813 const FlatFilePos block_pos{WITH_LOCK(cs_main, return index.GetBlockPos())};
814
815 if (!ReadBlockFromDisk(block, block_pos)) {
816 return false;
817 }
818
819 if (block.GetHash() != index.GetBlockHash()) {
820 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() "
821 "doesn't match index for %s at %s",
822 index.ToString(), block_pos.ToString());
823 }
824
825 return true;
826}
827
829 const FlatFilePos &pos) const {
830 // Open history file to read
832 if (filein.IsNull()) {
833 return error("ReadTxFromDisk: OpenBlockFile failed for %s",
834 pos.ToString());
835 }
836
837 // Read tx
838 try {
839 filein >> tx;
840 } catch (const std::exception &e) {
841 return error("%s: Deserialize or I/O error - %s at %s", __func__,
842 e.what(), pos.ToString());
843 }
844
845 return true;
846}
847
849 const FlatFilePos &pos) const {
850 // Open undo file to read
852 if (filein.IsNull()) {
853 return error("ReadTxUndoFromDisk: OpenUndoFile failed for %s",
854 pos.ToString());
855 }
856
857 // Read undo data
858 try {
859 filein >> tx_undo;
860 } catch (const std::exception &e) {
861 return error("%s: Deserialize or I/O error - %s at %s", __func__,
862 e.what(), pos.ToString());
863 }
864
865 return true;
866}
867
870 const FlatFilePos *dbp) {
871 unsigned int nBlockSize = ::GetSerializeSize(block, CLIENT_VERSION);
873 const auto position_known{dbp != nullptr};
874 if (position_known) {
875 blockPos = *dbp;
876 } else {
877 // When known, blockPos.nPos points at the offset of the block data in
878 // the blk file. That already accounts for the serialization header
879 // present in the file (the 4 magic message start bytes + the 4 length
880 // bytes = 8 bytes = BLOCK_SERIALIZATION_HEADER_SIZE). We add
881 // BLOCK_SERIALIZATION_HEADER_SIZE only for new blocks since they will
882 // have the serialization header added when written to disk.
883 nBlockSize +=
884 static_cast<unsigned int>(BLOCK_SERIALIZATION_HEADER_SIZE);
885 }
886 if (!FindBlockPos(blockPos, nBlockSize, nHeight, active_chain,
887 block.GetBlockTime(), position_known)) {
888 error("%s: FindBlockPos failed", __func__);
889 return FlatFilePos();
890 }
891 if (!position_known) {
892 if (!WriteBlockToDisk(block, blockPos, GetParams().DiskMagic())) {
893 AbortNode("Failed to write block");
894 return FlatFilePos();
895 }
896 }
897 return blockPos;
898}
899
901 std::atomic<bool> &m_importing;
902
903public:
905 assert(m_importing == false);
906 m_importing = true;
907 }
909 assert(m_importing == true);
910 m_importing = false;
911 }
912};
913
916 std::vector<fs::path> vImportFiles,
917 const fs::path &mempool_path) {
919
920 {
922
923 // -reindex
924 if (fReindex) {
925 int nFile = 0;
926 // Map of disk positions for blocks with unknown parent (only used
927 // for reindex); parent hash -> child disk position, multiple
928 // children can have the same parent.
929 std::multimap<BlockHash, FlatFilePos> blocks_with_unknown_parent;
930 while (true) {
931 FlatFilePos pos(nFile, 0);
932 if (!fs::exists(chainman.m_blockman.GetBlockPosFilename(pos))) {
933 // No block files left to reindex
934 break;
935 }
936 FILE *file = chainman.m_blockman.OpenBlockFile(pos, true);
937 if (!file) {
938 // This error is logged in OpenBlockFile
939 break;
940 }
941 LogPrintf("Reindexing block file blk%05u.dat...\n",
942 (unsigned int)nFile);
943 chainman.ActiveChainstate().LoadExternalBlockFile(
945 if (ShutdownRequested()) {
946 LogPrintf("Shutdown requested. Exit %s\n", __func__);
947 return;
948 }
949 nFile++;
950 }
951 WITH_LOCK(
952 ::cs_main,
953 chainman.m_blockman.m_block_tree_db->WriteReindexing(false));
954 fReindex = false;
955 LogPrintf("Reindexing finished\n");
956 // To avoid ending up in a situation without genesis block, re-try
957 // initializing (no-op if reindexing worked):
958 chainman.ActiveChainstate().LoadGenesisBlock();
959 }
960
961 // -loadblock=
962 for (const fs::path &path : vImportFiles) {
963 FILE *file = fsbridge::fopen(path, "rb");
964 if (file) {
965 LogPrintf("Importing blocks file %s...\n",
966 fs::PathToString(path));
967 chainman.ActiveChainstate().LoadExternalBlockFile(
968 file, /*dbp=*/nullptr,
969 /*blocks_with_unknown_parent=*/nullptr, avalanche);
970 if (ShutdownRequested()) {
971 LogPrintf("Shutdown requested. Exit %s\n", __func__);
972 return;
973 }
974 } else {
975 LogPrintf("Warning: Could not open blocks file %s\n",
976 fs::PathToString(path));
977 }
978 }
979
980 // Reconsider blocks we know are valid. They may have been marked
981 // invalid by, for instance, running an outdated version of the node
982 // software.
985 for (const MapCheckpoints::value_type &i : checkpoints) {
986 const BlockHash &hash = i.second;
987
988 LOCK(cs_main);
990 chainman.m_blockman.LookupBlockIndex(hash);
991 if (pblockindex && !pblockindex->nStatus.isValid()) {
992 LogPrintf("Reconsidering checkpointed block %s ...\n",
993 hash.GetHex());
994 chainman.ActiveChainstate().ResetBlockFailureFlags(pblockindex);
995 }
996
997 if (pblockindex && pblockindex->nStatus.isOnParkedChain()) {
998 LogPrintf("Unparking checkpointed block %s ...\n",
999 hash.GetHex());
1000 chainman.ActiveChainstate().UnparkBlockAndChildren(pblockindex);
1001 }
1002 }
1003
1004 // scan for better chains in the block chain database, that are not yet
1005 // connected in the active best chain
1006
1007 // We can't hold cs_main during ActivateBestChain even though we're
1008 // accessing the chainman unique_ptrs since ABC requires us not to be
1009 // holding cs_main, so retrieve the relevant pointers before the ABC
1010 // call.
1011 for (Chainstate *chainstate :
1012 WITH_LOCK(::cs_main, return chainman.GetAll())) {
1014 if (!chainstate->ActivateBestChain(state, nullptr, avalanche)) {
1015 LogPrintf("Failed to connect best block (%s)\n",
1016 state.ToString());
1017 StartShutdown();
1018 return;
1019 }
1020 }
1021
1022 if (chainman.m_blockman.StopAfterBlockImport()) {
1023 LogPrintf("Stopping after block import\n");
1024 StartShutdown();
1025 return;
1026 }
1027 } // End scope of ImportingNow
1028 chainman.ActiveChainstate().LoadMempool(mempool_path);
1029}
1030} // 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
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
std::string ToString() const
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition blockindex.h:32
const BlockHash * phashBlock
pointer to the hash of the block, if any.
Definition blockindex.h:29
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
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
const CCheckpointData & Checkpoints() const
Reads data from an underlying stream, while hashing the read data.
Definition hash.h:169
std::array< uint8_t, MESSAGE_START_SIZE > MessageMagic
Definition protocol.h:46
A mutable version of CTransaction.
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:693
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
SnapshotCompletionResult MaybeCompleteSnapshotValidation(std::function< void(bilingual_str)> shutdown_fnc=[](bilingual_str msg) { AbortNode(msg.original, msg);}) EXCLUSIVE_LOCKS_REQUIRED(Chainstate & ActiveChainstate() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
const CChainParams & GetParams() const
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
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
A writer stream (for serialization) that computes a 256-bit hash.
Definition hash.h:99
std::string ToString() const
Definition validation.h:125
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
std::set< int > m_dirty_fileinfo
Dirty block file entries.
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
const CChainParams & GetParams() const
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.
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
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.
const Consensus::Params & GetConsensus() const
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.
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.
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune) const
Actually unlink the specified files.
bool WriteBlockIndexDB() EXCLUSIVE_LOCKS_REQUIRED(bool LoadBlockIndexDB() 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.
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.
bool m_check_for_pruning
Global flag to indicate we should check to see if there are block/undo files that should be deleted.
bool FindUndoPos(BlockValidationState &state, int nFile, FlatFilePos &pos, unsigned int nAddSize)
bool IsPruneMode() const
Whether running in -prune mode.
void CleanupBlockRevFiles() const
std::atomic< bool > m_importing
std::vector< CBlockFileInfo > m_blockfile_info
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.
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.
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.
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:226
#define LogPrint(category,...)
Definition logging.h:211
#define LogPrintf(...)
Definition logging.h:207
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)
void ThreadImport(ChainstateManager &chainman, avalanche::Processor *const avalanche, 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)
static constexpr size_t BLOCK_SERIALIZATION_HEADER_SIZE
Size of header written by WriteBlockToDisk before a serialized CBlock.
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
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:87
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
Definition random.h:85
const char * name
Definition rest.cpp:47
reverse_range< T > reverse_iterate(T &x)
static std::string ToString(const CService &ip)
Definition db.h:37
@ SER_DISK
Definition serialize.h:153
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)
A BlockHash is a unqiue identifier for a block.
Definition blockhash.h:13
MapCheckpoints mapCheckpoints
Definition chainparams.h:34
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
#define AssertLockHeld(cs)
Definition sync.h:146
static int count
Definition tests.c:31
#define EXCLUSIVE_LOCKS_REQUIRED(...)
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition time.cpp:109
bilingual_str _(const char *psz)
Translation function.
Definition translation.h:68
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:94