28#include <unordered_map>
33std::vector<CBlockIndex *> BlockManager::GetAllBlockIndices() {
35 std::vector<CBlockIndex *>
rv;
103 pindex->nStatus = pindex->nStatus.withData(
false).withUndo(
false);
105 pindex->nDataPos = 0;
106 pindex->nUndoPos = 0;
115 std::multimap<CBlockIndex *, CBlockIndex *>::iterator
_it =
118 if (
_it->second == pindex) {
153 LogPrintf(
"Prune (Manual): prune_height=%d removed %d blk/rev pairs\n",
219 "Prune: target=%dMiB actual=%dMiB diff=%dMiB "
220 "max_prune_height=%d removed %d blk/rev pairs\n",
226void BlockManager::UpdatePruneLock(
const std::string &
name,
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;
319bool BlockManager::LoadBlockIndexDB() {
343 LogPrintf(
"Checking all blk files are present...\n");
363 "LoadBlockIndexDB(): Block files have previously been pruned\n");
374void BlockManager::ScanAndUnlinkAlreadyPrunedFiles() {
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") {
442 }
else if (path.substr(0, 3) ==
"rev") {
520 }
catch (
const std::exception &
e) {
521 return error(
"%s: Deserialize or I/O error - %s",
__func__,
e.what());
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.");
573 retval += file.nSize + file.nUndoSize;
606 bool fReadOnly)
const {
685 return AbortNode(
"Disk space is too low!",
686 _(
"Disk space is too low!"));
711 return AbortNode(state,
"Disk space is too low!",
712 _(
"Disk space is too low!"));
727 return error(
"WriteBlockToDisk: OpenBlockFile failed");
737 return error(
"WriteBlockToDisk: ftell failed");
755 return error(
"ConnectBlock(): FindUndoPos failed");
759 return AbortNode(state,
"Failed to write undo data");
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",
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__,
941 LogPrintf(
"Reindexing block file blk%05u.dat...\n",
942 (
unsigned int)nFile);
953 chainman.
m_blockman.m_block_tree_db->WriteReindexing(
false));
965 LogPrintf(
"Importing blocks file %s...\n",
975 LogPrintf(
"Warning: Could not open blocks file %s\n",
985 for (
const MapCheckpoints::value_type &i :
checkpoints) {
992 LogPrintf(
"Reconsidering checkpointed block %s ...\n",
998 LogPrintf(
"Unparking checkpointed block %s ...\n",
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)
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
const BlockHash * phashBlock
pointer to the hash of the block, if any.
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.
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.
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.
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.
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...
reverse_range< T > reverse_iterate(T &x)
static std::string ToString(const CService &ip)
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.
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 AssertLockHeld(cs)
#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...