41#include <unordered_map>
78bool BlockTreeDB::WriteBatchSync(
const std::vector<std::pair<int, const CBlockFileInfo*>>& fileInfo,
int nLastFile,
const std::vector<const CBlockIndex*>& blockinfo)
81 for (
const auto& [file, info] : fileInfo) {
93 return Write(std::make_pair(
DB_FLAG,
name), fValue ? uint8_t{
'1'} : uint8_t{
'0'});
102 fValue = ch == uint8_t{
'1'};
109 std::unique_ptr<CDBIterator> pcursor(
NewIterator());
113 while (pcursor->Valid()) {
114 if (interrupt)
return false;
115 std::pair<uint8_t, uint256> key;
118 if (pcursor->GetValue(diskindex)) {
123 pindexNew->nFile = diskindex.nFile;
124 pindexNew->nDataPos = diskindex.nDataPos;
125 pindexNew->nUndoPos = diskindex.nUndoPos;
131 pindexNew->nStatus = diskindex.nStatus;
132 pindexNew->
nTx = diskindex.
nTx;
135 LogError(
"%s: CheckProofOfWork failed: %s\n", __func__, pindexNew->
ToString());
141 LogError(
"%s: failed to read value\n", __func__);
167 if (pa < pb)
return false;
168 if (pa > pb)
return true;
179std::vector<CBlockIndex*> BlockManager::GetAllBlockIndices()
182 std::vector<CBlockIndex*> rv;
183 rv.reserve(m_block_index.size());
184 for (
auto& [
_, block_index] : m_block_index) {
185 rv.push_back(&block_index);
193 BlockMap::iterator it = m_block_index.find(hash);
194 return it == m_block_index.end() ? nullptr : &it->second;
200 BlockMap::const_iterator it = m_block_index.find(hash);
201 return it == m_block_index.end() ? nullptr : &it->second;
208 auto [mi, inserted] = m_block_index.try_emplace(block.
GetHash(), block);
220 BlockMap::iterator miPrev = m_block_index.find(block.
hashPrevBlock);
221 if (miPrev != m_block_index.end()) {
222 pindexNew->
pprev = &(*miPrev).second;
230 best_header = pindexNew;
243 for (
auto& entry : m_block_index) {
245 if (pindex->nFile == fileNumber) {
246 pindex->nStatus &= ~BLOCK_HAVE_DATA;
247 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
249 pindex->nDataPos = 0;
250 pindex->nUndoPos = 0;
258 while (range.first != range.second) {
259 std::multimap<CBlockIndex*, CBlockIndex*>::iterator _it = range.first;
261 if (_it->second == pindex) {
273 std::set<int>& setFilesToPrune,
274 int nManualPruneHeight,
285 const auto [min_block_to_prune, last_block_can_prune] = chainman.GetPruneRange(chain, nManualPruneHeight);
288 for (
int fileNumber = 0; fileNumber < this->
MaxBlockfileNum(); fileNumber++) {
290 if (fileinfo.nSize == 0 || fileinfo.nHeightLast > (
unsigned)last_block_can_prune || fileinfo.nHeightFirst < (
unsigned)min_block_to_prune) {
295 setFilesToPrune.insert(fileNumber);
298 LogPrintf(
"[%s] Prune (Manual): prune_height=%d removed %d blk/rev pairs\n",
299 chain.GetRole(), last_block_can_prune,
count);
303 std::set<int>& setFilesToPrune,
310 const auto target = std::max(
312 const uint64_t target_sync_height = chainman.m_best_header->nHeight;
321 const auto [min_block_to_prune, last_block_can_prune] = chainman.GetPruneRange(chain, last_prune);
328 uint64_t nBytesToPrune;
331 if (nCurrentUsage + nBuffer >= target) {
339 static constexpr uint64_t average_block_size = 1000000;
340 const uint64_t remaining_blocks = target_sync_height - chain_tip_height;
341 nBuffer += average_block_size * remaining_blocks;
344 for (
int fileNumber = 0; fileNumber < this->
MaxBlockfileNum(); fileNumber++) {
346 nBytesToPrune = fileinfo.nSize + fileinfo.nUndoSize;
348 if (fileinfo.nSize == 0) {
352 if (nCurrentUsage + nBuffer < target) {
358 if (fileinfo.nHeightLast > (
unsigned)last_block_can_prune || fileinfo.nHeightFirst < (
unsigned)min_block_to_prune) {
364 setFilesToPrune.insert(fileNumber);
365 nCurrentUsage -= nBytesToPrune;
370 LogPrint(
BCLog::PRUNE,
"[%s] target=%dMiB actual=%dMiB diff=%dMiB min_height=%d max_prune_height=%d removed %d blk/rev pairs\n",
371 chain.GetRole(), target / 1024 / 1024, nCurrentUsage / 1024 / 1024,
372 (int64_t(target) - int64_t(nCurrentUsage)) / 1024 / 1024,
373 min_block_to_prune, last_block_can_prune,
count);
376void BlockManager::UpdatePruneLock(
const std::string&
name,
const PruneLockInfo& lock_info) {
378 m_prune_locks[
name] = lock_info;
389 const auto [mi, inserted]{m_block_index.try_emplace(hash)};
399 if (!m_block_tree_db->LoadBlockIndexGuts(
404 if (snapshot_blockhash) {
406 if (!maybe_au_data) {
429 std::vector<CBlockIndex*> vSortedByHeight{GetAllBlockIndices()};
430 std::sort(vSortedByHeight.begin(), vSortedByHeight.end(),
436 if (previous_index && pindex->nHeight > previous_index->nHeight + 1) {
437 LogError(
"%s: block index is non-contiguous, index of height %d missing\n", __func__, previous_index->nHeight + 1);
440 previous_index = pindex;
441 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) +
GetBlockProof(*pindex);
442 pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
448 if (pindex->nTx > 0) {
451 pindex->GetBlockHash() == *snapshot_blockhash) {
453 Assert(pindex->m_chain_tx_count > 0);
454 }
else if (pindex->pprev->m_chain_tx_count > 0) {
455 pindex->m_chain_tx_count = pindex->pprev->m_chain_tx_count + pindex->nTx;
457 pindex->m_chain_tx_count = 0;
461 pindex->m_chain_tx_count = pindex->nTx;
476bool BlockManager::WriteBlockIndexDB()
479 std::vector<std::pair<int, const CBlockFileInfo*>> vFiles;
485 std::vector<const CBlockIndex*> vBlocks;
488 vBlocks.push_back(*it);
492 if (!m_block_tree_db->WriteBatchSync(vFiles, max_blockfile, vBlocks)) {
498bool BlockManager::LoadBlockIndexDB(
const std::optional<uint256>& snapshot_blockhash)
503 int max_blockfile_num{0};
506 m_block_tree_db->ReadLastBlockFile(max_blockfile_num);
508 LogPrintf(
"%s: last block file = %i\n", __func__, max_blockfile_num);
509 for (
int nFile = 0; nFile <= max_blockfile_num; nFile++) {
513 for (
int nFile = max_blockfile_num + 1;
true; nFile++) {
515 if (m_block_tree_db->ReadBlockFileInfo(nFile, info)) {
523 LogPrintf(
"Checking all blk files are present...\n");
524 std::set<int> setBlkDataFiles;
525 for (
const auto& [
_, block_index] : m_block_index) {
527 setBlkDataFiles.insert(block_index.nFile);
530 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) {
547 m_block_tree_db->ReadFlag(
"prunedblockfiles",
m_have_pruned);
549 LogPrintf(
"LoadBlockIndexDB(): Block files have previously been pruned\n");
553 bool fReindexing =
false;
554 m_block_tree_db->ReadReindexing(fReindexing);
560void BlockManager::ScanAndUnlinkAlreadyPrunedFiles()
568 std::set<int> block_files_to_prune;
569 for (
int file_number = 0; file_number < max_blockfile; file_number++) {
571 block_files_to_prune.insert(file_number);
582 for (
const MapCheckpoints::value_type& i : checkpoints | std::views::reverse) {
583 const uint256& hash = i.second;
592bool BlockManager::IsBlockPruned(
const CBlockIndex& block)
const
602 assert((last_block->nStatus & status_mask) == status_mask);
603 while (last_block->
pprev && ((last_block->
pprev->nStatus & status_mask) == status_mask)) {
606 if (last_block == lower_block)
return lower_block;
611 last_block = last_block->
pprev;
613 assert(last_block !=
nullptr);
617bool BlockManager::CheckBlockDataAvailability(
const CBlockIndex& upper_block,
const CBlockIndex& lower_block)
620 return GetFirstBlock(upper_block,
BLOCK_HAVE_DATA, &lower_block) == &lower_block;
631 std::map<std::string, fs::path> mapBlockFiles;
636 LogPrintf(
"Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
637 for (fs::directory_iterator it(
m_opts.
blocks_dir); it != fs::directory_iterator(); it++) {
639 if (fs::is_regular_file(*it) &&
640 path.length() == 12 &&
641 path.substr(8,4) ==
".dat")
643 if (path.substr(0, 3) ==
"blk") {
644 mapBlockFiles[path.substr(3, 5)] = it->path();
645 }
else if (path.substr(0, 3) ==
"rev") {
655 int nContigCounter = 0;
656 for (
const std::pair<const std::string, fs::path>& item : mapBlockFiles) {
676 if (fileout.IsNull()) {
677 LogError(
"%s: OpenUndoFile failed\n", __func__);
686 long fileOutPos = fileout.tell();
687 if (fileOutPos < 0) {
688 LogError(
"%s: ftell failed\n", __func__);
691 pos.
nPos = (
unsigned int)fileOutPos;
692 fileout << blockundo;
698 fileout << hasher.GetHash();
709 if (filein.IsNull()) {
710 LogError(
"%s: OpenUndoFile failed for %s\n", __func__, pos.ToString());
719 verifier >> blockundo;
720 filein >> hashChecksum;
721 }
catch (
const std::exception& e) {
722 LogError(
"%s: Deserialize or I/O error - %s at %s\n", __func__, e.what(), pos.ToString());
727 if (hashChecksum != verifier.GetHash()) {
728 LogError(
"%s: Checksum mismatch at %s\n", __func__, pos.ToString());
766 if (!fFinalize || finalize_undo) {
802 retval += file.nSize + file.nUndoSize;
810 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
814 if (removed_blockfile || removed_undofile) {
842 if (!m_blockfile_cursors[chain_type]) {
846 m_blockfile_cursors[chain_type] = new_cursor;
849 const int last_blockfile = m_blockfile_cursors[chain_type]->file_num;
851 int nFile = last_blockfile;
856 bool finalize_undo =
false;
857 unsigned int max_blockfile_size{MAX_BLOCKFILE_SIZE};
861 max_blockfile_size = 0x10000;
862 if (nAddSize >= max_blockfile_size) {
864 max_blockfile_size = nAddSize + 1;
867 assert(nAddSize < max_blockfile_size);
874 Assert(m_blockfile_cursors[chain_type])->undo_height);
889 if (nFile != last_blockfile) {
902 "Failed to flush previous block file %05i (finalize=1, finalize_undo=%i) before opening new block file %05i\n",
903 last_blockfile, finalize_undo, nFile);
932 auto& cursor{m_blockfile_cursors[chain_type]};
933 if (!cursor || cursor->file_num < pos.
nFile) {
939 const int nFile = pos.
nFile;
974 if (fileout.IsNull()) {
975 LogError(
"%s: OpenBlockFile failed\n", __func__);
984 long fileOutPos = fileout.tell();
985 if (fileOutPos < 0) {
986 LogError(
"%s: ftell failed\n", __func__);
989 pos.
nPos = (
unsigned int)fileOutPos;
1005 LogError(
"%s: FindUndoPos failed\n", __func__);
1025 }
else if (_pos.
nFile == cursor.file_num && block.
nHeight > cursor.undo_height) {
1026 cursor.undo_height = block.
nHeight;
1029 block.nUndoPos = _pos.
nPos;
1043 if (filein.IsNull()) {
1051 }
catch (
const std::exception& e) {
1052 LogError(
"%s: Deserialize or I/O error - %s at %s\n", __func__, e.what(), pos.
ToString());
1064 LogError(
"%s: Errors in block solution at %s\n", __func__, pos.
ToString());
1079 LogError(
"%s: GetHash() doesn't match index for %s at %s\n", __func__, index.
ToString(), block_pos.ToString());
1090 if (hpos.
nPos < 8) {
1096 if (filein.IsNull()) {
1103 unsigned int blk_size;
1105 filein >> blk_start >> blk_size;
1107 if (blk_start !=
GetParams().MessageStart()) {
1108 LogError(
"%s: Block magic mismatch for %s: %s versus expected %s\n", __func__, pos.
ToString(),
1115 LogError(
"%s: Block data is larger than maximum deserialization size for %s: %s versus %s\n", __func__, pos.
ToString(),
1120 block.resize(blk_size);
1122 }
catch (
const std::exception& e) {
1123 LogError(
"%s: Read from block file failed: %s for %s\n", __func__, e.what(), pos.
ToString());
1137 if (blockPos.IsNull()) {
1138 LogError(
"%s: FindNextBlockPos failed\n", __func__);
1152 std::array<std::byte, 8> xor_key{};
1164 xor_key_file >> xor_key;
1174 xor_key_file << xor_key;
1177 if (!opts.
use_xor && xor_key !=
decltype(xor_key){}) {
1178 throw std::runtime_error{
1179 strprintf(
"The blocksdir XOR-key can not be disabled when a random key was already stored! "
1180 "Stored key: '%s', stored path: '%s'.",
1185 return std::vector<std::byte>{xor_key.begin(), xor_key.end()};
1189 : m_prune_mode{opts.prune_target > 0},
1191 m_opts{
std::move(opts)},
1194 m_interrupt{interrupt} {}
1222 std::multimap<uint256, FlatFilePos> blocks_with_unknown_parent;
1229 if (file.IsNull()) {
1232 LogPrintf(
"Reindexing block file blk%05u.dat...\n", (
unsigned int)nFile);
1235 LogPrintf(
"Interrupt requested. Exit %s\n", __func__);
1248 for (
const fs::path& path : vImportFiles) {
1250 if (!file.IsNull()) {
1254 LogPrintf(
"Interrupt requested. Exit %s\n", __func__);
1269 if (!chainstate->ActivateBestChain(state,
nullptr)) {
1281 default: os.setstate(std::ios_base::failbit);
arith_uint256 GetBlockProof(const CBlockIndex &block)
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
@ BLOCK_HAVE_UNDO
undo data available in rev*.dat
@ BLOCK_HAVE_DATA
full block available in blk*.dat
@ BLOCK_FAILED_CHILD
descends from failed block
#define Assert(val)
Identity function.
Non-refcounted RAII wrapper for 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
uint64_t m_chain_tx_count
(memory only) Number of transactions in the chain up to and including 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 ...
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.
uint256 GetBlockHash() const
FlatFilePos GetUndoPos() const EXCLUSIVE_LOCKS_REQUIRED(
bool RaiseValidity(enum BlockStatus nUpTo) EXCLUSIVE_LOCKS_REQUIRED(
Raise the validity level of this block index entry.
unsigned int nTx
Number of transactions in this block.
int32_t nVersion
block header
int nHeight
height of the entry in the chain. The genesis block has height 0
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Undo information for a CBlock.
int Height() const
Return the maximal height in the chain.
const MessageStartChars & MessageStart() const
std::optional< AssumeutxoData > AssumeutxoForBlockhash(const uint256 &blockhash) const
uint64_t PruneAfterHeight() const
Batch of changes queued to be written to a CDBWrapper.
void Write(const K &key, const V &value)
bool WriteBatch(CDBBatch &batch, bool fSync=false)
bool Read(const K &key, V &value) const
CDBIterator * NewIterator()
bool Erase(const K &key, bool fSync=false)
bool Write(const K &key, const V &value, bool fSync=false)
bool Exists(const K &key) const
Used to marshal pointers into hashes for db storage.
uint256 ConstructBlockHash() const
Chainstate stores and provides an API to update our local knowledge of the current best chain.
CChain m_chain
The current chain of blockheaders we consult and build on.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
kernel::Notifications & GetNotifications() const
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
const util::SignalInterrupt & m_interrupt
void LoadExternalBlockFile(AutoFile &file_in, FlatFilePos *dbp=nullptr, std::multimap< uint256, FlatFilePos > *blocks_with_unknown_parent=nullptr)
Import blocks from an external file.
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...
void fillrand(Span< std::byte > output) noexcept
Fill a byte Span with random bytes.
FlatFileSeq represents a sequence of numbered files storing raw data.
FILE * Open(const FlatFilePos &pos, bool read_only=false) const
Open a handle to the file at the given position.
fs::path FileName(const FlatFilePos &pos) const
Get the name of the file at the given position.
bool Flush(const FlatFilePos &pos, bool finalize=false) const
Commit a file to disk, and optionally truncate off extra pre-allocated bytes if final.
size_t Allocate(const FlatFilePos &pos, size_t add_size, bool &out_of_space) const
Allocate additional space in a file after the given starting position.
Reads data from an underlying stream, while hashing the read data.
A writer stream (for serialization) that computes a 256-bit hash.
std::string ToString() const
constexpr bool IsNull() const
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
bool ReadLastBlockFile(int &nFile)
bool ReadFlag(const std::string &name, bool &fValue)
bool ReadBlockFileInfo(int nFile, CBlockFileInfo &info)
void ReadReindexing(bool &fReindexing)
bool WriteFlag(const std::string &name, bool fValue)
bool WriteBatchSync(const std::vector< std::pair< int, const CBlockFileInfo * > > &fileInfo, int nLastFile, const std::vector< const CBlockIndex * > &blockinfo)
bool WriteReindexing(bool fReindexing)
virtual void fatalError(const bilingual_str &message)
The fatal error notification is sent to notify the user when an error occurs in kernel code that can'...
virtual void flushError(const bilingual_str &message)
The flush error notification is sent to notify the user that an error occurred while flushing block d...
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.
const FlatFileSeq m_undo_file_seq
RecursiveMutex cs_LastBlockFile
const CChainParams & GetParams() const
bool FlushChainstateBlockFile(int tip_height)
void FindFilesToPrune(std::set< int > &setFilesToPrune, int last_prune, const Chainstate &chain, ChainstateManager &chainman)
Prune block and undo files (blk???.dat and rev???.dat) so that the disk space used is less than a use...
void UpdateBlockInfo(const CBlock &block, unsigned int nHeight, const FlatFilePos &pos)
Update blockfile info while processing a block during reindex.
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark one block file as pruned (modify associated database entries)
BlockfileType BlockfileTypeForHeight(int height)
std::atomic_bool m_blockfiles_indexed
Whether all blockfiles have been added to the block tree database.
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.
const Consensus::Params & GetConsensus() const
BlockManager(const util::SignalInterrupt &interrupt, Options opts)
bool ReadRawBlockFromDisk(std::vector< uint8_t > &block, const FlatFilePos &pos) const
std::set< CBlockIndex * > m_dirty_blockindex
Dirty block index entries.
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex &index) const
const std::vector< std::byte > m_xor_key
fs::path GetBlockPosFilename(const FlatFilePos &pos) const
Translation to a filesystem path.
bool FlushBlockFile(int blockfile_num, bool fFinalize, bool finalize_undo)
Return false if block file or undo file flushing fails.
uint64_t GetPruneTarget() const
Attempt to stay below this number of bytes of block files.
bool WriteBlockToDisk(const CBlock &block, FlatFilePos &pos) const
Write a block to disk.
int MaxBlockfileNum() const EXCLUSIVE_LOCKS_REQUIRED(cs_LastBlockFile)
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune) const
Actually unlink the specified files.
FlatFilePos FindNextBlockPos(unsigned int nAddSize, unsigned int nHeight, uint64_t nTime)
Helper function performing various preparations before a block can be saved to disk: Returns the corr...
bool CheckBlockDataAvailability(const CBlockIndex &upper_block LIFETIMEBOUND, const CBlockIndex &lower_block LIFETIMEBOUND) EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetFirstBlock(const CBlockIndex &upper_block LIFETIMEBOUND, uint32_t status_mask, const CBlockIndex *lower_block=nullptr) const EXCLUSIVE_LOCKS_REQUIRED(boo m_have_pruned)
Check if all blocks in the [upper_block, lower_block] range have data available.
bool FlushUndoFile(int block_file, bool finalize=false)
Return false if undo file flushing fails.
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
const util::SignalInterrupt & m_interrupt
const CBlockIndex * GetLastCheckpoint(const CCheckpointData &data) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Returns last CBlockIndex* that is a checkpoint.
bool IsBlockPruned(const CBlockIndex &block) const EXCLUSIVE_LOCKS_REQUIRED(void UpdatePruneLock(const std::string &name, const PruneLockInfo &lock_info) EXCLUSIVE_LOCKS_REQUIRED(AutoFil OpenBlockFile)(const FlatFilePos &pos, bool fReadOnly=false) const
Check whether the block associated with this index entry is pruned or not.
const FlatFileSeq m_block_file_seq
CBlockIndex * InsertBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Create a new block index entry for a given block hash.
bool WriteBlockIndexDB() EXCLUSIVE_LOCKS_REQUIRED(bool LoadBlockIndexDB(const std::optional< uint256 > &snapshot_blockhash) 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.
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
void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight, const Chainstate &chain, ChainstateManager &chainman)
std::atomic< bool > m_importing
std::vector< CBlockFileInfo > m_blockfile_info
bool UndoWriteToDisk(const CBlockUndo &blockundo, FlatFilePos &pos, const uint256 &hashBlock) const
bool WriteUndoDataForBlock(const CBlockUndo &blockundo, BlockValidationState &state, CBlockIndex &block) EXCLUSIVE_LOCKS_REQUIRED(FlatFilePo SaveBlockToDisk)(const CBlock &block, int nHeight)
Store block on disk and update block file statistics.
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
bool LoadBlockIndex(const std::optional< uint256 > &snapshot_blockhash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the blocktree off disk and into memory.
AutoFile OpenUndoFile(const FlatFilePos &pos, bool fReadOnly=false) const
Open an undo file (rev?????.dat)
std::optional< int > m_snapshot_height
The height of the base block of an assumeutxo snapshot, if one is in use.
ImportingNow(std::atomic< bool > &importing)
std::atomic< bool > & m_importing
Helper class that manages an interrupt flag, and allows a thread or signal to interrupt another threa...
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::map< int, uint256 > MapCheckpoints
#define LogPrintLevel(category, level,...)
#define LogPrint(category,...)
std::array< uint8_t, 4 > MessageStartChars
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)
static constexpr uint8_t DB_REINDEX_FLAG
static constexpr uint8_t DB_FLAG
static constexpr uint8_t DB_BLOCK_INDEX
static constexpr uint8_t DB_LAST_BLOCK
static constexpr uint8_t DB_BLOCK_FILES
static const unsigned int UNDOFILE_CHUNK_SIZE
The pre-allocation chunk size for rev?????.dat files (since 0.8)
void ImportBlocks(ChainstateManager &chainman, std::vector< fs::path > vImportFiles)
static auto InitBlocksdirXorKey(const BlockManager::Options &opts)
static const unsigned int BLOCKFILE_CHUNK_SIZE
The pre-allocation chunk size for blk?????.dat files (since 0.8)
std::ostream & operator<<(std::ostream &os, const BlockfileType &type)
static constexpr size_t BLOCK_SERIALIZATION_HEADER_SIZE
Size of header written by WriteBlockToDisk before a serialized CBlock.
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 TransactionSerParams TX_WITH_WITNESS
size_t GetSerializeSize(const T &t)
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...
bool CheckSignetBlockSolution(const CBlock &block, const Consensus::Params &consensusParams)
Extract signature and check whether a block has a valid solution.
Span< std::byte > MakeWritableByteSpan(V &&v) noexcept
T LocaleIndependentAtoi(std::string_view str)
Holds configuration for use during UTXO snapshot load and validation.
uint64_t m_chain_tx_count
Used to populate the m_chain_tx_count value, which is used during BlockManager::LoadBlockIndex().
MapCheckpoints mapCheckpoints
Parameters that influence chain consensus.
std::string ToString() const
An options struct for BlockManager, more ergonomically referred to as BlockManager::Options due to th...
Notifications & notifications
const fs::path blocks_dir
bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const
bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define AssertLockHeld(cs)
#define EXCLUSIVE_LOCKS_REQUIRED(...)
bilingual_str _(ConstevalStringLiteral str)
Translation function.
bool FatalError(Notifications ¬ifications, BlockValidationState &state, const bilingual_str &message)
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES