28#include <unordered_map>
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);
45 BlockMap::iterator it = m_block_index.find(hash);
46 return it == m_block_index.end() ? nullptr : &it->second;
51 BlockMap::const_iterator it = m_block_index.find(hash);
52 return it == m_block_index.end() ? nullptr : &it->second;
59 const auto [mi, inserted] =
60 m_block_index.try_emplace(block.
GetHash(), block);
72 BlockMap::iterator miPrev = m_block_index.find(block.
hashPrevBlock);
73 if (miPrev != m_block_index.end()) {
74 pindexNew->
pprev = &(*miPrev).second;
87 if (best_header ==
nullptr ||
89 best_header = pindexNew;
100 for (
auto &entry : m_block_index) {
102 if (pindex->nFile == fileNumber) {
103 pindex->nStatus = pindex->nStatus.withData(
false).withUndo(
false);
105 pindex->nDataPos = 0;
106 pindex->nUndoPos = 0;
114 while (range.first != range.second) {
115 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it =
118 if (_it->second == pindex) {
130 int nManualPruneHeight,
131 int chain_tip_height) {
135 if (chain_tip_height < 0) {
141 unsigned int nLastBlockWeCanPrune{std::min(
150 setFilesToPrune.insert(fileNumber);
153 LogPrintf(
"Prune (Manual): prune_height=%d removed %d blk/rev pairs\n",
154 nLastBlockWeCanPrune,
count);
158 uint64_t nPruneAfterHeight,
159 int chain_tip_height,
int prune_height,
165 if (uint64_t(chain_tip_height) <= nPruneAfterHeight) {
169 unsigned int nLastBlockWeCanPrune = std::min(
176 uint64_t nBytesToPrune;
206 nLastBlockWeCanPrune) {
212 setFilesToPrune.insert(fileNumber);
213 nCurrentUsage -= nBytesToPrune;
219 "Prune: target=%dMiB actual=%dMiB diff=%dMiB "
220 "max_prune_height=%d removed %d blk/rev pairs\n",
222 (int64_t(
GetPruneTarget()) - int64_t(nCurrentUsage)) / 1024 / 1024,
223 nLastBlockWeCanPrune,
count);
226void BlockManager::UpdatePruneLock(
const std::string &
name,
229 m_prune_locks[
name] = lock_info;
239 const auto [mi, inserted] = m_block_index.try_emplace(hash);
249 if (!m_block_tree_db->LoadBlockIndexGuts(
258 std::vector<CBlockIndex *> vSortedByHeight{GetAllBlockIndices()};
259 std::sort(vSortedByHeight.begin(), vSortedByHeight.end(),
266 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) +
269 (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime)
276 if (pindex->nTx > 0) {
277 if (!pindex->UpdateChainStats() && pindex->pprev) {
282 if (!pindex->nStatus.hasFailed() && pindex->pprev &&
283 pindex->pprev->nStatus.hasFailed()) {
284 pindex->nStatus = pindex->nStatus.withFailedParent();
296bool BlockManager::WriteBlockIndexDB() {
297 std::vector<std::pair<int, const CBlockFileInfo *>> vFiles;
305 std::vector<const CBlockIndex *> vBlocks;
308 vBlocks.push_back(cbi);
319bool BlockManager::LoadBlockIndexDB() {
331 LogPrintf(
"%s: last block file info: %s\n", __func__,
335 if (m_block_tree_db->ReadBlockFileInfo(nFile, info)) {
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);
351 for (
const int i : setBlkDataFiles) {
360 m_block_tree_db->ReadFlag(
"prunedblockfiles",
m_have_pruned);
363 "LoadBlockIndexDB(): Block files have previously been pruned\n");
367 if (m_block_tree_db->IsReindexing()) {
374void BlockManager::ScanAndUnlinkAlreadyPrunedFiles() {
380 std::set<int> block_files_to_prune;
383 block_files_to_prune.insert(file_number);
394 for (
const MapCheckpoints::value_type &i :
reverse_iterate(checkpoints)) {
405bool BlockManager::IsBlockPruned(
const CBlockIndex *pblockindex) {
408 pblockindex->
nTx > 0);
412BlockManager::GetFirstStoredBlock(
const CBlockIndex &start_block) {
415 while (last_block->
pprev && (last_block->
pprev->nStatus.hasData())) {
416 last_block = last_block->
pprev;
429 std::map<std::string, fs::path> mapBlockFiles;
434 LogPrintf(
"Removing unusable blk?????.dat and rev?????.dat files for "
435 "-reindex with -prune\n");
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") {
452 int contiguousCounter = 0;
453 for (
const auto &item : mapBlockFiles) {
454 if (
atoi(item.first) == contiguousCounter) {
474 return error(
"%s: OpenUndoFile failed", __func__);
479 fileout << messageStart << nSize;
482 long fileOutPos = ftell(fileout.
Get());
483 if (fileOutPos < 0) {
484 return error(
"%s: ftell failed", __func__);
486 pos.
nPos = (
unsigned int)fileOutPos;
487 fileout << blockundo;
493 fileout << hasher.GetHash();
503 return error(
"%s: no undo data available", __func__);
509 return error(
"%s: OpenUndoFile failed", __func__);
518 verifier >> blockundo;
519 filein >> hashChecksum;
520 }
catch (
const std::exception &e) {
521 return error(
"%s: Deserialize or I/O error - %s", __func__, e.what());
525 if (hashChecksum != verifier.
GetHash()) {
526 return error(
"%s: Checksum mismatch", __func__);
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.");
557 AbortNode(
"Flushing block file to disk failed. This is likely the "
558 "result of an I/O error.");
563 if (!fFinalize || finalize_undo) {
573 retval += file.nSize + file.nUndoSize;
580 const std::set<int> &setFilesToPrune)
const {
581 std::error_code error_code;
582 for (
const int i : setFilesToPrune) {
584 const bool removed_blockfile{
586 const bool removed_undofile{
587 fs::remove(
UndoFileSeq().FileName(pos), error_code)};
588 if (removed_blockfile || removed_undofile) {
606 bool fReadOnly)
const {
621 uint64_t nTime,
bool fKnown) {
629 bool finalize_undo =
false;
635 max_blockfile_size = 0x10000;
636 if (nAddSize >= max_blockfile_size) {
639 max_blockfile_size = nAddSize + 1;
645 assert(nAddSize < max_blockfile_size);
682 size_t bytes_allocated =
685 return AbortNode(
"Disk space is too low!",
686 _(
"Disk space is too low!"));
708 size_t bytes_allocated =
711 return AbortNode(state,
"Disk space is too low!",
712 _(
"Disk space is too low!"));
727 return error(
"WriteBlockToDisk: OpenBlockFile failed");
732 fileout << messageStart << nSize;
735 long fileOutPos = ftell(fileout.
Get());
736 if (fileOutPos < 0) {
737 return error(
"WriteBlockToDisk: ftell failed");
740 pos.
nPos = (
unsigned int)fileOutPos;
746bool BlockManager::WriteUndoDataForBlock(
const CBlockUndo &blockundo,
755 return error(
"ConnectBlock(): FindUndoPos failed");
759 return AbortNode(state,
"Failed to write undo data");
769 static_cast<uint32_t
>(block.
nHeight) ==
775 block.nUndoPos = _pos.
nPos;
776 block.nStatus = block.nStatus.withUndo();
790 return error(
"ReadBlockFromDisk: OpenBlockFile failed for %s",
797 }
catch (
const std::exception &e) {
798 return error(
"%s: Deserialize or I/O error - %s at %s", __func__,
804 return error(
"ReadBlockFromDisk: Errors in block header at %s",
820 return error(
"ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() "
821 "doesn't match index for %s at %s",
822 index.
ToString(), block_pos.ToString());
833 return error(
"ReadTxFromDisk: OpenBlockFile failed for %s",
840 }
catch (
const std::exception &e) {
841 return error(
"%s: Deserialize or I/O error - %s at %s", __func__,
853 return error(
"ReadTxUndoFromDisk: OpenUndoFile failed for %s",
860 }
catch (
const std::exception &e) {
861 return error(
"%s: Deserialize or I/O error - %s at %s", __func__,
873 const auto position_known{dbp !=
nullptr};
874 if (position_known) {
888 error(
"%s: FindBlockPos failed", __func__);
891 if (!position_known) {
916 std::vector<fs::path> vImportFiles,
929 std::multimap<BlockHash, FlatFilePos> blocks_with_unknown_parent;
941 LogPrintf(
"Reindexing block file blk%05u.dat...\n",
942 (
unsigned int)nFile);
944 file, &pos, &blocks_with_unknown_parent,
avalanche);
946 LogPrintf(
"Shutdown requested. Exit %s\n", __func__);
953 chainman.
m_blockman.m_block_tree_db->WriteReindexing(
false));
962 for (
const fs::path &path : vImportFiles) {
965 LogPrintf(
"Importing blocks file %s...\n",
971 LogPrintf(
"Shutdown requested. Exit %s\n", __func__);
975 LogPrintf(
"Warning: Could not open blocks file %s\n",
985 for (
const MapCheckpoints::value_type &i : checkpoints) {
991 if (pblockindex && !pblockindex->nStatus.isValid()) {
992 LogPrintf(
"Reconsidering checkpointed block %s ...\n",
997 if (pblockindex && pblockindex->nStatus.isOnParkedChain()) {
998 LogPrintf(
"Unparking checkpointed block %s ...\n",
1014 if (!chainstate->ActivateBestChain(state,
nullptr,
avalanche)) {
1015 LogPrintf(
"Failed to connect best block (%s)\n",
1023 LogPrintf(
"Stopping after block import\n");
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)
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
FILE * Get() const
Get wrapped FILE* without transfer of ownership.
The block chain is a tree shaped structure starting with the genesis block at the root,...
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.
int64_t nTimeReceived
(memory only) block header metadata
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.
const CCheckpointData & Checkpoints() const
Reads data from an underlying stream, while hashing the read data.
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.
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.
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.
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.
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:...
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
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.
std::map< int, BlockHash > MapCheckpoints
bool error(const char *fmt, const Args &...args)
#define LogPrint(category,...)
static bool exists(const path &p)
static std::string PathToString(const path &path)
Convert path object to byte string.
FILE * fopen(const fs::path &p, const char *mode)
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 ¶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.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
A BlockHash is a unqiue identifier for a block.
MapCheckpoints mapCheckpoints
std::string ToString() const
const fs::path blocks_dir
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
bilingual_str _(const char *psz)
Translation function.
int atoi(const std::string &str)
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...