Bitcoin ABC 0.33.11
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
68// Because validation code takes pointers to the map's CBlockIndex objects, if
69// we ever switch to another associative container, we need to either use a
70// container that has stable addressing (true of all std associative
71// containers), or make the key a `std::unique_ptr<CBlockIndex>`
72using BlockMap = std::unordered_map<BlockHash, CBlockIndex, BlockHasher>;
73
76 int height_first{std::numeric_limits<int>::max()};
77};
78
80 // Values used as array indexes - do not change carelessly.
81 NORMAL = 0,
84};
85
86std::ostream &operator<<(std::ostream &os, const BlockfileType &type);
87
89 // The latest blockfile number.
90 int file_num{0};
91
92 // Track the height of the highest block in file_num whose undo
93 // data has been written. Block data is written to block files in download
94 // order, but is written to undo files in validation order, which is
95 // usually in order by height. To avoid wasting disk space, undo files will
96 // be trimmed whenever the corresponding block file is finalized and
97 // the height of the highest block written to the block file equals the
98 // height of the highest block written to the undo file. This is a
99 // heuristic and can sometimes preemptively trim undo files that will write
100 // more data later, and sometimes fail to trim undo files that can't have
101 // more data written later.
103};
104
105std::ostream &operator<<(std::ostream &os, const BlockfileCursor &cursor);
106
117
118private:
119 const CChainParams &GetParams() const { return m_opts.chainparams; }
122 }
128 bool LoadBlockIndex(const std::optional<BlockHash> &snapshot_blockhash)
130
132 [[nodiscard]] bool FlushBlockFile(int blockfile_num, bool fFinalize,
133 bool finalize_undo);
134
136 [[nodiscard]] bool FlushUndoFile(int block_file, bool finalize = false);
137
149 [[nodiscard]] FlatFilePos FindNextBlockPos(unsigned int nAddSize,
150 unsigned int nHeight,
151 uint64_t nTime);
152 [[nodiscard]] bool FlushChainstateBlockFile(int tip_height);
153 bool FindUndoPos(BlockValidationState &state, int nFile, FlatFilePos &pos,
154 unsigned int nAddSize);
155
157 FlatFileSeq UndoFileSeq() const;
158
159 AutoFile OpenUndoFile(const FlatFilePos &pos, bool fReadOnly = false) const;
160
165 void FindFilesToPruneManual(std::set<int> &setFilesToPrune,
166 int nManualPruneHeight, const Chainstate &chain,
167 ChainstateManager &chainman);
168
192 void FindFilesToPrune(std::set<int> &setFilesToPrune, int last_prune,
193 const Chainstate &chain, ChainstateManager &chainman);
194
196 std::vector<CBlockFileInfo> m_blockfile_info;
197
209 std::array<std::optional<BlockfileCursor>, BlockfileType::NUM_TYPES>
210 m_blockfile_cursors GUARDED_BY(cs_LastBlockFile) = {{
212 std::nullopt,
213 }};
215 static const BlockfileCursor empty_cursor;
216 const auto &normal =
217 m_blockfile_cursors[BlockfileType::NORMAL].value_or(empty_cursor);
218 const auto &assumed =
219 m_blockfile_cursors[BlockfileType::ASSUMED].value_or(empty_cursor);
220 return std::max(normal.file_num, assumed.file_num);
221 }
222
229
230 const bool m_prune_mode;
231
233 std::set<CBlockIndex *> m_dirty_blockindex;
234
236 std::set<int> m_dirty_fileinfo;
237
245 std::unordered_map<std::string, PruneLockInfo>
246 m_prune_locks GUARDED_BY(::cs_main);
247
249
251
252public:
254
255 explicit BlockManager(const util::SignalInterrupt &interrupt, Options opts)
256 : m_prune_mode{opts.prune_target > 0}, m_opts{std::move(opts)},
257 m_interrupt{interrupt}, m_reindexing{m_opts.reindex} {};
258
260 std::atomic<bool> m_importing{false};
261
267 std::atomic_bool m_reindexing;
268
270
283 std::optional<int> m_snapshot_height;
284
285 std::vector<CBlockIndex *> GetAllBlockIndices()
287
294
295 std::unique_ptr<CBlockTreeDB> m_block_tree_db GUARDED_BY(::cs_main);
296
297 void WriteBlockIndexDB() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
298 bool LoadBlockIndexDB(const std::optional<BlockHash> &snapshot_blockhash)
300
306 void ScanAndUnlinkAlreadyPrunedFiles() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
307
309 CBlockIndex *&best_header)
314
316 void PruneOneBlockFile(const int fileNumber)
318
321 const CBlockIndex *LookupBlockIndex(const BlockHash &hash) const
323
326
327 bool WriteBlockUndo(const CBlockUndo &blockundo,
328 BlockValidationState &state, CBlockIndex &block)
330
342
351 void UpdateBlockInfo(const CBlock &block, unsigned int nHeight,
352 const FlatFilePos &pos);
353
355 [[nodiscard]] bool IsPruneMode() const { return m_prune_mode; }
356
358 [[nodiscard]] uint64_t GetPruneTarget() const {
359 return m_opts.prune_target;
360 }
361 static constexpr auto PRUNE_TARGET_MANUAL{
362 std::numeric_limits<uint64_t>::max()};
363
364 [[nodiscard]] bool LoadingBlocks() const {
365 return m_importing || m_reindexing;
366 }
367
371 uint64_t CalculateCurrentUsage();
372
376
380 bool
381 CheckBlockDataAvailability(const CBlockIndex &upper_block LIFETIMEBOUND,
382 const CBlockIndex &lower_block LIFETIMEBOUND)
384
408 const CBlockIndex *
409 GetFirstBlock(const CBlockIndex &upper_block LIFETIMEBOUND,
410 std::function<bool(BlockStatus)> status_test,
411 const CBlockIndex *lower_block = nullptr) const
413
415 bool m_have_pruned = false;
416
419 bool IsBlockPruned(const CBlockIndex &block) const
421
423 void UpdatePruneLock(const std::string &name,
424 const PruneLockInfo &lock_info)
426
429 bool fReadOnly = false) const;
430
432 fs::path GetBlockPosFilename(const FlatFilePos &pos) const;
433
437 void UnlinkPrunedFiles(const std::set<int> &setFilesToPrune) const;
438
440 bool ReadBlock(CBlock &block, const FlatFilePos &pos) const;
441 bool ReadBlock(CBlock &block, const CBlockIndex &index) const;
442 bool ReadRawBlock(std::vector<uint8_t> &block,
443 const FlatFilePos &pos) const;
444 bool ReadBlockUndo(CBlockUndo &blockundo, const CBlockIndex &index) const;
445
447 bool ReadTxFromDisk(CMutableTransaction &tx, const FlatFilePos &pos) const;
448 bool ReadTxUndoFromDisk(CTxUndo &tx, const FlatFilePos &pos) const;
449
450 void CleanupBlockRevFiles() const;
451};
452
453void ImportBlocks(ChainstateManager &chainman,
454 avalanche::Processor *const avalanche,
455 std::vector<fs::path> vImportFiles);
456} // namespace node
457
458#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:725
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1174
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:114
const kernel::BlockManagerOpts m_opts
Definition: blockstorage.h:250
std::set< int > m_dirty_fileinfo
Dirty block file entries.
Definition: blockstorage.h:236
FlatFileSeq UndoFileSeq() const
RecursiveMutex cs_LastBlockFile
Definition: blockstorage.h:195
const CChainParams & GetParams() const
Definition: blockstorage.h:119
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:415
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: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:120
BlockManager(const util::SignalInterrupt &interrupt, Options opts)
Definition: blockstorage.h:255
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:364
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:358
int MaxBlockfileNum() const EXCLUSIVE_LOCKS_REQUIRED(cs_LastBlockFile)
Definition: blockstorage.h:214
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune) const
Actually unlink the specified files.
void 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:308
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:230
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:259
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:233
std::atomic_bool m_reindexing
Tracks if a reindex is currently in progress.
Definition: blockstorage.h:267
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:228
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:428
bool IsPruneMode() const
Whether running in -prune mode.
Definition: blockstorage.h:355
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:260
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:341
std::vector< CBlockFileInfo > m_blockfile_info
Definition: blockstorage.h:196
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:283
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:285
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: messages.h:12
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:79
@ NUM_TYPES
Definition: blockstorage.h:83
@ NORMAL
Definition: blockstorage.h:81
@ ASSUMED
Definition: blockstorage.h:82
std::unordered_map< BlockHash, CBlockIndex, BlockHasher > BlockMap
Definition: blockstorage.h:72
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
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:76
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56