42 #include <unordered_map> 79 bool BlockTreeDB::WriteBatchSync(
const std::vector<std::pair<int, const CBlockFileInfo*>>& fileInfo,
int nLastFile,
const std::vector<const CBlockIndex*>& blockinfo)
82 for (
const auto& [file, info] : fileInfo) {
94 return Write(std::make_pair(
DB_FLAG,
name), fValue ? uint8_t{
'1'} : uint8_t{
'0'});
103 fValue = ch == uint8_t{
'1'};
110 std::unique_ptr<CDBIterator> pcursor(
NewIterator());
114 while (pcursor->Valid()) {
115 if (interrupt)
return false;
116 std::pair<uint8_t, uint256> key;
119 if (pcursor->GetValue(diskindex)) {
124 pindexNew->nFile = diskindex.nFile;
125 pindexNew->nDataPos = diskindex.nDataPos;
126 pindexNew->nUndoPos = diskindex.nUndoPos;
132 pindexNew->nStatus = diskindex.nStatus;
133 pindexNew->
nTx = diskindex.
nTx;
136 LogError(
"%s: CheckProofOfWork failed: %s\n", __func__, pindexNew->
ToString());
142 LogError(
"%s: failed to read value\n", __func__);
168 if (pa < pb)
return false;
169 if (pa > pb)
return true;
180 std::vector<CBlockIndex*> BlockManager::GetAllBlockIndices()
183 std::vector<CBlockIndex*> rv;
184 rv.reserve(m_block_index.size());
185 for (
auto& [
_, block_index] : m_block_index) {
186 rv.push_back(&block_index);
194 BlockMap::iterator it = m_block_index.find(hash);
195 return it == m_block_index.end() ? nullptr : &it->second;
201 BlockMap::const_iterator it = m_block_index.find(hash);
202 return it == m_block_index.end() ? nullptr : &it->second;
209 auto [mi, inserted] = m_block_index.try_emplace(block.
GetHash(), block);
221 BlockMap::iterator miPrev = m_block_index.find(block.
hashPrevBlock);
222 if (miPrev != m_block_index.end()) {
223 pindexNew->
pprev = &(*miPrev).second;
231 best_header = pindexNew;
244 for (
auto& entry : m_block_index) {
246 if (pindex->nFile == fileNumber) {
250 pindex->nDataPos = 0;
251 pindex->nUndoPos = 0;
259 while (range.first != range.second) {
260 std::multimap<CBlockIndex*, CBlockIndex*>::iterator _it = range.first;
262 if (_it->second == pindex) {
274 std::set<int>& setFilesToPrune,
275 int nManualPruneHeight,
286 const auto [min_block_to_prune, last_block_can_prune] = chainman.GetPruneRange(chain, nManualPruneHeight);
289 for (
int fileNumber = 0; fileNumber < this->
MaxBlockfileNum(); fileNumber++) {
291 if (fileinfo.nSize == 0 || fileinfo.nHeightLast > (
unsigned)last_block_can_prune || fileinfo.nHeightFirst < (unsigned)min_block_to_prune) {
296 setFilesToPrune.insert(fileNumber);
299 LogPrintf(
"[%s] Prune (Manual): prune_height=%d removed %d blk/rev pairs\n",
300 chain.GetRole(), last_block_can_prune,
count);
304 std::set<int>& setFilesToPrune,
311 const auto target = std::max(
313 const uint64_t target_sync_height = chainman.m_best_header->nHeight;
322 const auto [min_block_to_prune, last_block_can_prune] = chainman.GetPruneRange(chain, last_prune);
329 uint64_t nBytesToPrune;
332 if (nCurrentUsage + nBuffer >= target) {
340 static constexpr uint64_t average_block_size = 1000000;
341 const uint64_t remaining_blocks = target_sync_height - chain_tip_height;
342 nBuffer += average_block_size * remaining_blocks;
345 for (
int fileNumber = 0; fileNumber < this->
MaxBlockfileNum(); fileNumber++) {
347 nBytesToPrune = fileinfo.nSize + fileinfo.nUndoSize;
349 if (fileinfo.nSize == 0) {
353 if (nCurrentUsage + nBuffer < target) {
359 if (fileinfo.nHeightLast > (
unsigned)last_block_can_prune || fileinfo.nHeightFirst < (unsigned)min_block_to_prune) {
365 setFilesToPrune.insert(fileNumber);
366 nCurrentUsage -= nBytesToPrune;
371 LogDebug(
BCLog::PRUNE,
"[%s] target=%dMiB actual=%dMiB diff=%dMiB min_height=%d max_prune_height=%d removed %d blk/rev pairs\n",
372 chain.GetRole(), target / 1024 / 1024, nCurrentUsage / 1024 / 1024,
373 (int64_t(target) - int64_t(nCurrentUsage)) / 1024 / 1024,
374 min_block_to_prune, last_block_can_prune,
count);
377 void BlockManager::UpdatePruneLock(
const std::string&
name,
const PruneLockInfo& lock_info) {
379 m_prune_locks[
name] = lock_info;
390 const auto [mi, inserted]{m_block_index.try_emplace(hash)};
400 if (!m_block_tree_db->LoadBlockIndexGuts(
405 if (snapshot_blockhash) {
407 if (!maybe_au_data) {
430 std::vector<CBlockIndex*> vSortedByHeight{GetAllBlockIndices()};
431 std::sort(vSortedByHeight.begin(), vSortedByHeight.end(),
437 if (previous_index && pindex->nHeight > previous_index->nHeight + 1) {
438 LogError(
"%s: block index is non-contiguous, index of height %d missing\n", __func__, previous_index->nHeight + 1);
441 previous_index = pindex;
442 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) +
GetBlockProof(*pindex);
443 pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
449 if (pindex->nTx > 0) {
452 pindex->GetBlockHash() == *snapshot_blockhash) {
454 Assert(pindex->m_chain_tx_count > 0);
455 }
else if (pindex->pprev->m_chain_tx_count > 0) {
456 pindex->m_chain_tx_count = pindex->pprev->m_chain_tx_count + pindex->nTx;
458 pindex->m_chain_tx_count = 0;
462 pindex->m_chain_tx_count = pindex->nTx;
477 bool BlockManager::WriteBlockIndexDB()
480 std::vector<std::pair<int, const CBlockFileInfo*>> vFiles;
486 std::vector<const CBlockIndex*> vBlocks;
489 vBlocks.push_back(*it);
493 if (!m_block_tree_db->WriteBatchSync(vFiles, max_blockfile, vBlocks)) {
499 bool BlockManager::LoadBlockIndexDB(
const std::optional<uint256>& snapshot_blockhash)
504 int max_blockfile_num{0};
507 m_block_tree_db->ReadLastBlockFile(max_blockfile_num);
509 LogPrintf(
"%s: last block file = %i\n", __func__, max_blockfile_num);
510 for (
int nFile = 0; nFile <= max_blockfile_num; nFile++) {
514 for (
int nFile = max_blockfile_num + 1;
true; nFile++) {
516 if (m_block_tree_db->ReadBlockFileInfo(nFile, info)) {
524 LogPrintf(
"Checking all blk files are present...\n");
525 std::set<int> setBlkDataFiles;
526 for (
const auto& [
_, block_index] : m_block_index) {
528 setBlkDataFiles.insert(block_index.nFile);
531 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) {
548 m_block_tree_db->ReadFlag(
"prunedblockfiles",
m_have_pruned);
550 LogPrintf(
"LoadBlockIndexDB(): Block files have previously been pruned\n");
554 bool fReindexing =
false;
555 m_block_tree_db->ReadReindexing(fReindexing);
561 void BlockManager::ScanAndUnlinkAlreadyPrunedFiles()
569 std::set<int> block_files_to_prune;
570 for (
int file_number = 0; file_number < max_blockfile; file_number++) {
572 block_files_to_prune.insert(file_number);
583 for (
const MapCheckpoints::value_type& i : checkpoints | std::views::reverse) {
584 const uint256& hash = i.second;
593 bool BlockManager::IsBlockPruned(
const CBlockIndex& block)
const 603 assert((last_block->nStatus & status_mask) == status_mask);
604 while (last_block->
pprev && ((last_block->
pprev->nStatus & status_mask) == status_mask)) {
607 if (last_block == lower_block)
return lower_block;
612 last_block = last_block->
pprev;
614 assert(last_block !=
nullptr);
621 return GetFirstBlock(upper_block,
BLOCK_HAVE_DATA, &lower_block) == &lower_block;
632 std::map<std::string, fs::path> mapBlockFiles;
637 LogPrintf(
"Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
638 for (fs::directory_iterator it(
m_opts.
blocks_dir); it != fs::directory_iterator(); it++) {
640 if (fs::is_regular_file(*it) &&
641 path.length() == 12 &&
642 path.substr(8,4) ==
".dat")
644 if (path.substr(0, 3) ==
"blk") {
645 mapBlockFiles[path.substr(3, 5)] = it->path();
646 }
else if (path.substr(0, 3) ==
"rev") {
656 int nContigCounter = 0;
657 for (
const std::pair<const std::string, fs::path>& item : mapBlockFiles) {
658 if (LocaleIndependentAtoi<int>(item.first) == nContigCounter) {
679 if (filein.IsNull()) {
680 LogError(
"OpenUndoFile failed for %s", pos.ToString());
689 verifier >> blockundo;
690 filein >> hashChecksum;
691 }
catch (
const std::exception& e) {
692 LogError(
"%s: Deserialize or I/O error - %s at %s\n", __func__, e.what(), pos.ToString());
697 if (hashChecksum != verifier.GetHash()) {
698 LogError(
"%s: Checksum mismatch at %s\n", __func__, pos.ToString());
736 if (!fFinalize || finalize_undo) {
747 return BlockfileType::NORMAL;
772 retval += file.nSize + file.nUndoSize;
780 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
784 if (removed_blockfile || removed_undofile) {
812 if (!m_blockfile_cursors[chain_type]) {
816 m_blockfile_cursors[chain_type] = new_cursor;
819 const int last_blockfile = m_blockfile_cursors[chain_type]->file_num;
821 int nFile = last_blockfile;
826 bool finalize_undo =
false;
831 max_blockfile_size = 0x10000;
832 if (nAddSize >= max_blockfile_size) {
834 max_blockfile_size = nAddSize + 1;
837 assert(nAddSize < max_blockfile_size);
844 Assert(m_blockfile_cursors[chain_type])->undo_height);
859 if (nFile != last_blockfile) {
872 "Failed to flush previous block file %05i (finalize=1, finalize_undo=%i) before opening new block file %05i\n",
873 last_blockfile, finalize_undo, nFile);
902 auto& cursor{m_blockfile_cursors[chain_type]};
903 if (!cursor || cursor->file_num < pos.
nFile) {
909 const int nFile = pos.
nFile;
949 const unsigned int blockundo_size{
static_cast<unsigned int>(
GetSerializeSize(blockundo))};
956 if (fileout.IsNull()) {
965 fileout << blockundo;
971 fileout << hasher.GetHash();
987 }
else if (pos.
nFile == cursor.file_num && block.
nHeight > cursor.undo_height) {
988 cursor.undo_height = block.
nHeight;
991 block.nUndoPos = pos.
nPos;
1005 if (filein.IsNull()) {
1013 }
catch (
const std::exception& e) {
1014 LogError(
"%s: Deserialize or I/O error - %s at %s\n", __func__, e.what(), pos.
ToString());
1026 LogError(
"%s: Errors in block solution at %s\n", __func__, pos.
ToString());
1041 LogError(
"%s: GetHash() doesn't match index for %s at %s\n", __func__, index.
ToString(), block_pos.ToString());
1052 if (hpos.
nPos < 8) {
1058 if (filein.IsNull()) {
1065 unsigned int blk_size;
1067 filein >> blk_start >> blk_size;
1070 LogError(
"%s: Block magic mismatch for %s: %s versus expected %s\n", __func__, pos.
ToString(),
1077 LogError(
"%s: Block data is larger than maximum deserialization size for %s: %s versus %s\n", __func__, pos.
ToString(),
1082 block.resize(blk_size);
1084 }
catch (
const std::exception& e) {
1085 LogError(
"%s: Read from block file failed: %s for %s\n", __func__, e.what(), pos.
ToString());
1097 LogError(
"FindNextBlockPos failed");
1101 if (fileout.IsNull()) {
1119 std::array<std::byte, 8> xor_key{};
1124 bool first_run =
true;
1125 for (
const auto& entry : fs::directory_iterator(opts.
blocks_dir)) {
1127 if (!entry.is_regular_file() || !path.starts_with(
'.')) {
1133 if (opts.
use_xor && first_run) {
1143 xor_key_file >> xor_key;
1153 xor_key_file << xor_key;
1156 if (!opts.
use_xor && xor_key != decltype(xor_key){}) {
1157 throw std::runtime_error{
1158 strprintf(
"The blocksdir XOR-key can not be disabled when a random key was already stored! " 1159 "Stored key: '%s', stored path: '%s'.",
1164 return std::vector<std::byte>{xor_key.begin(), xor_key.end()};
1170 m_opts{std::move(opts)},
1173 m_interrupt{interrupt}
1175 m_block_tree_db = std::make_unique<BlockTreeDB>(m_opts.block_tree_db_params);
1177 if (m_opts.block_tree_db_params.wipe_data) {
1178 m_block_tree_db->WriteReindexing(
true);
1179 m_blockfiles_indexed =
false;
1182 CleanupBlockRevFiles();
1213 std::multimap<uint256, FlatFilePos> blocks_with_unknown_parent;
1220 if (file.IsNull()) {
1223 LogPrintf(
"Reindexing block file blk%05u.dat...\n", (
unsigned int)nFile);
1226 LogPrintf(
"Interrupt requested. Exit %s\n", __func__);
1239 for (
const fs::path& path : import_paths) {
1241 if (!file.IsNull()) {
1245 LogPrintf(
"Interrupt requested. Exit %s\n", __func__);
1260 if (!chainstate->ActivateBestChain(state,
nullptr)) {
1270 case BlockfileType::NORMAL: os <<
"normal";
break;
1272 default: os.setstate(std::ios_base::failbit);
bool Exists(const K &key) const
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
std::optional< int > m_snapshot_height
The height of the base block of an assumeutxo snapshot, if one is in use.
std::string ToString() const
bool WriteBatchSync(const std::vector< std::pair< int, const CBlockFileInfo *>> &fileInfo, int nLastFile, const std::vector< const CBlockIndex *> &blockinfo)
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
std::set< int > m_dirty_fileinfo
Dirty block file entries.
const util::SignalInterrupt & m_interrupt
bool m_check_for_pruning
Global flag to indicate we should check to see if there are block/undo files that should be deleted...
void UpdateBlockInfo(const CBlock &block, unsigned int nHeight, const FlatFilePos &pos)
Update blockfile info while processing a block during reindex.
bool ReadRawBlock(std::vector< uint8_t > &block, const FlatFilePos &pos) const
bool WriteBlockUndo(const CBlockUndo &blockundo, BlockValidationState &state, CBlockIndex &block) EXCLUSIVE_LOCKS_REQUIRED(FlatFilePos WriteBlock(const CBlock &block, int nHeight)
Store block on disk and update block file statistics.
bool IsPruneMode() const
Whether running in -prune mode.
FILE * fopen(const fs::path &p, const char *mode)
static constexpr uint8_t DB_FLAG
void CleanupBlockRevFiles() const
descends from failed block
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Batch of changes queued to be written to a CDBWrapper.
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
static constexpr uint8_t DB_BLOCK_INDEX
bool ReadBlockFileInfo(int nFile, CBlockFileInfo &info)
RecursiveMutex cs_LastBlockFile
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
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.
size_t GetSerializeSize(const T &t)
const Consensus::Params & GetConsensus() const
Span< std::byte > MakeWritableByteSpan(V &&v) noexcept
bool WriteReindexing(bool fReindexing)
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
int Height() const
Return the maximal height in the chain.
AutoFile OpenUndoFile(const FlatFilePos &pos, bool fReadOnly=false) const
Open an undo file (rev?????.dat)
bool FlushBlockFile(int blockfile_num, bool fFinalize, bool finalize_undo)
Return false if block file or undo file flushing fails.
bool ReadBlock(CBlock &block, const FlatFilePos &pos) const
Functions for disk access for blocks.
std::atomic< bool > & m_importing
undo data available in rev*.dat
BlockManager(const util::SignalInterrupt &interrupt, Options opts)
void LoadExternalBlockFile(AutoFile &file_in, FlatFilePos *dbp=nullptr, std::multimap< uint256, FlatFilePos > *blocks_with_unknown_parent=nullptr)
Import blocks from an external file.
bool ReadFlag(const std::string &name, bool &fValue)
CChain m_chain
The current chain of blockheaders we consult and build on.
consteval auto _(util::TranslatedLiteral str)
void ImportBlocks(ChainstateManager &chainman, std::span< const fs::path > import_paths)
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune) const
Actually unlink the specified files.
Non-refcounted RAII wrapper for FILE*.
static constexpr uint8_t DB_REINDEX_FLAG
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'...
const util::SignalInterrupt & m_interrupt
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.
bool ReadLastBlockFile(int &nFile)
void fillrand(Span< std::byte > output) noexcept
Fill a byte Span with random bytes.
std::array< uint8_t, 4 > MessageStartChars
uint256 GetBlockHash() const
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...
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...
void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight, const Chainstate &chain, ChainstateManager &chainman)
int MaxBlockfileNum() const EXCLUSIVE_LOCKS_REQUIRED(cs_LastBlockFile)
uint64_t PruneAfterHeight() const
static const unsigned int BLOCKFILE_CHUNK_SIZE
The pre-allocation chunk size for blk?????.dat files (since 0.8)
bool IsBlockPruned(const CBlockIndex &block) const EXCLUSIVE_LOCKS_REQUIRED(void UpdatePruneLock(const std::string &name, const PruneLockInfo &lock_info) EXCLUSIVE_LOCKS_REQUIRED(AutoFile OpenBlockFile(const FlatFilePos &pos, bool fReadOnly=false) const
Check whether the block associated with this index entry is pruned or not.
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.
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...
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.
An options struct for BlockManager, more ergonomically referred to as BlockManager::Options due to th...
unsigned int nTimeMax
(memory only) Maximum nTime in the chain up to and including this block.
static std::string PathToString(const path &path)
Convert path object to a byte string.
Chainstate stores and provides an API to update our local knowledge of the current best chain...
static auto InitBlocksdirXorKey(const BlockManager::Options &opts)
static constexpr size_t BLOCK_SERIALIZATION_HEADER_SIZE
Size of header written by WriteBlock before a serialized CBlock (8 bytes)
bool Erase(const K &key, bool fSync=false)
bool FindUndoPos(BlockValidationState &state, int nFile, FlatFilePos &pos, unsigned int nAddSize)
uint64_t m_chain_tx_count
(memory only) Number of transactions in the chain up to and including this block. ...
std::string ToString() const
std::optional< AssumeutxoData > AssumeutxoForBlockhash(const uint256 &blockhash) const
A writer stream (for serialization) that computes a 256-bit hash.
ImportingNow(std::atomic< bool > &importing)
kernel::Notifications & GetNotifications() const
const kernel::BlockManagerOpts m_opts
const FlatFileSeq m_block_file_seq
CDBIterator * NewIterator()
BlockfileType BlockfileTypeForHeight(int height)
bool signet_blocks
If true, witness commitments contain a payload equal to a Bitcoin Script solution to the signet chall...
void Write(const K &key, const V &value)
#define LogPrintLevel(category, level,...)
void BuildSkip()
Build the skiplist pointer for this entry.
std::atomic_bool m_blockfiles_indexed
Whether all blockfiles have been added to the block tree database.
Used to marshal pointers into hashes for db storage.
bool LoadBlockIndex(const std::optional< uint256 > &snapshot_blockhash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the blocktree off disk and into memory.
Parameters that influence chain consensus.
bool WriteFlag(const std::string &name, bool fValue)
Notifications & notifications
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.
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool Read(const K &key, V &value) const
bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const
constexpr bool IsNull() const
bool Flush(const FlatFilePos &pos, bool finalize=false) const
Commit a file to disk, and optionally truncate off extra pre-allocated bytes if final.
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
FILE * Open(const FlatFilePos &pos, bool read_only=false) const
Open a handle to the file at the given position.
FlatFilePos GetUndoPos() const EXCLUSIVE_LOCKS_REQUIRED(
const CBlockIndex * GetLastCheckpoint(const CCheckpointData &data) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Returns last CBlockIndex* that is a checkpoint.
const FlatFileSeq m_undo_file_seq
const CChainParams & GetParams() const
const std::vector< std::byte > m_xor_key
Helper class that manages an interrupt flag, and allows a thread or signal to interrupt another threa...
int32_t nVersion
block header
const CChainParams & GetParams() const
std::string ToString() const
uint256 ConstructBlockHash() const
bool Write(const K &key, const V &value, bool fSync=false)
#define EXCLUSIVE_LOCKS_REQUIRED(...)
fs::path FileName(const FlatFilePos &pos) const
Get the name of the file at the given position.
fs::path GetBlockPosFilename(const FlatFilePos &pos) const
Translation to a filesystem path.
#define LogDebug(category,...)
static constexpr uint8_t DB_LAST_BLOCK
bool FlushUndoFile(int block_file, bool finalize=false)
Return false if undo file flushing fails.
std::set< CBlockIndex * > m_dirty_blockindex
Dirty block index entries.
The block chain is a tree shaped structure starting with the genesis block at the root...
Undo information for a CBlock.
const fs::path blocks_dir
uint64_t m_chain_tx_count
Used to populate the m_chain_tx_count value, which is used during BlockManager::LoadBlockIndex().
const MessageStartChars & MessageStart() const
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network) ...
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
bool RaiseValidity(enum BlockStatus nUpTo) EXCLUSIVE_LOCKS_REQUIRED(
Raise the validity level of this block index entry.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Holds configuration for use during UTXO snapshot load and validation.
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...
CBlockIndex * InsertBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Create a new block index entry for a given block hash.
bool FlushChainstateBlockFile(int tip_height)
Reads data from an underlying stream, while hashing the read data.
static const unsigned int UNDOFILE_CHUNK_SIZE
The pre-allocation chunk size for rev?????.dat files (since 0.8)
void ReadReindexing(bool &fReindexing)
bool WriteBatch(CDBBatch &batch, bool fSync=false)
arith_uint256 GetBlockProof(const CBlockIndex &block)
bool FatalError(Notifications ¬ifications, BlockValidationState &state, const bilingual_str &message)
int nHeight
height of the entry in the chain. The genesis block has height 0
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
void CheckBlockDataAvailability(BlockManager &blockman, const CBlockIndex &blockindex, bool check_for_undo)
full block available in blk*.dat
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
static constexpr size_t UNDO_DATA_DISK_OVERHEAD
Total overhead when writing undo data: header (8 bytes) plus checksum (32 bytes)
static bool exists(const path &p)
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark one block file as pruned (modify associated database entries)
FlatFileSeq represents a sequence of numbered files storing raw data.
static constexpr uint8_t DB_BLOCK_FILES
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
std::atomic< bool > m_importing
uint64_t GetPruneTarget() const
Attempt to stay below this number of bytes of block files.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
std::ostream & operator<<(std::ostream &os, const BlockfileType &type)
unsigned int nTx
Number of transactions in this block.
std::map< int, uint256 > MapCheckpoints
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...
bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const
std::string ToString(const T &t)
Locale-independent version of std::to_string.
#define Assert(val)
Identity function.
static constexpr TransactionSerParams TX_WITH_WITNESS
bool CheckSignetBlockSolution(const CBlock &block, const Consensus::Params &consensusParams)
Extract signature and check whether a block has a valid solution.
bool ReadBlockUndo(CBlockUndo &blockundo, const CBlockIndex &index) const
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
std::vector< CBlockFileInfo > m_blockfile_info