Bitcoin ABC 0.31.1
P2P Digital Currency
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
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 <unordered_map>
10#include <vector>
11
12#include <attributes.h>
13#include <chain.h>
14#include <chainparams.h>
16#include <kernel/chain.h>
17#include <kernel/cs_main.h>
18#include <protocol.h>
19#include <sync.h>
20#include <txdb.h>
21#include <util/fs.h>
22
24class CBlock;
25class CBlockFileInfo;
26class CBlockHeader;
27class CBlockUndo;
28class CChainParams;
29class CTxUndo;
30class Chainstate;
32struct CCheckpointData;
33class Config;
34struct FlatFilePos;
35namespace Consensus {
36struct Params;
37}
38namespace avalanche {
39class Processor;
40}
41
42namespace node {
43
45static constexpr unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
47static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
49static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
50
52static constexpr size_t BLOCK_SERIALIZATION_HEADER_SIZE =
53 CMessageHeader::MESSAGE_START_SIZE + sizeof(unsigned int);
54
55extern std::atomic_bool fReindex;
56
57// Because validation code takes pointers to the map's CBlockIndex objects, if
58// we ever switch to another associative container, we need to either use a
59// container that has stable addressing (true of all std associative
60// containers), or make the key a `std::unique_ptr<CBlockIndex>`
61using BlockMap = std::unordered_map<BlockHash, CBlockIndex, BlockHasher>;
62
65 int height_first{std::numeric_limits<int>::max()};
66};
67
69 // Values used as array indexes - do not change carelessly.
70 NORMAL = 0,
73};
74
75std::ostream &operator<<(std::ostream &os, const BlockfileType &type);
76
78 // The latest blockfile number.
79 int file_num{0};
80
81 // Track the height of the highest block in file_num whose undo
82 // data has been written. Block data is written to block files in download
83 // order, but is written to undo files in validation order, which is
84 // usually in order by height. To avoid wasting disk space, undo files will
85 // be trimmed whenever the corresponding block file is finalized and
86 // the height of the highest block written to the block file equals the
87 // height of the highest block written to the undo file. This is a
88 // heuristic and can sometimes preemptively trim undo files that will write
89 // more data later, and sometimes fail to trim undo files that can't have
90 // more data written later.
92};
93
94std::ostream &operator<<(std::ostream &os, const BlockfileCursor &cursor);
95
106
107private:
108 const CChainParams &GetParams() const { return m_opts.chainparams; }
111 }
117 bool LoadBlockIndex(const std::optional<BlockHash> &snapshot_blockhash)
119
121 [[nodiscard]] bool FlushBlockFile(int blockfile_num, bool fFinalize,
122 bool finalize_undo);
123
125 [[nodiscard]] bool FlushUndoFile(int block_file, bool finalize = false);
126
127 [[nodiscard]] bool FindBlockPos(FlatFilePos &pos, unsigned int nAddSize,
128 unsigned int nHeight, uint64_t nTime,
129 bool fKnown);
130 [[nodiscard]] bool FlushChainstateBlockFile(int tip_height);
131 bool FindUndoPos(BlockValidationState &state, int nFile, FlatFilePos &pos,
132 unsigned int nAddSize);
133
135 FlatFileSeq UndoFileSeq() const;
136
137 FILE *OpenUndoFile(const FlatFilePos &pos, bool fReadOnly = false) const;
138
139 bool
140 WriteBlockToDisk(const CBlock &block, FlatFilePos &pos,
141 const CMessageHeader::MessageMagic &messageStart) const;
142 bool
143 UndoWriteToDisk(const CBlockUndo &blockundo, FlatFilePos &pos,
144 const BlockHash &hashBlock,
145 const CMessageHeader::MessageMagic &messageStart) const;
146
151 void FindFilesToPruneManual(std::set<int> &setFilesToPrune,
152 int nManualPruneHeight, const Chainstate &chain,
153 ChainstateManager &chainman);
154
178 void FindFilesToPrune(std::set<int> &setFilesToPrune, int last_prune,
179 const Chainstate &chain, ChainstateManager &chainman);
180
182 std::vector<CBlockFileInfo> m_blockfile_info;
183
195 std::array<std::optional<BlockfileCursor>, BlockfileType::NUM_TYPES>
196 m_blockfile_cursors GUARDED_BY(cs_LastBlockFile) = {{
198 std::nullopt,
199 }};
201 static const BlockfileCursor empty_cursor;
202 const auto &normal =
203 m_blockfile_cursors[BlockfileType::NORMAL].value_or(empty_cursor);
204 const auto &assumed =
205 m_blockfile_cursors[BlockfileType::ASSUMED].value_or(empty_cursor);
206 return std::max(normal.file_num, assumed.file_num);
207 }
208
215
216 const bool m_prune_mode;
217
219 std::set<CBlockIndex *> m_dirty_blockindex;
220
222 std::set<int> m_dirty_fileinfo;
223
231 std::unordered_map<std::string, PruneLockInfo>
232 m_prune_locks GUARDED_BY(::cs_main);
233
235
237
238public:
240
241 explicit BlockManager(Options opts)
242 : m_prune_mode{opts.prune_target > 0}, m_opts{std::move(opts)} {};
243
244 std::atomic<bool> m_importing{false};
245
247
260 std::optional<int> m_snapshot_height;
261
262 std::vector<CBlockIndex *> GetAllBlockIndices()
264
271
272 std::unique_ptr<CBlockTreeDB> m_block_tree_db GUARDED_BY(::cs_main);
273
274 bool WriteBlockIndexDB() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
275 bool LoadBlockIndexDB(const std::optional<BlockHash> &snapshot_blockhash)
277
283 void ScanAndUnlinkAlreadyPrunedFiles() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
284
286 CBlockIndex *&best_header)
291
293 void PruneOneBlockFile(const int fileNumber)
295
298 const CBlockIndex *LookupBlockIndex(const BlockHash &hash) const
300
303
304 bool WriteUndoDataForBlock(const CBlockUndo &blockundo,
305 BlockValidationState &state, CBlockIndex &block)
307
313 const FlatFilePos *dbp);
314
316 [[nodiscard]] bool IsPruneMode() const { return m_prune_mode; }
317
319 [[nodiscard]] uint64_t GetPruneTarget() const {
320 return m_opts.prune_target;
321 }
322 static constexpr auto PRUNE_TARGET_MANUAL{
323 std::numeric_limits<uint64_t>::max()};
324
325 [[nodiscard]] bool LoadingBlocks() const { return m_importing || fReindex; }
326
327 [[nodiscard]] bool StopAfterBlockImport() const {
329 }
330
334 uint64_t CalculateCurrentUsage();
335
339
343 bool
344 CheckBlockDataAvailability(const CBlockIndex &upper_block LIFETIMEBOUND,
345 const CBlockIndex &lower_block LIFETIMEBOUND)
347
351 const CBlockIndex *
352 GetFirstStoredBlock(const CBlockIndex &start_block LIFETIMEBOUND,
353 const CBlockIndex *lower_block = nullptr)
355
357 bool m_have_pruned = false;
358
361 bool IsBlockPruned(const CBlockIndex *pblockindex)
363
365 void UpdatePruneLock(const std::string &name,
366 const PruneLockInfo &lock_info)
368
370 FILE *OpenBlockFile(const FlatFilePos &pos, bool fReadOnly = false) const;
371
373 fs::path GetBlockPosFilename(const FlatFilePos &pos) const;
374
378 void UnlinkPrunedFiles(const std::set<int> &setFilesToPrune) const;
379
381 bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos) const;
382 bool ReadBlockFromDisk(CBlock &block, const CBlockIndex &index) const;
383 bool UndoReadFromDisk(CBlockUndo &blockundo,
384 const CBlockIndex &index) const;
385
387 bool ReadTxFromDisk(CMutableTransaction &tx, const FlatFilePos &pos) const;
388 bool ReadTxUndoFromDisk(CTxUndo &tx, const FlatFilePos &pos) const;
389
390 void CleanupBlockRevFiles() const;
391};
392
393void ImportBlocks(ChainstateManager &chainman,
394 avalanche::Processor *const avalanche,
395 std::vector<fs::path> vImportFiles);
396} // namespace node
397
398#endif // BITCOIN_NODE_BLOCKSTORAGE_H
#define LIFETIMEBOUND
Definition: attributes.h:16
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:19
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:85
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:97
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:700
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1147
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:103
const kernel::BlockManagerOpts m_opts
Definition: blockstorage.h:236
std::set< int > m_dirty_fileinfo
Dirty block file entries.
Definition: blockstorage.h:222
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:181
bool CheckBlockDataAvailability(const CBlockIndex &upper_block LIFETIMEBOUND, const CBlockIndex &lower_block LIFETIMEBOUND) EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetFirstStoredBlock(const CBlockIndex &start_block LIFETIMEBOUND, const CBlockIndex *lower_block=nullptr) EXCLUSIVE_LOCKS_REQUIRED(boo m_have_pruned)
Check if all blocks in the [upper_block, lower_block] range have data available.
Definition: blockstorage.h:357
const CChainParams & GetParams() const
Definition: blockstorage.h:108
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:312
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:322
bool StopAfterBlockImport() const
Definition: blockstorage.h:327
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:109
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:325
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:319
int MaxBlockfileNum() const EXCLUSIVE_LOCKS_REQUIRED(cs_LastBlockFile)
Definition: blockstorage.h:200
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:285
const bool m_prune_mode
Definition: blockstorage.h:216
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:219
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:214
bool FindUndoPos(BlockValidationState &state, int nFile, FlatFilePos &pos, unsigned int nAddSize)
bool IsPruneMode() const
Whether running in -prune mode.
Definition: blockstorage.h:316
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:244
std::vector< CBlockFileInfo > m_blockfile_info
Definition: blockstorage.h:182
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:370
BlockManager(Options opts)
Definition: blockstorage.h:241
std::optional< int > m_snapshot_height
The height of the base block of an assumeutxo snapshot, if one is in use.
Definition: blockstorage.h:260
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:262
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:47
BlockfileType
Definition: blockstorage.h:68
@ NUM_TYPES
Definition: blockstorage.h:72
@ NORMAL
Definition: blockstorage.h:70
@ ASSUMED
Definition: blockstorage.h:71
std::unordered_map< BlockHash, CBlockIndex, BlockHasher > BlockMap
Definition: blockstorage.h:61
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:45
static constexpr size_t BLOCK_SERIALIZATION_HEADER_SIZE
Size of header written by WriteBlockToDisk before a serialized CBlock.
Definition: blockstorage.h:52
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: blockstorage.h:49
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:65
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56