Bitcoin ABC 0.32.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 <array>
9#include <cstdint>
10#include <functional>
11#include <optional>
12#include <unordered_map>
13#include <vector>
14
15#include <attributes.h>
16#include <chain.h>
17#include <chainparams.h>
19#include <kernel/chain.h>
20#include <kernel/cs_main.h>
21#include <protocol.h>
22#include <sync.h>
23#include <txdb.h>
24#include <util/fs.h>
25
27class CBlock;
28class CBlockFileInfo;
29class CBlockHeader;
30class CBlockUndo;
31class CChainParams;
32class CTxUndo;
33class Chainstate;
35struct CCheckpointData;
36class Config;
37struct FlatFilePos;
38namespace Consensus {
39struct Params;
40}
41namespace avalanche {
42class Processor;
43}
44namespace util {
45class SignalInterrupt;
46} // namespace util
47
48namespace node {
49
51static constexpr unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
53static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
55static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
56
58static constexpr size_t BLOCK_SERIALIZATION_HEADER_SIZE{
59 CMessageHeader::MESSAGE_START_SIZE + sizeof(unsigned int)};
60
65static constexpr size_t UNDO_DATA_DISK_OVERHEAD{
67
68extern std::atomic_bool fReindex;
69
70// Because validation code takes pointers to the map's CBlockIndex objects, if
71// we ever switch to another associative container, we need to either use a
72// container that has stable addressing (true of all std associative
73// containers), or make the key a `std::unique_ptr<CBlockIndex>`
74using BlockMap = std::unordered_map<BlockHash, CBlockIndex, BlockHasher>;
75
78 int height_first{std::numeric_limits<int>::max()};
79};
80
82 // Values used as array indexes - do not change carelessly.
83 NORMAL = 0,
86};
87
88std::ostream &operator<<(std::ostream &os, const BlockfileType &type);
89
91 // The latest blockfile number.
92 int file_num{0};
93
94 // Track the height of the highest block in file_num whose undo
95 // data has been written. Block data is written to block files in download
96 // order, but is written to undo files in validation order, which is
97 // usually in order by height. To avoid wasting disk space, undo files will
98 // be trimmed whenever the corresponding block file is finalized and
99 // the height of the highest block written to the block file equals the
100 // height of the highest block written to the undo file. This is a
101 // heuristic and can sometimes preemptively trim undo files that will write
102 // more data later, and sometimes fail to trim undo files that can't have
103 // more data written later.
105};
106
107std::ostream &operator<<(std::ostream &os, const BlockfileCursor &cursor);
108
119
120private:
121 const CChainParams &GetParams() const { return m_opts.chainparams; }
124 }
130 bool LoadBlockIndex(const std::optional<BlockHash> &snapshot_blockhash)
132
134 [[nodiscard]] bool FlushBlockFile(int blockfile_num, bool fFinalize,
135 bool finalize_undo);
136
138 [[nodiscard]] bool FlushUndoFile(int block_file, bool finalize = false);
139
151 [[nodiscard]] FlatFilePos FindNextBlockPos(unsigned int nAddSize,
152 unsigned int nHeight,
153 uint64_t nTime);
154 [[nodiscard]] bool FlushChainstateBlockFile(int tip_height);
155 bool FindUndoPos(BlockValidationState &state, int nFile, FlatFilePos &pos,
156 unsigned int nAddSize);
157
159 FlatFileSeq UndoFileSeq() const;
160
161 AutoFile OpenUndoFile(const FlatFilePos &pos, bool fReadOnly = false) const;
162
167 void FindFilesToPruneManual(std::set<int> &setFilesToPrune,
168 int nManualPruneHeight, const Chainstate &chain,
169 ChainstateManager &chainman);
170
194 void FindFilesToPrune(std::set<int> &setFilesToPrune, int last_prune,
195 const Chainstate &chain, ChainstateManager &chainman);
196
198 std::vector<CBlockFileInfo> m_blockfile_info;
199
211 std::array<std::optional<BlockfileCursor>, BlockfileType::NUM_TYPES>
212 m_blockfile_cursors GUARDED_BY(cs_LastBlockFile) = {{
214 std::nullopt,
215 }};
217 static const BlockfileCursor empty_cursor;
218 const auto &normal =
219 m_blockfile_cursors[BlockfileType::NORMAL].value_or(empty_cursor);
220 const auto &assumed =
221 m_blockfile_cursors[BlockfileType::ASSUMED].value_or(empty_cursor);
222 return std::max(normal.file_num, assumed.file_num);
223 }
224
231
232 const bool m_prune_mode;
233
235 std::set<CBlockIndex *> m_dirty_blockindex;
236
238 std::set<int> m_dirty_fileinfo;
239
247 std::unordered_map<std::string, PruneLockInfo>
248 m_prune_locks GUARDED_BY(::cs_main);
249
251
253
254public:
256
257 explicit BlockManager(const util::SignalInterrupt &interrupt, Options opts)
258 : m_prune_mode{opts.prune_target > 0}, m_opts{std::move(opts)},
259 m_interrupt{interrupt} {};
260
262 std::atomic<bool> m_importing{false};
263
265
278 std::optional<int> m_snapshot_height;
279
280 std::vector<CBlockIndex *> GetAllBlockIndices()
282
289
290 std::unique_ptr<CBlockTreeDB> m_block_tree_db GUARDED_BY(::cs_main);
291
292 bool WriteBlockIndexDB() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
293 bool LoadBlockIndexDB(const std::optional<BlockHash> &snapshot_blockhash)
295
301 void ScanAndUnlinkAlreadyPrunedFiles() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
302
304 CBlockIndex *&best_header)
309
311 void PruneOneBlockFile(const int fileNumber)
313
316 const CBlockIndex *LookupBlockIndex(const BlockHash &hash) const
318
321
322 bool WriteBlockUndo(const CBlockUndo &blockundo,
323 BlockValidationState &state, CBlockIndex &block)
325
337
346 void UpdateBlockInfo(const CBlock &block, unsigned int nHeight,
347 const FlatFilePos &pos);
348
350 [[nodiscard]] bool IsPruneMode() const { return m_prune_mode; }
351
353 [[nodiscard]] uint64_t GetPruneTarget() const {
354 return m_opts.prune_target;
355 }
356 static constexpr auto PRUNE_TARGET_MANUAL{
357 std::numeric_limits<uint64_t>::max()};
358
359 [[nodiscard]] bool LoadingBlocks() const { return m_importing || fReindex; }
360
361 [[nodiscard]] bool StopAfterBlockImport() const {
363 }
364
368 uint64_t CalculateCurrentUsage();
369
373
377 bool
378 CheckBlockDataAvailability(const CBlockIndex &upper_block LIFETIMEBOUND,
379 const CBlockIndex &lower_block LIFETIMEBOUND)
381
405 const CBlockIndex *
406 GetFirstBlock(const CBlockIndex &upper_block LIFETIMEBOUND,
407 std::function<bool(BlockStatus)> status_test,
408 const CBlockIndex *lower_block = nullptr) const
410
412 bool m_have_pruned = false;
413
416 bool IsBlockPruned(const CBlockIndex &block) const
418
420 void UpdatePruneLock(const std::string &name,
421 const PruneLockInfo &lock_info)
423
426 bool fReadOnly = false) const;
427
429 fs::path GetBlockPosFilename(const FlatFilePos &pos) const;
430
434 void UnlinkPrunedFiles(const std::set<int> &setFilesToPrune) const;
435
437 bool ReadBlock(CBlock &block, const FlatFilePos &pos) const;
438 bool ReadBlock(CBlock &block, const CBlockIndex &index) const;
439 bool ReadRawBlock(std::vector<uint8_t> &block,
440 const FlatFilePos &pos) const;
441 bool ReadBlockUndo(CBlockUndo &blockundo, const CBlockIndex &index) const;
442
444 bool ReadTxFromDisk(CMutableTransaction &tx, const FlatFilePos &pos) const;
445 bool ReadTxUndoFromDisk(CTxUndo &tx, const FlatFilePos &pos) const;
446
447 void CleanupBlockRevFiles() const;
448};
449
450void ImportBlocks(ChainstateManager &chainman,
451 avalanche::Processor *const avalanche,
452 std::vector<fs::path> vImportFiles);
453} // namespace node
454
455#endif // BITCOIN_NODE_BLOCKSTORAGE_H
#define LIFETIMEBOUND
Definition: attributes.h:16
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:21
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:430
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:100
Undo information for a CBlock.
Definition: undo.h:72
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
A mutable version of CTransaction.
Definition: transaction.h:274
Restore the UTXO in a Coin at a given COutPoint.
Definition: undo.h:61
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:733
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1185
Definition: config.h:19
FlatFileSeq represents a sequence of numbered files storing raw data.
Definition: flatfile.h:49
static constexpr unsigned int size()
Definition: uint256.h:93
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: blockstorage.h:116
const kernel::BlockManagerOpts m_opts
Definition: blockstorage.h:252
std::set< int > m_dirty_fileinfo
Dirty block file entries.
Definition: blockstorage.h:238
FlatFileSeq UndoFileSeq() const
RecursiveMutex cs_LastBlockFile
Definition: blockstorage.h:197
const CChainParams & GetParams() const
Definition: blockstorage.h:121
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:412
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...
void UpdateBlockInfo(const CBlock &block, unsigned int nHeight, const FlatFilePos &pos)
Update blockfile info while processing a block during reindex.
FlatFileSeq BlockFileSeq() const
static constexpr auto PRUNE_TARGET_MANUAL
Definition: blockstorage.h:356
bool StopAfterBlockImport() const
Definition: blockstorage.h:361
bool LoadBlockIndex(const std::optional< BlockHash > &snapshot_blockhash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the blocktree off disk and into memory.
bool ReadBlockUndo(CBlockUndo &blockundo, const CBlockIndex &index) const
bool ReadRawBlock(std::vector< uint8_t > &block, const FlatFilePos &pos) const
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:122
BlockManager(const util::SignalInterrupt &interrupt, Options opts)
Definition: blockstorage.h:257
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:359
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.
Definition: blockstorage.h:353
int MaxBlockfileNum() const EXCLUSIVE_LOCKS_REQUIRED(cs_LastBlockFile)
Definition: blockstorage.h:216
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:303
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...
const bool m_prune_mode
Definition: blockstorage.h:232
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
Definition: blockstorage.h:261
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:235
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:230
bool FindUndoPos(BlockValidationState &state, int nFile, FlatFilePos &pos, unsigned int nAddSize)
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.
Definition: blockstorage.h:425
bool IsPruneMode() const
Whether running in -prune mode.
Definition: blockstorage.h:350
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:262
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.
Definition: blockstorage.h:336
std::vector< CBlockFileInfo > m_blockfile_info
Definition: blockstorage.h:198
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
bool ReadBlock(CBlock &block, const FlatFilePos &pos) const
Functions for disk access for blocks.
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.
Definition: blockstorage.h:278
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:280
BlockMap m_block_index GUARDED_BY(cs_main)
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.
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:53
BlockfileType
Definition: blockstorage.h:81
@ NUM_TYPES
Definition: blockstorage.h:85
@ NORMAL
Definition: blockstorage.h:83
@ ASSUMED
Definition: blockstorage.h:84
std::unordered_map< BlockHash, CBlockIndex, BlockHasher > BlockMap
Definition: blockstorage.h:74
std::ostream & operator<<(std::ostream &os, const BlockfileType &type)
static constexpr size_t UNDO_DATA_DISK_OVERHEAD
Total overhead when writing undo data: header (8 bytes) plus checksum (32 bytes)
Definition: blockstorage.h:65
static constexpr unsigned int BLOCKFILE_CHUNK_SIZE
The pre-allocation chunk size for blk?????.dat files (since 0.8)
Definition: blockstorage.h:51
static constexpr size_t BLOCK_SERIALIZATION_HEADER_SIZE
Size of header written by WriteBlock before a serialized CBlock.
Definition: blockstorage.h:58
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: blockstorage.h:55
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:46
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:78
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56