63 std::map<std::string, fs::path> mapBlockFiles;
68 LogPrintf(
"Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
70 for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator(); it++) {
72 if (fs::is_regular_file(*it) &&
73 path.length() == 12 &&
74 path.substr(8,4) ==
".dat")
76 if (path.substr(0, 3) ==
"blk") {
77 mapBlockFiles[path.substr(3, 5)] = it->path();
78 }
else if (path.substr(0, 3) ==
"rev") {
88 int nContigCounter = 0;
89 for (
const std::pair<const std::string, fs::path>& item : mapBlockFiles) {
90 if (LocaleIndependentAtoi<int>(item.first) == nContigCounter) {
115 return error(
"%s: OpenUndoFile failed", __func__);
120 fileout << messageStart << nSize;
123 long fileOutPos = ftell(fileout.
Get());
124 if (fileOutPos < 0) {
125 return error(
"%s: ftell failed", __func__);
127 pos.
nPos = (
unsigned int)fileOutPos;
128 fileout << blockundo;
143 return error(
"%s: no undo data available", __func__);
149 return error(
"%s: OpenUndoFile failed", __func__);
157 verifier >> blockundo;
158 filein >> hashChecksum;
159 }
catch (
const std::exception& e) {
160 return error(
"%s: Deserialize or I/O error - %s", __func__, e.what());
164 if (hashChecksum != verifier.
GetHash()) {
165 return error(
"%s: Checksum mismatch", __func__);
174 if (!
UndoFileSeq().Flush(undo_pos_old, finalize)) {
175 AbortNode(
"Flushing undo file to disk failed. This is likely the result of an I/O error.");
184 AbortNode(
"Flushing block file to disk failed. This is likely the result of an I/O error.");
197 retval += file.nSize + file.nUndoSize;
204 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
247 bool finalize_undo =
false;
282 return AbortNode(
"Disk space is too low!",
_(
"Disk space is too low!"));
306 return AbortNode(state,
"Disk space is too low!",
_(
"Disk space is too low!"));
320 return error(
"WriteBlockToDisk: OpenBlockFile failed");
325 fileout << messageStart << nSize;
328 long fileOutPos = ftell(fileout.
Get());
329 if (fileOutPos < 0) {
330 return error(
"WriteBlockToDisk: ftell failed");
332 pos.
nPos = (
unsigned int)fileOutPos;
344 return error(
"ConnectBlock(): FindUndoPos failed");
347 return AbortNode(state,
"Failed to write undo data");
374 return error(
"ReadBlockFromDisk: OpenBlockFile failed for %s", pos.
ToString());
380 }
catch (
const std::exception& e) {
381 return error(
"%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.
ToString());
386 return error(
"ReadBlockFromDisk: Errors in block header at %s", pos.
ToString());
391 return error(
"ReadBlockFromDisk: Errors in block solution at %s", pos.
ToString());
405 return error(
"ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
406 pindex->
ToString(), block_pos.ToString());
417 return error(
"%s: OpenBlockFile failed for %s", __func__, pos.
ToString());
422 unsigned int blk_size;
424 filein >> blk_start >> blk_size;
427 return error(
"%s: Block magic mismatch for %s: %s versus expected %s", __func__, pos.
ToString(),
433 return error(
"%s: Block data is larger than maximum deserialization size for %s: %s versus %s", __func__, pos.
ToString(),
437 block.resize(blk_size);
438 filein.
read((
char*)block.data(), blk_size);
439 }
catch (
const std::exception& e) {
440 return error(
"%s: Read from block file failed: %s for %s", __func__, e.what(), pos.
ToString());
462 if (dbp !=
nullptr) {
466 error(
"%s: FindBlockPos failed", __func__);
469 if (dbp ==
nullptr) {
512 LogPrintf(
"Reindexing block file blk%05u.dat...\n", (
unsigned int)nFile);
515 LogPrintf(
"Shutdown requested. Exit %s\n", __func__);
520 WITH_LOCK(::
cs_main, chainman.m_blockman.m_block_tree_db->WriteReindexing(
false));
528 for (
const fs::path& path : vImportFiles) {
534 LogPrintf(
"Shutdown requested. Exit %s\n", __func__);
549 if (!chainstate->ActivateBestChain(state,
nullptr)) {
557 LogPrintf(
"Stopping after block import\n");
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
void FlushBlockFile(bool fFinalize=false, bool finalize_undo=false)
static void FlushUndoFile(int block_file, bool finalize=false)
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex)
std::atomic_bool fImporting(false)
std::set< CBlockIndex * > setDirtyBlockIndex
Dirty block index entries.
bool fHavePruned
Pruning-related variables and constants.
void ThreadImport(ChainstateManager &chainman, std::vector< fs::path > vImportFiles, const ArgsManager &args)
FILE * OpenBlockFile(const FlatFilePos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
std::vector< CBlockFileInfo > vinfoBlockFile
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
bool FindBlockPos(FlatFilePos &pos, unsigned int nAddSize, unsigned int nHeight, CChain &active_chain, uint64_t nTime, bool fKnown=false)
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
static FlatFileSeq BlockFileSeq()
RecursiveMutex cs_LastBlockFile
void CleanupBlockRevFiles()
bool ReadRawBlockFromDisk(std::vector< uint8_t > &block, const FlatFilePos &pos, const CMessageHeader::MessageStartChars &message_start)
bool IsBlockPruned(const CBlockIndex *pblockindex)
Check whether the block associated with this index entry is pruned or not.
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
fs::path GetBlockPosFilename(const FlatFilePos &pos)
Translation to a filesystem path.
static bool WriteBlockToDisk(const CBlock &block, FlatFilePos &pos, const CMessageHeader::MessageStartChars &messageStart)
std::atomic_bool fReindex(false)
bool fCheckForPruning
Global flag to indicate we should check to see if there are block/undo files that should be deleted.
bool WriteUndoDataForBlock(const CBlockUndo &blockundo, BlockValidationState &state, CBlockIndex *pindex, const CChainParams &chainparams)
static bool FindUndoPos(BlockValidationState &state, int nFile, FlatFilePos &pos, unsigned int nAddSize)
bool fPruneMode
True if we're running in -prune mode.
static FILE * OpenUndoFile(const FlatFilePos &pos, bool fReadOnly=false)
Open an undo file (rev?????.dat)
FlatFilePos SaveBlockToDisk(const CBlock &block, int nHeight, CChain &active_chain, const CChainParams &chainparams, const FlatFilePos *dbp)
Store block on disk.
static FlatFileSeq UndoFileSeq()
std::set< int > setDirtyFileInfo
Dirty block file entries.
static bool UndoWriteToDisk(const CBlockUndo &blockundo, FlatFilePos &pos, const uint256 &hashBlock, const CMessageHeader::MessageStartChars &messageStart)
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
static const unsigned int UNDOFILE_CHUNK_SIZE
The pre-allocation chunk size for rev?????.dat files (since 0.8)
static const unsigned int BLOCKFILE_CHUNK_SIZE
The pre-allocation chunk size for blk?????.dat files (since 0.8)
static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
@ BLOCK_HAVE_UNDO
undo data available in rev*.dat
@ BLOCK_HAVE_DATA
full block available in blk*.dat
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*.
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
FILE * Get() const
Get wrapped FILE* without transfer of ownership.
void read(char *pch, size_t nSize)
uint64_t nTimeFirst
earliest time of block in file
uint64_t nTimeLast
latest time of block in file
std::string ToString() const
unsigned int nHeightFirst
lowest height of block in file
unsigned int nHeightLast
highest height of block in file
unsigned int nBlocks
number of blocks stored in file
unsigned int nSize
number of used bytes of block file
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
int nFile
Which # file this block is stored in (blk?????.dat)
FlatFilePos GetBlockPos() const
unsigned int nUndoPos
Byte offset within rev?????.dat where this block's undo data is stored.
uint256 GetBlockHash() const
unsigned int nTx
Number of transactions in this block.
FlatFilePos GetUndoPos() const
int nHeight
height of the entry in the chain. The genesis block has height 0
uint32_t nStatus
Verification status of this block.
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 CMessageHeader::MessageStartChars & MessageStart() const
CChainState stores and provides an API to update our local knowledge of the current best chain.
bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size) EXCLUSIVE_LOCKS_REQUIRED(void LoadExternalBlockFile(FILE *fileIn, FlatFilePos *dbp=nullptr)
Resize the CoinsViews caches dynamically and flush state to disk.
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
void LoadMempool(const ArgsManager &args)
Load the persisted mempool from disk.
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.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
CChainState &InitializeChainstate(CTxMemPool *mempool, const std::optional< uint256 > &snapshot_blockhash=std::nullopt) LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(std::vector< CChainState * GetAll)()
Instantiate a new chainstate and assign it based upon whether it is from a snapshot.
CChainState & ActiveChainstate() const
The most-work chain.
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
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
static const 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 byte string.
FILE * fopen(const fs::path &p, const char *mode)
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.
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...
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.
bool CheckSignetBlockSolution(const CBlock &block, const Consensus::Params &consensusParams)
Extract signature and check whether a block has a valid solution.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Parameters that influence chain consensus.
bool signet_blocks
If true, witness commitments contain a payload equal to a Bitcoin Script solution to the signet chall...
std::string ToString() const
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
void SetSyscallSandboxPolicy(SyscallSandboxPolicy syscall_policy)
Force the current thread (and threads created from the current thread) into a restricted-service oper...
@ INITIALIZATION_LOAD_BLOCKS
bool error(const char *fmt, const Args &... args)
std::string FormatISO8601Date(int64_t nTime)
bilingual_str _(const char *psz)
Translation function.
void ScheduleBatchPriority()
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
static const int PROTOCOL_VERSION
network protocol versioning