Bitcoin Core 22.99.0
P2P Digital Currency
blockstorage.cpp
Go to the documentation of this file.
1// Copyright (c) 2011-2021 The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <node/blockstorage.h>
6
7#include <chain.h>
8#include <chainparams.h>
9#include <clientversion.h>
11#include <flatfile.h>
12#include <fs.h>
13#include <hash.h>
14#include <pow.h>
15#include <shutdown.h>
16#include <signet.h>
17#include <streams.h>
18#include <undo.h>
20#include <util/system.h>
21#include <validation.h>
22
23std::atomic_bool fImporting(false);
24std::atomic_bool fReindex(false);
25bool fHavePruned = false;
26bool fPruneMode = false;
27uint64_t nPruneTarget = 0;
28
29// TODO make namespace {
31std::vector<CBlockFileInfo> vinfoBlockFile;
37bool fCheckForPruning = false;
38
40std::set<CBlockIndex*> setDirtyBlockIndex;
41
43std::set<int> setDirtyFileInfo;
44// } // namespace
45
46static FILE* OpenUndoFile(const FlatFilePos& pos, bool fReadOnly = false);
49
50bool IsBlockPruned(const CBlockIndex* pblockindex)
51{
52 return (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0);
53}
54
55// If we're using -prune with -reindex, then delete block files that will be ignored by the
56// reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
57// is missing, do the same here to delete any later block files after a gap. Also delete all
58// rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
59// is in sync with what's actually on disk by the time we start downloading, so that pruning
60// works correctly.
62{
63 std::map<std::string, fs::path> mapBlockFiles;
64
65 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
66 // Remove the rev files immediately and insert the blk file paths into an
67 // ordered map keyed by block file index.
68 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
69 fs::path blocksdir = gArgs.GetBlocksDirPath();
70 for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator(); it++) {
71 const std::string path = fs::PathToString(it->path().filename());
72 if (fs::is_regular_file(*it) &&
73 path.length() == 12 &&
74 path.substr(8,4) == ".dat")
75 {
76 if (path.substr(0, 3) == "blk") {
77 mapBlockFiles[path.substr(3, 5)] = it->path();
78 } else if (path.substr(0, 3) == "rev") {
79 remove(it->path());
80 }
81 }
82 }
83
84 // Remove all block files that aren't part of a contiguous set starting at
85 // zero by walking the ordered map (keys are block file indices) by
86 // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
87 // start removing block files.
88 int nContigCounter = 0;
89 for (const std::pair<const std::string, fs::path>& item : mapBlockFiles) {
90 if (LocaleIndependentAtoi<int>(item.first) == nContigCounter) {
91 nContigCounter++;
92 continue;
93 }
94 remove(item.second);
95 }
96}
97
98std::string CBlockFileInfo::ToString() const
99{
100 return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, FormatISO8601Date(nTimeFirst), FormatISO8601Date(nTimeLast));
101}
102
104{
106
107 return &vinfoBlockFile.at(n);
108}
109
110static bool UndoWriteToDisk(const CBlockUndo& blockundo, FlatFilePos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
111{
112 // Open history file to append
114 if (fileout.IsNull()) {
115 return error("%s: OpenUndoFile failed", __func__);
116 }
117
118 // Write index header
119 unsigned int nSize = GetSerializeSize(blockundo, fileout.GetVersion());
120 fileout << messageStart << nSize;
121
122 // Write undo data
123 long fileOutPos = ftell(fileout.Get());
124 if (fileOutPos < 0) {
125 return error("%s: ftell failed", __func__);
126 }
127 pos.nPos = (unsigned int)fileOutPos;
128 fileout << blockundo;
129
130 // calculate & write checksum
132 hasher << hashBlock;
133 hasher << blockundo;
134 fileout << hasher.GetHash();
135
136 return true;
137}
138
139bool UndoReadFromDisk(CBlockUndo& blockundo, const CBlockIndex* pindex)
140{
141 FlatFilePos pos = pindex->GetUndoPos();
142 if (pos.IsNull()) {
143 return error("%s: no undo data available", __func__);
144 }
145
146 // Open history file to read
147 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
148 if (filein.IsNull()) {
149 return error("%s: OpenUndoFile failed", __func__);
150 }
151
152 // Read block
153 uint256 hashChecksum;
154 CHashVerifier<CAutoFile> verifier(&filein); // We need a CHashVerifier as reserializing may lose data
155 try {
156 verifier << pindex->pprev->GetBlockHash();
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());
161 }
162
163 // Verify checksum
164 if (hashChecksum != verifier.GetHash()) {
165 return error("%s: Checksum mismatch", __func__);
166 }
167
168 return true;
169}
170
171static void FlushUndoFile(int block_file, bool finalize = false)
172{
173 FlatFilePos undo_pos_old(block_file, vinfoBlockFile[block_file].nUndoSize);
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.");
176 }
177}
178
179void FlushBlockFile(bool fFinalize = false, bool finalize_undo = false)
180{
183 if (!BlockFileSeq().Flush(block_pos_old, fFinalize)) {
184 AbortNode("Flushing block file to disk failed. This is likely the result of an I/O error.");
185 }
186 // we do not always flush the undo file, as the chain tip may be lagging behind the incoming blocks,
187 // e.g. during IBD or a sync after a node going offline
188 if (!fFinalize || finalize_undo) FlushUndoFile(nLastBlockFile, finalize_undo);
189}
190
192{
194
195 uint64_t retval = 0;
196 for (const CBlockFileInfo& file : vinfoBlockFile) {
197 retval += file.nSize + file.nUndoSize;
198 }
199 return retval;
200}
201
202void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
203{
204 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
205 FlatFilePos pos(*it, 0);
206 fs::remove(BlockFileSeq().FileName(pos));
207 fs::remove(UndoFileSeq().FileName(pos));
208 LogPrint(BCLog::BLOCKSTORE, "Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
209 }
210}
211
213{
214 return FlatFileSeq(gArgs.GetBlocksDirPath(), "blk", gArgs.GetBoolArg("-fastprune", false) ? 0x4000 /* 16kb */ : BLOCKFILE_CHUNK_SIZE);
215}
216
218{
220}
221
222FILE* OpenBlockFile(const FlatFilePos& pos, bool fReadOnly)
223{
224 return BlockFileSeq().Open(pos, fReadOnly);
225}
226
228static FILE* OpenUndoFile(const FlatFilePos& pos, bool fReadOnly)
229{
230 return UndoFileSeq().Open(pos, fReadOnly);
231}
232
234{
235 return BlockFileSeq().FileName(pos);
236}
237
238bool FindBlockPos(FlatFilePos& pos, unsigned int nAddSize, unsigned int nHeight, CChain& active_chain, uint64_t nTime, bool fKnown = false)
239{
241
242 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
243 if (vinfoBlockFile.size() <= nFile) {
244 vinfoBlockFile.resize(nFile + 1);
245 }
246
247 bool finalize_undo = false;
248 if (!fKnown) {
249 while (vinfoBlockFile[nFile].nSize + nAddSize >= (gArgs.GetBoolArg("-fastprune", false) ? 0x10000 /* 64kb */ : MAX_BLOCKFILE_SIZE)) {
250 // when the undo file is keeping up with the block file, we want to flush it explicitly
251 // when it is lagging behind (more blocks arrive than are being connected), we let the
252 // undo block write case handle it
253 finalize_undo = (vinfoBlockFile[nFile].nHeightLast == (unsigned int)active_chain.Tip()->nHeight);
254 nFile++;
255 if (vinfoBlockFile.size() <= nFile) {
256 vinfoBlockFile.resize(nFile + 1);
257 }
258 }
259 pos.nFile = nFile;
260 pos.nPos = vinfoBlockFile[nFile].nSize;
261 }
262
263 if ((int)nFile != nLastBlockFile) {
264 if (!fKnown) {
266 }
267 FlushBlockFile(!fKnown, finalize_undo);
268 nLastBlockFile = nFile;
269 }
270
271 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
272 if (fKnown) {
273 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
274 } else {
275 vinfoBlockFile[nFile].nSize += nAddSize;
276 }
277
278 if (!fKnown) {
279 bool out_of_space;
280 size_t bytes_allocated = BlockFileSeq().Allocate(pos, nAddSize, out_of_space);
281 if (out_of_space) {
282 return AbortNode("Disk space is too low!", _("Disk space is too low!"));
283 }
284 if (bytes_allocated != 0 && fPruneMode) {
285 fCheckForPruning = true;
286 }
287 }
288
289 setDirtyFileInfo.insert(nFile);
290 return true;
291}
292
293static bool FindUndoPos(BlockValidationState& state, int nFile, FlatFilePos& pos, unsigned int nAddSize)
294{
295 pos.nFile = nFile;
296
298
299 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
300 vinfoBlockFile[nFile].nUndoSize += nAddSize;
301 setDirtyFileInfo.insert(nFile);
302
303 bool out_of_space;
304 size_t bytes_allocated = UndoFileSeq().Allocate(pos, nAddSize, out_of_space);
305 if (out_of_space) {
306 return AbortNode(state, "Disk space is too low!", _("Disk space is too low!"));
307 }
308 if (bytes_allocated != 0 && fPruneMode) {
309 fCheckForPruning = true;
310 }
311
312 return true;
313}
314
315static bool WriteBlockToDisk(const CBlock& block, FlatFilePos& pos, const CMessageHeader::MessageStartChars& messageStart)
316{
317 // Open history file to append
319 if (fileout.IsNull()) {
320 return error("WriteBlockToDisk: OpenBlockFile failed");
321 }
322
323 // Write index header
324 unsigned int nSize = GetSerializeSize(block, fileout.GetVersion());
325 fileout << messageStart << nSize;
326
327 // Write block
328 long fileOutPos = ftell(fileout.Get());
329 if (fileOutPos < 0) {
330 return error("WriteBlockToDisk: ftell failed");
331 }
332 pos.nPos = (unsigned int)fileOutPos;
333 fileout << block;
334
335 return true;
336}
337
338bool WriteUndoDataForBlock(const CBlockUndo& blockundo, BlockValidationState& state, CBlockIndex* pindex, const CChainParams& chainparams)
339{
340 // Write undo information to disk
341 if (pindex->GetUndoPos().IsNull()) {
342 FlatFilePos _pos;
343 if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, CLIENT_VERSION) + 40)) {
344 return error("ConnectBlock(): FindUndoPos failed");
345 }
346 if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart())) {
347 return AbortNode(state, "Failed to write undo data");
348 }
349 // rev files are written in block height order, whereas blk files are written as blocks come in (often out of order)
350 // we want to flush the rev (undo) file once we've written the last block, which is indicated by the last height
351 // in the block file info as below; note that this does not catch the case where the undo writes are keeping up
352 // with the block writes (usually when a synced up node is getting newly mined blocks) -- this case is caught in
353 // the FindBlockPos function
354 if (_pos.nFile < nLastBlockFile && static_cast<uint32_t>(pindex->nHeight) == vinfoBlockFile[_pos.nFile].nHeightLast) {
355 FlushUndoFile(_pos.nFile, true);
356 }
357
358 // update nUndoPos in block index
359 pindex->nUndoPos = _pos.nPos;
360 pindex->nStatus |= BLOCK_HAVE_UNDO;
361 setDirtyBlockIndex.insert(pindex);
362 }
363
364 return true;
365}
366
367bool ReadBlockFromDisk(CBlock& block, const FlatFilePos& pos, const Consensus::Params& consensusParams)
368{
369 block.SetNull();
370
371 // Open history file to read
372 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
373 if (filein.IsNull()) {
374 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
375 }
376
377 // Read block
378 try {
379 filein >> block;
380 } catch (const std::exception& e) {
381 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
382 }
383
384 // Check the header
385 if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams)) {
386 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
387 }
388
389 // Signet only: check block solution
390 if (consensusParams.signet_blocks && !CheckSignetBlockSolution(block, consensusParams)) {
391 return error("ReadBlockFromDisk: Errors in block solution at %s", pos.ToString());
392 }
393
394 return true;
395}
396
397bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
398{
399 const FlatFilePos block_pos{WITH_LOCK(cs_main, return pindex->GetBlockPos())};
400
401 if (!ReadBlockFromDisk(block, block_pos, consensusParams)) {
402 return false;
403 }
404 if (block.GetHash() != pindex->GetBlockHash()) {
405 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
406 pindex->ToString(), block_pos.ToString());
407 }
408 return true;
409}
410
411bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const FlatFilePos& pos, const CMessageHeader::MessageStartChars& message_start)
412{
413 FlatFilePos hpos = pos;
414 hpos.nPos -= 8; // Seek back 8 bytes for meta header
415 CAutoFile filein(OpenBlockFile(hpos, true), SER_DISK, CLIENT_VERSION);
416 if (filein.IsNull()) {
417 return error("%s: OpenBlockFile failed for %s", __func__, pos.ToString());
418 }
419
420 try {
422 unsigned int blk_size;
423
424 filein >> blk_start >> blk_size;
425
426 if (memcmp(blk_start, message_start, CMessageHeader::MESSAGE_START_SIZE)) {
427 return error("%s: Block magic mismatch for %s: %s versus expected %s", __func__, pos.ToString(),
428 HexStr(blk_start),
429 HexStr(message_start));
430 }
431
432 if (blk_size > MAX_SIZE) {
433 return error("%s: Block data is larger than maximum deserialization size for %s: %s versus %s", __func__, pos.ToString(),
434 blk_size, MAX_SIZE);
435 }
436
437 block.resize(blk_size); // Zeroing of memory is intentional here
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());
441 }
442
443 return true;
444}
445
446bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const CBlockIndex* pindex, const CMessageHeader::MessageStartChars& message_start)
447{
448 FlatFilePos block_pos;
449 {
450 LOCK(cs_main);
451 block_pos = pindex->GetBlockPos();
452 }
453
454 return ReadRawBlockFromDisk(block, block_pos, message_start);
455}
456
458FlatFilePos SaveBlockToDisk(const CBlock& block, int nHeight, CChain& active_chain, const CChainParams& chainparams, const FlatFilePos* dbp)
459{
460 unsigned int nBlockSize = ::GetSerializeSize(block, CLIENT_VERSION);
461 FlatFilePos blockPos;
462 if (dbp != nullptr) {
463 blockPos = *dbp;
464 }
465 if (!FindBlockPos(blockPos, nBlockSize + 8, nHeight, active_chain, block.GetBlockTime(), dbp != nullptr)) {
466 error("%s: FindBlockPos failed", __func__);
467 return FlatFilePos();
468 }
469 if (dbp == nullptr) {
470 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) {
471 AbortNode("Failed to write block");
472 return FlatFilePos();
473 }
474 }
475 return blockPos;
476}
477
480 {
481 assert(fImporting == false);
482 fImporting = true;
483 }
484
486 {
487 assert(fImporting == true);
488 fImporting = false;
489 }
490};
491
492void ThreadImport(ChainstateManager& chainman, std::vector<fs::path> vImportFiles, const ArgsManager& args)
493{
496
497 {
498 CImportingNow imp;
499
500 // -reindex
501 if (fReindex) {
502 int nFile = 0;
503 while (true) {
504 FlatFilePos pos(nFile, 0);
505 if (!fs::exists(GetBlockPosFilename(pos))) {
506 break; // No block files left to reindex
507 }
508 FILE* file = OpenBlockFile(pos, true);
509 if (!file) {
510 break; // This error is logged in OpenBlockFile
511 }
512 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
513 chainman.ActiveChainstate().LoadExternalBlockFile(file, &pos);
514 if (ShutdownRequested()) {
515 LogPrintf("Shutdown requested. Exit %s\n", __func__);
516 return;
517 }
518 nFile++;
519 }
520 WITH_LOCK(::cs_main, chainman.m_blockman.m_block_tree_db->WriteReindexing(false));
521 fReindex = false;
522 LogPrintf("Reindexing finished\n");
523 // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
525 }
526
527 // -loadblock=
528 for (const fs::path& path : vImportFiles) {
529 FILE* file = fsbridge::fopen(path, "rb");
530 if (file) {
531 LogPrintf("Importing blocks file %s...\n", fs::PathToString(path));
533 if (ShutdownRequested()) {
534 LogPrintf("Shutdown requested. Exit %s\n", __func__);
535 return;
536 }
537 } else {
538 LogPrintf("Warning: Could not open blocks file %s\n", fs::PathToString(path));
539 }
540 }
541
542 // scan for better chains in the block chain database, that are not yet connected in the active best chain
543
544 // We can't hold cs_main during ActivateBestChain even though we're accessing
545 // the chainman unique_ptrs since ABC requires us not to be holding cs_main, so retrieve
546 // the relevant pointers before the ABC call.
547 for (CChainState* chainstate : WITH_LOCK(::cs_main, return chainman.GetAll())) {
549 if (!chainstate->ActivateBestChain(state, nullptr)) {
550 LogPrintf("Failed to connect best block (%s)\n", state.ToString());
552 return;
553 }
554 }
555
556 if (args.GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
557 LogPrintf("Stopping after block import\n");
559 return;
560 }
561 } // End scope of CImportingNow
562 chainman.ActiveChainstate().LoadMempool(args);
563}
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:118
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()
int nLastBlockFile
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)
Definition: blockstorage.h:34
static const unsigned int BLOCKFILE_CHUNK_SIZE
The pre-allocation chunk size for blk?????.dat files (since 0.8)
Definition: blockstorage.h:32
static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT
Definition: blockstorage.h:29
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: blockstorage.h:36
@ BLOCK_HAVE_UNDO
undo data available in rev*.dat
Definition: chain.h:122
@ BLOCK_HAVE_DATA
full block available in blk*.dat
Definition: chain.h:121
const fs::path & GetBlocksDirPath() const
Get blocks directory path.
Definition: system.cpp:401
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:602
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:565
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
Definition: streams.h:609
FILE * Get() const
Get wrapped FILE* without transfer of ownership.
Definition: streams.h:605
int GetVersion() const
Definition: streams.h:615
void read(char *pch, size_t nSize)
Definition: streams.h:617
uint64_t nTimeFirst
earliest time of block in file
Definition: chain.h:48
uint64_t nTimeLast
latest time of block in file
Definition: chain.h:49
std::string ToString() const
unsigned int nHeightFirst
lowest height of block in file
Definition: chain.h:46
unsigned int nHeightLast
highest height of block in file
Definition: chain.h:47
unsigned int nBlocks
number of blocks stored in file
Definition: chain.h:43
unsigned int nSize
number of used bytes of block file
Definition: chain.h:44
uint32_t nBits
Definition: block.h:28
int64_t GetBlockTime() const
Definition: block.h:55
uint256 GetHash() const
Definition: block.cpp:11
Definition: block.h:63
void SetNull()
Definition: block.h:88
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:146
std::string ToString() const
Definition: chain.h:294
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:152
int nFile
Which # file this block is stored in (blk?????.dat)
Definition: chain.h:161
FlatFilePos GetBlockPos() const
Definition: chain.h:223
unsigned int nUndoPos
Byte offset within rev?????.dat where this block's undo data is stored.
Definition: chain.h:167
uint256 GetBlockHash() const
Definition: chain.h:254
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:177
FlatFilePos GetUndoPos() const
Definition: chain.h:232
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:158
uint32_t nStatus
Verification status of this block.
Definition: chain.h:195
Undo information for a CBlock.
Definition: undo.h:64
An in-memory indexed chain of blocks.
Definition: chain.h:410
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:421
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:70
const CMessageHeader::MessageStartChars & MessageStart() const
Definition: chainparams.h:83
CChainState stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:544
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.
Definition: hash.h:158
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:101
uint256 GetHash()
Compute the double-SHA256 hash of all data written to this object.
Definition: hash.h:122
unsigned char MessageStartChars[MESSAGE_START_SIZE]
Definition: protocol.h:40
static constexpr size_t MESSAGE_START_SIZE
Definition: protocol.h:33
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:847
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.
Definition: validation.h:925
CChainState & ActiveChainstate() const
The most-work chain.
FlatFileSeq represents a sequence of numbered files storing raw data.
Definition: flatfile.h:47
fs::path FileName(const FlatFilePos &pos) const
Get the name of the file at the given position.
Definition: flatfile.cpp:28
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.
Definition: flatfile.cpp:55
FILE * Open(const FlatFilePos &pos, bool read_only=false)
Open a handle to the file at the given position.
Definition: flatfile.cpp:33
std::string ToString() const
Definition: validation.h:125
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
Definition: fs.h:34
256-bit opaque blob.
Definition: uint256.h:124
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:33
#define LogPrint(category,...)
Definition: logging.h:191
#define LogPrintf(...)
Definition: logging.h:187
unsigned int nHeight
@ BLOCKSTORE
Definition: logging.h:64
static bool exists(const path &p)
Definition: fs.h:77
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:120
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:25
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:74
@ SER_DISK
Definition: serialize.h:139
@ SER_GETHASH
Definition: serialize.h:140
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...
Definition: serialize.h:31
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1080
bool AbortNode(const std::string &strMessage, bilingual_str user_message)
Abort with a message.
Definition: shutdown.cpp:21
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
Definition: shutdown.cpp:87
void StartShutdown()
Request shutdown of the application.
Definition: shutdown.cpp:56
bool CheckSignetBlockSolution(const CBlock &block, const Consensus::Params &consensusParams)
Extract signature and check whether a block has a valid solution.
Definition: signet.cpp:124
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.
Definition: string.h:87
Parameters that influence chain consensus.
Definition: params.h:70
bool signet_blocks
If true, witness commitments contain a payload equal to a Bitcoin Script solution to the signet chall...
Definition: params.h:115
int nFile
Definition: flatfile.h:16
std::string ToString() const
Definition: flatfile.cpp:23
unsigned int nPos
Definition: flatfile.h:17
bool IsNull() const
Definition: flatfile.h:37
#define LOCK(cs)
Definition: sync.h:226
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:270
void SetSyscallSandboxPolicy(SyscallSandboxPolicy syscall_policy)
Force the current thread (and threads created from the current thread) into a restricted-service oper...
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
std::string FormatISO8601Date(int64_t nTime)
Definition: time.cpp:145
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:63
void ScheduleBatchPriority()
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
Definition: system.cpp:1376
ArgsManager gArgs
Definition: system.cpp:85
assert(!tx.IsCoinBase())
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12