35 std::vector<CBlockIndex *> BlockManager::GetAllBlockIndices() {
37 std::vector<CBlockIndex *> rv;
38 rv.reserve(m_block_index.size());
39 for (
auto &[
_, block_index] : m_block_index) {
40 rv.push_back(&block_index);
47 BlockMap::iterator it = m_block_index.find(hash);
48 return it == m_block_index.end() ? nullptr : &it->second;
53 BlockMap::const_iterator it = m_block_index.find(hash);
54 return it == m_block_index.end() ? nullptr : &it->second;
61 const auto [mi, inserted] =
62 m_block_index.try_emplace(block.
GetHash(), block);
74 BlockMap::iterator miPrev = m_block_index.find(block.
hashPrevBlock);
75 if (miPrev != m_block_index.end()) {
76 pindexNew->
pprev = &(*miPrev).second;
89 if (best_header ==
nullptr ||
91 best_header = pindexNew;
102 for (
auto &entry : m_block_index) {
104 if (pindex->nFile == fileNumber) {
105 pindex->nStatus = pindex->nStatus.withData(
false).withUndo(
false);
107 pindex->nDataPos = 0;
108 pindex->nUndoPos = 0;
116 while (range.first != range.second) {
117 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it =
120 if (_it->second == pindex) {
132 int nManualPruneHeight,
133 int chain_tip_height) {
137 if (chain_tip_height < 0) {
143 unsigned int nLastBlockWeCanPrune{std::min(
152 setFilesToPrune.insert(fileNumber);
155 LogPrintf(
"Prune (Manual): prune_height=%d removed %d blk/rev pairs\n",
156 nLastBlockWeCanPrune,
count);
160 uint64_t nPruneAfterHeight,
161 int chain_tip_height,
int prune_height,
167 if (uint64_t(chain_tip_height) <= nPruneAfterHeight) {
171 unsigned int nLastBlockWeCanPrune = std::min(
178 uint64_t nBytesToPrune;
208 nLastBlockWeCanPrune) {
214 setFilesToPrune.insert(fileNumber);
215 nCurrentUsage -= nBytesToPrune;
221 "Prune: target=%dMiB actual=%dMiB diff=%dMiB "
222 "max_prune_height=%d removed %d blk/rev pairs\n",
223 nPruneTarget / 1024 / 1024, nCurrentUsage / 1024 / 1024,
224 ((int64_t)
nPruneTarget - (int64_t)nCurrentUsage) / 1024 / 1024,
225 nLastBlockWeCanPrune,
count);
235 const auto [mi, inserted] = m_block_index.try_emplace(hash);
245 if (!m_block_tree_db->LoadBlockIndexGuts(
252 std::vector<CBlockIndex *> vSortedByHeight{GetAllBlockIndices()};
253 std::sort(vSortedByHeight.begin(), vSortedByHeight.end(),
260 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) +
263 (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime)
270 if (pindex->nTx > 0) {
271 if (!pindex->UpdateChainStats() && pindex->pprev) {
276 if (!pindex->nStatus.hasFailed() && pindex->pprev &&
277 pindex->pprev->nStatus.hasFailed()) {
278 pindex->nStatus = pindex->nStatus.withFailedParent();
290 bool BlockManager::WriteBlockIndexDB() {
291 std::vector<std::pair<int, const CBlockFileInfo *>> vFiles;
299 std::vector<const CBlockIndex *> vBlocks;
302 vBlocks.push_back(cbi);
313 bool BlockManager::LoadBlockIndexDB() {
325 LogPrintf(
"%s: last block file info: %s\n", __func__,
329 if (m_block_tree_db->ReadBlockFileInfo(nFile, info)) {
337 LogPrintf(
"Checking all blk files are present...\n");
338 std::set<int> setBlkDataFiles;
339 for (
const auto &[
_, block_index] : m_block_index) {
340 if (block_index.nStatus.hasData()) {
341 setBlkDataFiles.insert(block_index.nFile);
345 for (
const int i : setBlkDataFiles) {
354 m_block_tree_db->ReadFlag(
"prunedblockfiles",
m_have_pruned);
357 "LoadBlockIndexDB(): Block files have previously been pruned\n");
361 if (m_block_tree_db->IsReindexing()) {
372 for (
const MapCheckpoints::value_type &i :
reverse_iterate(checkpoints)) {
383 bool BlockManager::IsBlockPruned(
const CBlockIndex *pblockindex) {
386 pblockindex->
nTx > 0);
393 while (last_block->
pprev && (last_block->
pprev->nStatus.hasData())) {
394 last_block = last_block->
pprev;
407 std::map<std::string, fs::path> mapBlockFiles;
412 LogPrintf(
"Removing unusable blk?????.dat and rev?????.dat files for "
413 "-reindex with -prune\n");
416 if (fs::is_regular_file(file) && path.length() == 12 &&
417 path.substr(8, 4) ==
".dat") {
418 if (path.substr(0, 3) ==
"blk") {
419 mapBlockFiles[path.substr(3, 5)] = file.path();
420 }
else if (path.substr(0, 3) ==
"rev") {
430 int contiguousCounter = 0;
431 for (
const auto &item : mapBlockFiles) {
432 if (
atoi(item.first) == contiguousCounter) {
452 return error(
"%s: OpenUndoFile failed", __func__);
457 fileout << messageStart << nSize;
460 long fileOutPos = ftell(fileout.
Get());
461 if (fileOutPos < 0) {
462 return error(
"%s: ftell failed", __func__);
464 pos.
nPos = (
unsigned int)fileOutPos;
465 fileout << blockundo;
480 return error(
"%s: no undo data available", __func__);
486 return error(
"%s: OpenUndoFile failed", __func__);
495 verifier >> blockundo;
496 filein >> hashChecksum;
497 }
catch (
const std::exception &e) {
498 return error(
"%s: Deserialize or I/O error - %s", __func__, e.what());
502 if (hashChecksum != verifier.
GetHash()) {
503 return error(
"%s: Checksum mismatch", __func__);
512 if (!
UndoFileSeq().Flush(undo_pos_old, finalize)) {
513 AbortNode(
"Flushing undo file to disk failed. This is likely the "
514 "result of an I/O error.");
523 AbortNode(
"Flushing block file to disk failed. This is likely the "
524 "result of an I/O error.");
529 if (!fFinalize || finalize_undo) {
539 retval += file.nSize + file.nUndoSize;
546 for (
const int i : setFilesToPrune) {
581 uint64_t nTime,
bool fKnown) {
589 bool finalize_undo =
false;
629 size_t bytes_allocated =
632 return AbortNode(
"Disk space is too low!",
633 _(
"Disk space is too low!"));
655 size_t bytes_allocated =
658 return AbortNode(state,
"Disk space is too low!",
659 _(
"Disk space is too low!"));
673 return error(
"WriteBlockToDisk: OpenBlockFile failed");
678 fileout << messageStart << nSize;
681 long fileOutPos = ftell(fileout.
Get());
682 if (fileOutPos < 0) {
683 return error(
"WriteBlockToDisk: ftell failed");
686 pos.
nPos = (
unsigned int)fileOutPos;
692 bool BlockManager::WriteUndoDataForBlock(
const CBlockUndo &blockundo,
702 return error(
"ConnectBlock(): FindUndoPos failed");
706 return AbortNode(state,
"Failed to write undo data");
716 static_cast<uint32_t
>(pindex->
nHeight) ==
722 pindex->nUndoPos = _pos.
nPos;
723 pindex->nStatus = pindex->nStatus.withUndo();
737 return error(
"ReadBlockFromDisk: OpenBlockFile failed for %s",
744 }
catch (
const std::exception &e) {
745 return error(
"%s: Deserialize or I/O error - %s at %s", __func__,
751 return error(
"ReadBlockFromDisk: Errors in block header at %s",
768 return error(
"ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() "
769 "doesn't match index for %s at %s",
770 pindex->
ToString(), block_pos.ToString());
780 return error(
"ReadTxFromDisk: OpenBlockFile failed for %s",
787 }
catch (
const std::exception &e) {
788 return error(
"%s: Deserialize or I/O error - %s at %s", __func__,
799 return error(
"ReadTxUndoFromDisk: OpenUndoFile failed for %s",
806 }
catch (
const std::exception &e) {
807 return error(
"%s: Deserialize or I/O error - %s at %s", __func__,
824 if (dbp !=
nullptr) {
829 error(
"%s: FindBlockPos failed", __func__);
832 if (dbp ==
nullptr) {
854 std::vector<fs::path> vImportFiles,
const ArgsManager &args) {
876 LogPrintf(
"Reindexing block file blk%05u.dat...\n",
877 (
unsigned int)nFile);
881 LogPrintf(
"Shutdown requested. Exit %s\n", __func__);
888 chainman.
m_blockman.m_block_tree_db->WriteReindexing(
false));
897 for (
const fs::path &path : vImportFiles) {
900 LogPrintf(
"Importing blocks file %s...\n",
904 LogPrintf(
"Shutdown requested. Exit %s\n", __func__);
908 LogPrintf(
"Warning: Could not open blocks file %s\n",
918 for (
const MapCheckpoints::value_type &i : checkpoints) {
924 if (pblockindex && !pblockindex->nStatus.isValid()) {
925 LogPrintf(
"Reconsidering checkpointed block %s ...\n",
930 if (pblockindex && pblockindex->nStatus.isOnParkedChain()) {
931 LogPrintf(
"Unparking checkpointed block %s ...\n",
947 if (!chainstate->ActivateBestChain(config, state,
nullptr)) {
948 LogPrintf(
"Failed to connect best block (%s)\n",
957 LogPrintf(
"Stopping after block import\n");
RecursiveMutex cs_main
Global state.
@ TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
arith_uint256 GetBlockProof(const CBlockIndex &block)
const CChainParams & Params()
Return the currently selected parameters.
std::map< int, BlockHash > MapCheckpoints
const fs::path & GetBlocksDirPath() const
Get blocks directory path.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Non-refcounted RAII wrapper for FILE*.
FILE * Get() const
Get wrapped FILE* without transfer of ownership.
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
The block chain is a tree shaped structure starting with the genesis block at the root,...
uint64_t nTimeReceived
(memory only) block header metadata
std::string ToString() const
CBlockIndex * pprev
pointer to the index of the predecessor of this block
void BuildSkip()
Build the skiplist pointer for this entry.
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
const BlockHash * phashBlock
pointer to the hash of the block, if any.
unsigned int nTimeMax
(memory only) Maximum nTime in the chain up to and including this block.
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
FlatFilePos GetUndoPos() const EXCLUSIVE_LOCKS_REQUIRED(
unsigned int nTx
Number of transactions in this block.
bool RaiseValidity(enum BlockValidity nUpTo) EXCLUSIVE_LOCKS_REQUIRED(
Raise the validity level of this block index entry.
BlockHash GetBlockHash() const
int nHeight
height of the entry in the chain. The genesis block has height 0
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Undo information for a CBlock.
An in-memory indexed chain of blocks.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
const CCheckpointData & Checkpoints() const
const CMessageHeader::MessageMagic & DiskMagic() const
Reads data from an underlying stream, while hashing the read data.
A writer stream (for serialization) that computes a 256-bit hash.
uint256 GetHash()
Compute the double-SHA256 hash of all data written to this object.
A mutable version of CTransaction.
Restore the UTXO in a Coin at a given COutPoint.
Chainstate stores and provides an API to update our local knowledge of the current best chain.
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
void UnparkBlockAndChildren(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove parked status from a block and its descendants.
void LoadMempool(const Config &config, const ArgsManager &args)
Load the persisted mempool from disk.
void ResetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove invalidity status from a block and its descendants.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Chainstate & ActiveChainstate() const
The most-work chain.
Chainstate &InitializeChainstate(CTxMemPool *mempool, const std::optional< BlockHash > &snapshot_blockhash=std::nullopt) LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate and assign it based upon whether it is from a snapshot.
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
virtual const CChainParams & GetChainParams() const =0
FlatFileSeq represents a sequence of numbered files storing raw data.
fs::path FileName(const FlatFilePos &pos) const
Get the name of the file at the given position.
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.
FILE * Open(const FlatFilePos &pos, bool read_only=false)
Open a handle to the file at the given position.
std::string ToString() const
std::string GetHex() const
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
std::set< int > m_dirty_fileinfo
Dirty block file entries.
bool WriteUndoDataForBlock(const CBlockUndo &blockundo, BlockValidationState &state, CBlockIndex *pindex, const CChainParams &chainparams) EXCLUSIVE_LOCKS_REQUIRED(FlatFilePo SaveBlockToDisk)(const CBlock &block, int nHeight, CChain &active_chain, const CChainParams &chainparams, const FlatFilePos *dbp)
Store block on disk.
RecursiveMutex cs_LastBlockFile
bool LoadBlockIndex(const Consensus::Params &consensus_params) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the blocktree off disk and into memory.
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...
void FlushUndoFile(int block_file, bool finalize=false)
bool FindBlockPos(FlatFilePos &pos, unsigned int nAddSize, unsigned int nHeight, CChain &active_chain, uint64_t nTime, bool fKnown)
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)
CBlockIndex * InsertBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Create a new block index entry for a given block hash.
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
const CBlockIndex * GetLastCheckpoint(const CCheckpointData &data) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Returns last CBlockIndex* that is a checkpoint.
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)
std::vector< CBlockFileInfo > m_blockfile_info
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
bool m_have_pruned
True if any block files have ever been pruned.
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)
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
#define LogPrint(category,...)
static bool exists(const path &p)
static std::string PathToString(const path &path)
Convert path object to a byte string.
FILE * fopen(const fs::path &p, const char *mode)
const CBlockIndex *GetFirstStoredBlock(const CBlockIndex *start_block) EXCLUSIVE_LOCKS_REQUIRED(voi CleanupBlockRevFiles)()
Find the first block that is not pruned.
static const unsigned int UNDOFILE_CHUNK_SIZE
The pre-allocation chunk size for rev?????.dat files (since 0.8)
const CBlockIndex * GetFirstStoredBlock(const CBlockIndex *start_block)
bool fPruneMode
Pruning-related variables and constants.
std::atomic_bool fImporting
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params ¶ms)
Functions for disk access for blocks.
static FILE * OpenUndoFile(const FlatFilePos &pos, bool fReadOnly=false)
Open an undo file (rev?????.dat)
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
static FlatFileSeq UndoFileSeq()
static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT
FILE * OpenBlockFile(const FlatFilePos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
static bool WriteBlockToDisk(const CBlock &block, FlatFilePos &pos, const CMessageHeader::MessageMagic &messageStart)
void ThreadImport(const Config &config, ChainstateManager &chainman, std::vector< fs::path > vImportFiles, const ArgsManager &args)
bool ReadTxFromDisk(CMutableTransaction &tx, const FlatFilePos &pos)
Functions for disk access for txs.
static constexpr unsigned int BLOCKFILE_CHUNK_SIZE
The pre-allocation chunk size for blk?????.dat files (since 0.8)
fs::path GetBlockPosFilename(const FlatFilePos &pos)
Translation to a filesystem path.
bool ReadTxUndoFromDisk(CTxUndo &tx_undo, const FlatFilePos &pos)
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
std::atomic_bool fReindex
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex)
static bool UndoWriteToDisk(const CBlockUndo &blockundo, FlatFilePos &pos, const BlockHash &hashBlock, const CMessageHeader::MessageMagic &messageStart)
static FlatFileSeq BlockFileSeq()
bool CheckProofOfWork(const BlockHash &hash, uint32_t nBits, const Consensus::Params ¶ms)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
reverse_range< T > reverse_iterate(T &x)
size_t GetSerializeSize(const T &t, int nVersion=0)
bool AbortNode(const std::string &strMessage, bilingual_str user_message)
Abort with a message.
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
void StartShutdown()
Request shutdown of the application.
int atoi(const std::string &str)
std::string ToString(const T &t)
Locale-independent version of std::to_string.
A BlockHash is a unqiue identifier for a block.
MapCheckpoints mapCheckpoints
Parameters that influence chain consensus.
std::string ToString() const
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
void ScheduleBatchPriority()
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
bool error(const char *fmt, const Args &...args)
#define EXCLUSIVE_LOCKS_REQUIRED(...)
T GetTime()
Return system time (or mocked time, if set)
bilingual_str _(const char *psz)
Translation function.
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...
static const int PROTOCOL_VERSION
network protocol versioning