Bitcoin ABC 0.31.6
P2P Digital Currency
blockstorage.h
Go to the documentation of this file.
1// Copyright (c) 2011-2021 The Bitcoin 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#ifndef BITCOIN_NODE_BLOCKSTORAGE_H
6#define BITCOIN_NODE_BLOCKSTORAGE_H
7
8#include <cstdint>
9#include <functional>
10#include <unordered_map>
11#include <vector>
12
13#include <attributes.h>
14#include <chain.h>
15#include <chainparams.h>
17#include <kernel/chain.h>
18#include <kernel/cs_main.h>
19#include <protocol.h>
20#include <sync.h>
21#include <txdb.h>
22#include <util/fs.h>
23
25class CBlock;
26class CBlockFileInfo;
27class CBlockHeader;
28class CBlockUndo;
29class CChainParams;
30class CTxUndo;
31class Chainstate;
33struct CCheckpointData;
34class Config;
35struct FlatFilePos;
36namespace Consensus {
37struct Params;
38}
39namespace avalanche {
40class Processor;
41}
42
43namespace node {
44
46static constexpr unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
48static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
50static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
51
53static constexpr size_t BLOCK_SERIALIZATION_HEADER_SIZE =
54 CMessageHeader::MESSAGE_START_SIZE + sizeof(unsigned int);
55
56extern std::atomic_bool fReindex;
57
58// Because validation code takes pointers to the map's CBlockIndex objects, if
59// we ever switch to another associative container, we need to either use a
60// container that has stable addressing (true of all std associative
61// containers), or make the key a `std::unique_ptr<CBlockIndex>`
62using BlockMap = std::unordered_map<BlockHash, CBlockIndex, BlockHasher>;
63
66 int height_first{std::numeric_limits<int>::max()};
67};
68
70 // Values used as array indexes - do not change carelessly.
71 NORMAL = 0,
74};
75
76std::ostream &operator<<(std::ostream &os, const BlockfileType &type);
77
79 // The latest blockfile number.
80 int file_num{0};
81
82 // Track the height of the highest block in file_num whose undo
83 // data has been written. Block data is written to block files in download
84 // order, but is written to undo files in validation order, which is
85 // usually in order by height. To avoid wasting disk space, undo files will
86 // be trimmed whenever the corresponding block file is finalized and
87 // the height of the highest block written to the block file equals the
88 // height of the highest block written to the undo file. This is a
89 // heuristic and can sometimes preemptively trim undo files that will write
90 // more data later, and sometimes fail to trim undo files that can't have
91 // more data written later.
93};
94
95std::ostream &operator<<(std::ostream &os, const BlockfileCursor &cursor);
96
107
108private:
109 const CChainParams &GetParams() const { return m_opts.chainparams; }
112 }
118 bool LoadBlockIndex(const std::optional<BlockHash> &snapshot_blockhash)
120
122 [[nodiscard]] bool FlushBlockFile(int blockfile_num, bool fFinalize,
123 bool finalize_undo);
124
126 [[nodiscard]] bool FlushUndoFile(int block_file, bool finalize = false);
127
128 [[nodiscard]] bool FindBlockPos(FlatFilePos &pos, unsigned int nAddSize,
129 unsigned int nHeight, uint64_t nTime,
130 bool fKnown);
131 [[nodiscard]] bool FlushChainstateBlockFile(int tip_height);
132 bool FindUndoPos(BlockValidationState &state, int nFile, FlatFilePos &pos,
133 unsigned int nAddSize);
134
136 FlatFileSeq UndoFileSeq() const;
137
138 FILE *OpenUndoFile(const FlatFilePos &pos, bool fReadOnly = false) const;
139
140 bool
141 WriteBlockToDisk(const CBlock &block, FlatFilePos &pos,
142 const CMessageHeader::MessageMagic &messageStart) const;
143 bool
144 UndoWriteToDisk(const CBlockUndo &blockundo, FlatFilePos &pos,
145 const BlockHash &hashBlock,
146 const CMessageHeader::MessageMagic &messageStart) const;
147
152 void FindFilesToPruneManual(std::set<int> &setFilesToPrune,
153 int nManualPruneHeight, const Chainstate &chain,
154 ChainstateManager &chainman);
155
179 void FindFilesToPrune(std::set<int> &setFilesToPrune, int last_prune,
180 const Chainstate &chain, ChainstateManager &chainman);
181
183 std::vector<CBlockFileInfo> m_blockfile_info;
184
196 std::array<std::optional<BlockfileCursor>, BlockfileType::NUM_TYPES>
197 m_blockfile_cursors GUARDED_BY(cs_LastBlockFile) = {{
199 std::nullopt,
200 }};
202 static const BlockfileCursor empty_cursor;
203 const auto &normal =
204 m_blockfile_cursors[BlockfileType::NORMAL].value_or(empty_cursor);
205 const auto &assumed =
206 m_blockfile_cursors[BlockfileType::ASSUMED].value_or(empty_cursor);
207 return std::max(normal.file_num, assumed.file_num);
208 }
209
216
217 const bool m_prune_mode;
218
220 std::set<CBlockIndex *> m_dirty_blockindex;
221
223 std::set<int> m_dirty_fileinfo;
224
232 std::unordered_map<std::string, PruneLockInfo>
233 m_prune_locks GUARDED_BY(::cs_main);
234
236
238
239public:
241
242 explicit BlockManager(Options opts)
243 : m_prune_mode{opts.prune_target > 0}, m_opts{std::move(opts)} {};
244
245 std::atomic<bool> m_importing{false};
246
248
261 std::optional<int> m_snapshot_height;
262
263 std::vector<CBlockIndex *> GetAllBlockIndices()
265
272
273 std::unique_ptr<CBlockTreeDB> m_block_tree_db GUARDED_BY(::cs_main);
274
275 bool WriteBlockIndexDB() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
276 bool LoadBlockIndexDB(const std::optional<BlockHash> &snapshot_blockhash)
278
284 void ScanAndUnlinkAlreadyPrunedFiles() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
285
287 CBlockIndex *&best_header)
292
294 void PruneOneBlockFile(const int fileNumber)
296
299 const CBlockIndex *LookupBlockIndex(const BlockHash &hash) const
301
304
305 bool WriteUndoDataForBlock(const CBlockUndo &blockundo,
306 BlockValidationState &state, CBlockIndex &block)
308
314 const FlatFilePos *dbp);
315
317 [[nodiscard]] bool IsPruneMode() const { return m_prune_mode; }
318
320 [[nodiscard]] uint64_t GetPruneTarget() const {
321 return m_opts.prune_target;
322 }
323 static constexpr auto PRUNE_TARGET_MANUAL{
324 std::numeric_limits<uint64_t>::max()};
325
326 [[nodiscard]] bool LoadingBlocks() const { return m_importing || fReindex; }
327
328 [[nodiscard]] bool StopAfterBlockImport() const {
330 }
331
335 uint64_t CalculateCurrentUsage();
336
340
344 bool
345 CheckBlockDataAvailability(const CBlockIndex &upper_block LIFETIMEBOUND,
346 const CBlockIndex &lower_block LIFETIMEBOUND)
348
372 const CBlockIndex *
373 GetFirstBlock(const CBlockIndex &upper_block LIFETIMEBOUND,
374 std::function<bool(BlockStatus)> status_test,
375 const CBlockIndex *lower_block = nullptr) const
377
379 bool m_have_pruned = false;
380
383 bool IsBlockPruned(const CBlockIndex *pblockindex)
385
387 void UpdatePruneLock(const std::string &name,
388 const PruneLockInfo &lock_info)
390
392 FILE *OpenBlockFile(const FlatFilePos &pos, bool fReadOnly = false) const;
393
395 fs::path GetBlockPosFilename(const FlatFilePos &pos) const;
396
400 void UnlinkPrunedFiles(const std::set<int> &setFilesToPrune) const;
401
403 bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos) const;
404 bool ReadBlockFromDisk(CBlock &block, const CBlockIndex &index) const;
405 bool UndoReadFromDisk(CBlockUndo &blockundo,
406 const CBlockIndex &index) const;
407
409 bool ReadTxFromDisk(CMutableTransaction &tx, const FlatFilePos &pos) const;
410 bool ReadTxUndoFromDisk(CTxUndo &tx, const FlatFilePos &pos) const;
411
412 void CleanupBlockRevFiles() const;
413};
414
415void ImportBlocks(ChainstateManager &chainman,
416 avalanche::Processor *const avalanche,
417 std::vector<fs::path> vImportFiles);
418} // namespace node
419
420#endif // BITCOIN_NODE_BLOCKSTORAGE_H
#define LIFETIMEBOUND
Definition: attributes.h:16
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:21
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:23
Definition: block.h:60
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
Access to the block database (blocks/index/)
Definition: txdb.h:117
Undo information for a CBlock.
Definition: undo.h:73
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:86
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:98
static constexpr size_t MESSAGE_START_SIZE
Definition: protocol.h:36
std::array< uint8_t, MESSAGE_START_SIZE > MessageMagic
Definition: protocol.h:46
A mutable version of CTransaction.
Definition: transaction.h:274
Restore the UTXO in a Coin at a given COutPoint.
Definition: undo.h:62
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:705
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1158
Definition: config.h:19
FlatFileSeq represents a sequence of numbered files storing raw data.
Definition: flatfile.h:49
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: blockstorage.h:104
const kernel::BlockManagerOpts m_opts
Definition: blockstorage.h:237
std::set< int > m_dirty_fileinfo
Dirty block file entries.
Definition: blockstorage.h:223
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos) const
Functions for disk access for blocks.
bool WriteBlockToDisk(const CBlock &block, FlatFilePos &pos, const CMessageHeader::MessageMagic &messageStart) const
FlatFileSeq UndoFileSeq() const
RecursiveMutex cs_LastBlockFile
Definition: blockstorage.h:182
const CChainParams & GetParams() const
Definition: blockstorage.h:109
bool CheckBlockDataAvailability(const CBlockIndex &upper_block LIFETIMEBOUND, const CBlockIndex &lower_block LIFETIMEBOUND) EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetFirstBlock(const CBlockIndex &upper_block LIFETIMEBOUND, std::function< bool(BlockStatus)> status_test, 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.
Definition: blockstorage.h:379
bool WriteUndoDataForBlock(const CBlockUndo &blockundo, BlockValidationState &state, CBlockIndex &block) EXCLUSIVE_LOCKS_REQUIRED(FlatFilePos SaveBlockToDisk(const CBlock &block, int nHeight, const FlatFilePos *dbp)
Store block on disk.
Definition: blockstorage.h:313
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 undo???.dat) so that the disk space used is less than a us...
FlatFileSeq BlockFileSeq() const
FILE * OpenUndoFile(const FlatFilePos &pos, bool fReadOnly=false) const
Open an undo file (rev?????.dat)
static constexpr auto PRUNE_TARGET_MANUAL
Definition: blockstorage.h:323
bool StopAfterBlockImport() const
Definition: blockstorage.h:328
bool LoadBlockIndex(const std::optional< BlockHash > &snapshot_blockhash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the blocktree off disk and into memory.
void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark one block file as pruned (modify associated database entries)
BlockfileType BlockfileTypeForHeight(int height)
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool ReadTxFromDisk(CMutableTransaction &tx, const FlatFilePos &pos) const
Functions for disk access for txs.
const Consensus::Params & GetConsensus() const
Definition: blockstorage.h:110
std::unordered_map< std::string, PruneLockInfo > m_prune_locks GUARDED_BY(::cs_main)
Map from external index name to oldest block that must not be pruned.
CBlockIndex * InsertBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Create a new block index entry for a given block hash.
bool ReadTxUndoFromDisk(CTxUndo &tx, const FlatFilePos &pos) const
bool LoadingBlocks() const
Definition: blockstorage.h:326
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex &index) const
fs::path GetBlockPosFilename(const FlatFilePos &pos) const
Translation to a filesystem path.
bool FindBlockPos(FlatFilePos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown)
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.
Definition: blockstorage.h:320
int MaxBlockfileNum() const EXCLUSIVE_LOCKS_REQUIRED(cs_LastBlockFile)
Definition: blockstorage.h:201
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune) const
Actually unlink the specified files.
bool WriteBlockIndexDB() EXCLUSIVE_LOCKS_REQUIRED(bool LoadBlockIndexDB(const std::optional< BlockHash > &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.
Definition: blockstorage.h:286
const bool m_prune_mode
Definition: blockstorage.h:217
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.
bool UndoWriteToDisk(const CBlockUndo &blockundo, FlatFilePos &pos, const BlockHash &hashBlock, const CMessageHeader::MessageMagic &messageStart) const
const CBlockIndex * GetLastCheckpoint(const CCheckpointData &data) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Returns last CBlockIndex* that is a checkpoint.
std::set< CBlockIndex * > m_dirty_blockindex
Dirty block index entries.
Definition: blockstorage.h:220
bool m_check_for_pruning
Global flag to indicate we should check to see if there are block/undo files that should be deleted.
Definition: blockstorage.h:215
bool FindUndoPos(BlockValidationState &state, int nFile, FlatFilePos &pos, unsigned int nAddSize)
bool IsPruneMode() const
Whether running in -prune mode.
Definition: blockstorage.h:317
void CleanupBlockRevFiles() const
void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight, const Chainstate &chain, ChainstateManager &chainman)
Calculate the block/rev files to delete based on height specified by user with RPC command pruneblock...
std::array< std::optional< BlockfileCursor >, BlockfileType::NUM_TYPES > m_blockfile_cursors GUARDED_BY(cs_LastBlockFile)
Since assumedvalid chainstates may be syncing a range of the chain that is very far away from the nor...
std::atomic< bool > m_importing
Definition: blockstorage.h:245
std::vector< CBlockFileInfo > m_blockfile_info
Definition: blockstorage.h:183
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
bool IsBlockPruned(const CBlockIndex *pblockindex) EXCLUSIVE_LOCKS_REQUIRED(void UpdatePruneLock(const std::string &name, const PruneLockInfo &lock_info) EXCLUSIVE_LOCKS_REQUIRED(FILE OpenBlockFile)(const FlatFilePos &pos, bool fReadOnly=false) const
Check whether the block associated with this index entry is pruned or not.
Definition: blockstorage.h:392
BlockManager(Options opts)
Definition: blockstorage.h:242
std::optional< int > m_snapshot_height
The height of the base block of an assumeutxo snapshot, if one is in use.
Definition: blockstorage.h:261
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.
Definition: blockstorage.h:263
BlockMap m_block_index GUARDED_BY(cs_main)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
unsigned int nHeight
Filesystem operations and types.
Definition: fs.h:20
Definition: init.h:31
static const unsigned int UNDOFILE_CHUNK_SIZE
The pre-allocation chunk size for rev?????.dat files (since 0.8)
Definition: blockstorage.h:48
BlockfileType
Definition: blockstorage.h:69
@ NUM_TYPES
Definition: blockstorage.h:73
@ NORMAL
Definition: blockstorage.h:71
@ ASSUMED
Definition: blockstorage.h:72
std::unordered_map< BlockHash, CBlockIndex, BlockHasher > BlockMap
Definition: blockstorage.h:62
std::ostream & operator<<(std::ostream &os, const BlockfileType &type)
static constexpr unsigned int BLOCKFILE_CHUNK_SIZE
The pre-allocation chunk size for blk?????.dat files (since 0.8)
Definition: blockstorage.h:46
static constexpr size_t BLOCK_SERIALIZATION_HEADER_SIZE
Size of header written by WriteBlockToDisk before a serialized CBlock.
Definition: blockstorage.h:53
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: blockstorage.h:50
std::atomic_bool fReindex
void ImportBlocks(ChainstateManager &chainman, avalanche::Processor *const avalanche, std::vector< fs::path > vImportFiles)
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:259
const char * name
Definition: rest.cpp:47
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
Parameters that influence chain consensus.
Definition: params.h:34
An options struct for BlockManager, more ergonomically referred to as BlockManager::Options due to th...
const CChainParams & chainparams
int height_first
Height of earliest block that should be kept and not pruned.
Definition: blockstorage.h:66
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56