62 std::map<std::string, fs::path> mapBlockFiles;
67 LogPrintf(
"Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
69 for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator(); it++) {
70 if (fs::is_regular_file(*it) &&
71 it->path().filename().string().length() == 12 &&
72 it->path().filename().string().substr(8,4) ==
".dat")
74 if (it->path().filename().string().substr(0, 3) ==
"blk") {
75 mapBlockFiles[it->path().filename().string().substr(3, 5)] = it->path();
76 }
else if (it->path().filename().string().substr(0, 3) ==
"rev") {
86 int nContigCounter = 0;
87 for (
const std::pair<const std::string, fs::path>& item : mapBlockFiles) {
88 if (
atoi(item.first) == nContigCounter) {
113 return error(
"%s: OpenUndoFile failed", __func__);
118 fileout << messageStart << nSize;
121 long fileOutPos = ftell(fileout.
Get());
122 if (fileOutPos < 0) {
123 return error(
"%s: ftell failed", __func__);
125 pos.
nPos = (
unsigned int)fileOutPos;
126 fileout << blockundo;
141 return error(
"%s: no undo data available", __func__);
147 return error(
"%s: OpenUndoFile failed", __func__);
155 verifier >> blockundo;
156 filein >> hashChecksum;
157 }
catch (
const std::exception& e) {
158 return error(
"%s: Deserialize or I/O error - %s", __func__, e.what());
162 if (hashChecksum != verifier.
GetHash()) {
163 return error(
"%s: Checksum mismatch", __func__);
172 if (!
UndoFileSeq().Flush(undo_pos_old, finalize)) {
173 AbortNode(
"Flushing undo file to disk failed. This is likely the result of an I/O error.");
182 AbortNode(
"Flushing block file to disk failed. This is likely the result of an I/O error.");
195 retval += file.nSize + file.nUndoSize;
202 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
206 LogPrintf(
"Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
245 bool finalize_undo =
false;
280 return AbortNode(
"Disk space is too low!",
_(
"Disk space is too low!"));
304 return AbortNode(state,
"Disk space is too low!",
_(
"Disk space is too low!"));
318 return error(
"WriteBlockToDisk: OpenBlockFile failed");
323 fileout << messageStart << nSize;
326 long fileOutPos = ftell(fileout.
Get());
327 if (fileOutPos < 0) {
328 return error(
"WriteBlockToDisk: ftell failed");
330 pos.
nPos = (
unsigned int)fileOutPos;
342 return error(
"ConnectBlock(): FindUndoPos failed");
345 return AbortNode(state,
"Failed to write undo data");
372 return error(
"ReadBlockFromDisk: OpenBlockFile failed for %s", pos.
ToString());
378 }
catch (
const std::exception& e) {
379 return error(
"%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.
ToString());
384 return error(
"ReadBlockFromDisk: Errors in block header at %s", pos.
ToString());
389 return error(
"ReadBlockFromDisk: Errors in block solution at %s", pos.
ToString());
407 return error(
"ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
419 return error(
"%s: OpenBlockFile failed for %s", __func__, pos.
ToString());
424 unsigned int blk_size;
426 filein >> blk_start >> blk_size;
429 return error(
"%s: Block magic mismatch for %s: %s versus expected %s", __func__, pos.
ToString(),
435 return error(
"%s: Block data is larger than maximum deserialization size for %s: %s versus %s", __func__, pos.
ToString(),
439 block.resize(blk_size);
440 filein.
read((
char*)block.data(), blk_size);
441 }
catch (
const std::exception& e) {
442 return error(
"%s: Read from block file failed: %s for %s", __func__, e.what(), pos.
ToString());
464 if (dbp !=
nullptr) {
468 error(
"%s: FindBlockPos failed", __func__);
471 if (dbp ==
nullptr) {
513 LogPrintf(
"Reindexing block file blk%05u.dat...\n", (
unsigned int)nFile);
516 LogPrintf(
"Shutdown requested. Exit %s\n", __func__);
529 for (
const fs::path& path : vImportFiles) {
532 LogPrintf(
"Importing blocks file %s...\n", path.string());
535 LogPrintf(
"Shutdown requested. Exit %s\n", __func__);
539 LogPrintf(
"Warning: Could not open blocks file %s\n", path.string());
550 if (!chainstate->ActivateBestChain(state,
nullptr)) {
558 LogPrintf(
"Stopping after block import\n");
std::atomic_bool fImporting(false)
static FlatFileSeq BlockFileSeq()
std::string ToString() const
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
#define LogPrint(category,...)
FILE * fopen(const fs::path &p, const char *mode)
std::string FormatISO8601Date(int64_t nTime)
CBlockIndex * pprev
pointer to the index of the predecessor of this block
std::set< CBlockIndex * > setDirtyBlockIndex
Dirty block index entries.
uint32_t nStatus
Verification status of this block.
std::vector< CBlockFileInfo > vinfoBlockFile
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
An in-memory indexed chain of blocks.
static FILE * OpenUndoFile(const FlatFilePos &pos, bool fReadOnly=false)
Open an undo file (rev?????.dat)
CChainState stores and provides an API to update our local knowledge of the current best chain...
unsigned int nSize
number of used bytes of block file
void FlushBlockFile(bool fFinalize=false, bool finalize_undo=false)
bool FindBlockPos(FlatFilePos &pos, unsigned int nAddSize, unsigned int nHeight, CChain &active_chain, uint64_t nTime, bool fKnown=false)
FlatFilePos GetBlockPos() const
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
undo data available in rev*.dat
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
int nFile
Which # file this block is stored in (blk?????.dat)
bool IsBlockPruned(const CBlockIndex *pblockindex)
Check whether the block associated with this index entry is pruned or not.
unsigned int nHeightLast
highest height of block in file
Reads data from an underlying stream, while hashing the read data.
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
FILE * Open(const FlatFilePos &pos, bool read_only=false)
Open a handle to the file at the given position.
size_t GetSerializeSize(const T &t, int nVersion=0)
void LoadMempool(const ArgsManager &args)
Load the persisted mempool from disk.
uint256 GetBlockHash() const
bool WriteUndoDataForBlock(const CBlockUndo &blockundo, BlockValidationState &state, CBlockIndex *pindex, const CChainParams &chainparams)
RecursiveMutex cs_LastBlockFile
std::string ToString(const T &t)
Locale-independent version of std::to_string.
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
uint64_t nTimeFirst
earliest time of block in file
bool fPruneMode
True if we're running in -prune mode.
static bool WriteBlockToDisk(const CBlock &block, FlatFilePos &pos, const CMessageHeader::MessageStartChars &messageStart)
std::string ToString() const
bilingual_str _(const char *psz)
Translation function.
int atoi(const std::string &str)
static bool UndoWriteToDisk(const CBlockUndo &blockundo, FlatFilePos &pos, const uint256 &hashBlock, const CMessageHeader::MessageStartChars &messageStart)
bool signet_blocks
If true, witness commitments contain a payload equal to a Bitcoin Script solution to the signet chall...
std::atomic_bool fReindex(false)
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex)
fs::path GetBlockPosFilename(const FlatFilePos &pos)
Translation to a filesystem path.
unsigned int nHeightFirst
lowest height of block in file
bool fCheckForPruning
Global flag to indicate we should check to see if there are block/undo files that should be deleted...
const CMessageHeader::MessageStartChars & MessageStart() const
void read(char *pch, size_t nSize)
Parameters that influence chain consensus.
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params ¶ms)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
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.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
unsigned int nUndoPos
Byte offset within rev?????.dat where this block's undo data is stored.
uint256 GetHash()
Compute the double-SHA256 hash of all data written to this object.
std::string ToString() const
CChainState &InitializeChainstate(CTxMemPool *mempool, const std::optional< uint256 > &snapshot_blockhash=std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(std::vector< CChainState * GetAll)()
Instantiate a new chainstate and assign it based upon whether it is from a snapshot.
FlatFilePos SaveBlockToDisk(const CBlock &block, int nHeight, CChain &active_chain, const CChainParams &chainparams, const FlatFilePos *dbp)
Store block on disk.
FILE * Get() const
Get wrapped FILE* without transfer of ownership.
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
fs::path FileName(const FlatFilePos &pos) const
Get the name of the file at the given position.
The block chain is a tree shaped structure starting with the genesis block at the root...
Undo information for a CBlock.
static const int PROTOCOL_VERSION
network protocol versioning
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
unsigned int nBlocks
number of blocks stored in file
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...
std::unique_ptr< CBlockTreeDB > pblocktree
Global variable that points to the active block tree (protected by cs_main)
static FlatFileSeq UndoFileSeq()
std::set< int > setDirtyFileInfo
Dirty block file entries.
void StartShutdown()
Request shutdown of the application.
bool ReadRawBlockFromDisk(std::vector< uint8_t > &block, const FlatFilePos &pos, const CMessageHeader::MessageStartChars &message_start)
FlatFilePos GetUndoPos() const
A writer stream (for serialization) that computes a 256-bit hash.
const fs::path & GetBlocksDirPath() const
Get blocks directory path.
uint64_t nTimeLast
latest time of block in file
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
CChainState & ActiveChainstate() const
The most-work chain.
void CleanupBlockRevFiles()
static bool FindUndoPos(BlockValidationState &state, int nFile, FlatFilePos &pos, unsigned int nAddSize)
void ScheduleBatchPriority()
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
int nHeight
height of the entry in the chain. The genesis block has height 0
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
full block available in blk*.dat
bool fHavePruned
Pruning-related variables and constants.
void ThreadImport(ChainstateManager &chainman, std::vector< fs::path > vImportFiles, const ArgsManager &args)
static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT
std::string ToString() const
FlatFileSeq represents a sequence of numbered files storing raw data.
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
static const unsigned int UNDOFILE_CHUNK_SIZE
The pre-allocation chunk size for rev?????.dat files (since 0.8)
bool error(const char *fmt, const Args &... args)
FILE * OpenBlockFile(const FlatFilePos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
unsigned int nTx
Number of transactions in this block.
Non-refcounted RAII wrapper for FILE*.
bool AbortNode(const std::string &strMessage, bilingual_str user_message)
Abort with a message.
static void FlushUndoFile(int block_file, bool finalize=false)
bool CheckSignetBlockSolution(const CBlock &block, const Consensus::Params &consensusParams)
Extract signature and check whether a block has a valid solution.
static const unsigned int BLOCKFILE_CHUNK_SIZE
The pre-allocation chunk size for blk?????.dat files (since 0.8)