Branch data Line data Source code
1 : : // Copyright (c) 2011-2022 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 : : #ifndef BITCOIN_NODE_BLOCKSTORAGE_H
6 : : #define BITCOIN_NODE_BLOCKSTORAGE_H
7 : :
8 : : #include <attributes.h>
9 : : #include <chain.h>
10 : : #include <dbwrapper.h>
11 : : #include <kernel/blockmanager_opts.h>
12 : : #include <kernel/chain.h>
13 : : #include <kernel/chainparams.h>
14 : : #include <kernel/cs_main.h>
15 : : #include <kernel/messagestartchars.h>
16 : : #include <sync.h>
17 : : #include <util/fs.h>
18 : : #include <util/hasher.h>
19 : :
20 : : #include <atomic>
21 : : #include <cstdint>
22 : : #include <functional>
23 : : #include <limits>
24 : : #include <map>
25 : : #include <memory>
26 : : #include <set>
27 : : #include <string>
28 : : #include <unordered_map>
29 : : #include <utility>
30 : : #include <vector>
31 : :
32 : : class BlockValidationState;
33 : : class CAutoFile;
34 : : class CBlock;
35 : : class CBlockUndo;
36 : : class CChainParams;
37 : : class Chainstate;
38 : : class ChainstateManager;
39 : : struct CCheckpointData;
40 : : struct FlatFilePos;
41 : : namespace Consensus {
42 : : struct Params;
43 : : }
44 : : namespace util {
45 : : class SignalInterrupt;
46 : : } // namespace util
47 : :
48 : : namespace kernel {
49 : : /** Access to the block database (blocks/index/) */
50 : 0 : class BlockTreeDB : public CDBWrapper
51 : : {
52 : : public:
53 : 0 : using CDBWrapper::CDBWrapper;
54 : : bool WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*>>& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo);
55 : : bool ReadBlockFileInfo(int nFile, CBlockFileInfo& info);
56 : : bool ReadLastBlockFile(int& nFile);
57 : : bool WriteReindexing(bool fReindexing);
58 : : void ReadReindexing(bool& fReindexing);
59 : : bool WriteFlag(const std::string& name, bool fValue);
60 : : bool ReadFlag(const std::string& name, bool& fValue);
61 : : bool LoadBlockIndexGuts(const Consensus::Params& consensusParams, std::function<CBlockIndex*(const uint256&)> insertBlockIndex, const util::SignalInterrupt& interrupt)
62 : : EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
63 : : };
64 : : } // namespace kernel
65 : :
66 : : namespace node {
67 : : using kernel::BlockTreeDB;
68 : :
69 : : /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
70 : : static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
71 : : /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
72 : : static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
73 : : /** The maximum size of a blk?????.dat file (since 0.8) */
74 : : static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
75 : :
76 : : /** Size of header written by WriteBlockToDisk before a serialized CBlock */
77 : : static constexpr size_t BLOCK_SERIALIZATION_HEADER_SIZE = std::tuple_size_v<MessageStartChars> + sizeof(unsigned int);
78 : :
79 : : extern std::atomic_bool fReindex;
80 : :
81 : : // Because validation code takes pointers to the map's CBlockIndex objects, if
82 : : // we ever switch to another associative container, we need to either use a
83 : : // container that has stable addressing (true of all std associative
84 : : // containers), or make the key a `std::unique_ptr<CBlockIndex>`
85 : : using BlockMap = std::unordered_map<uint256, CBlockIndex, BlockHasher>;
86 : :
87 : : struct CBlockIndexWorkComparator {
88 : : bool operator()(const CBlockIndex* pa, const CBlockIndex* pb) const;
89 : : };
90 : :
91 : : struct CBlockIndexHeightOnlyComparator {
92 : : /* Only compares the height of two block indices, doesn't try to tie-break */
93 : : bool operator()(const CBlockIndex* pa, const CBlockIndex* pb) const;
94 : : };
95 : :
96 : 0 : struct PruneLockInfo {
97 : 0 : int height_first{std::numeric_limits<int>::max()}; //! Height of earliest block that should be kept and not pruned
98 : : };
99 : :
100 : : enum BlockfileType {
101 : : // Values used as array indexes - do not change carelessly.
102 : : NORMAL = 0,
103 : : ASSUMED = 1,
104 : : NUM_TYPES = 2,
105 : : };
106 : :
107 : : std::ostream& operator<<(std::ostream& os, const BlockfileType& type);
108 : :
109 : : struct BlockfileCursor {
110 : : // The latest blockfile number.
111 : : int file_num{0};
112 : :
113 : : // Track the height of the highest block in file_num whose undo
114 : : // data has been written. Block data is written to block files in download
115 : : // order, but is written to undo files in validation order, which is
116 : : // usually in order by height. To avoid wasting disk space, undo files will
117 : : // be trimmed whenever the corresponding block file is finalized and
118 : : // the height of the highest block written to the block file equals the
119 : : // height of the highest block written to the undo file. This is a
120 : : // heuristic and can sometimes preemptively trim undo files that will write
121 : : // more data later, and sometimes fail to trim undo files that can't have
122 : : // more data written later.
123 : : int undo_height{0};
124 : : };
125 : :
126 : : std::ostream& operator<<(std::ostream& os, const BlockfileCursor& cursor);
127 : :
128 : :
129 : : /**
130 : : * Maintains a tree of blocks (stored in `m_block_index`) which is consulted
131 : : * to determine where the most-work tip is.
132 : : *
133 : : * This data is used mostly in `Chainstate` - information about, e.g.,
134 : : * candidate tips is not maintained here.
135 : : */
136 : 0 : class BlockManager
137 : : {
138 : : friend Chainstate;
139 : : friend ChainstateManager;
140 : :
141 : : private:
142 : 401 : const CChainParams& GetParams() const { return m_opts.chainparams; }
143 : 3 : const Consensus::Params& GetConsensus() const { return m_opts.chainparams.GetConsensus(); }
144 : : /**
145 : : * Load the blocktree off disk and into memory. Populate certain metadata
146 : : * per index entry (nStatus, nChainWork, nTimeMax, etc.) as well as peripheral
147 : : * collections like m_dirty_blockindex.
148 : : */
149 : : bool LoadBlockIndex(const std::optional<uint256>& snapshot_blockhash)
150 : : EXCLUSIVE_LOCKS_REQUIRED(cs_main);
151 : :
152 : : /** Return false if block file or undo file flushing fails. */
153 : : [[nodiscard]] bool FlushBlockFile(int blockfile_num, bool fFinalize, bool finalize_undo);
154 : :
155 : : /** Return false if undo file flushing fails. */
156 : : [[nodiscard]] bool FlushUndoFile(int block_file, bool finalize = false);
157 : :
158 : : [[nodiscard]] bool FindBlockPos(FlatFilePos& pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown);
159 : : [[nodiscard]] bool FlushChainstateBlockFile(int tip_height);
160 : : bool FindUndoPos(BlockValidationState& state, int nFile, FlatFilePos& pos, unsigned int nAddSize);
161 : :
162 : : FlatFileSeq BlockFileSeq() const;
163 : : FlatFileSeq UndoFileSeq() const;
164 : :
165 : : CAutoFile OpenUndoFile(const FlatFilePos& pos, bool fReadOnly = false) const;
166 : :
167 : : bool WriteBlockToDisk(const CBlock& block, FlatFilePos& pos) const;
168 : : bool UndoWriteToDisk(const CBlockUndo& blockundo, FlatFilePos& pos, const uint256& hashBlock) const;
169 : :
170 : : /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
171 : : void FindFilesToPruneManual(
172 : : std::set<int>& setFilesToPrune,
173 : : int nManualPruneHeight,
174 : : const Chainstate& chain,
175 : : ChainstateManager& chainman);
176 : :
177 : : /**
178 : : * Prune block and undo files (blk???.dat and rev???.dat) so that the disk space used is less than a user-defined target.
179 : : * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
180 : : * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
181 : : * (which in this case means the blockchain must be re-downloaded.)
182 : : *
183 : : * Pruning functions are called from FlushStateToDisk when the m_check_for_pruning flag has been set.
184 : : * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
185 : : * Pruning cannot take place until the longest chain is at least a certain length (CChainParams::nPruneAfterHeight).
186 : : * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
187 : : * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
188 : : * A db flag records the fact that at least some block files have been pruned.
189 : : *
190 : : * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
191 : : * @param last_prune The last height we're able to prune, according to the prune locks
192 : : */
193 : : void FindFilesToPrune(
194 : : std::set<int>& setFilesToPrune,
195 : : int last_prune,
196 : : const Chainstate& chain,
197 : : ChainstateManager& chainman);
198 : :
199 : : RecursiveMutex cs_LastBlockFile;
200 : : std::vector<CBlockFileInfo> m_blockfile_info;
201 : :
202 : : //! Since assumedvalid chainstates may be syncing a range of the chain that is very
203 : : //! far away from the normal/background validation process, we should segment blockfiles
204 : : //! for assumed chainstates. Otherwise, we might have wildly different height ranges
205 : : //! mixed into the same block files, which would impair our ability to prune
206 : : //! effectively.
207 : : //!
208 : : //! This data structure maintains separate blockfile number cursors for each
209 : : //! BlockfileType. The ASSUMED state is initialized, when necessary, in FindBlockPos().
210 : : //!
211 : : //! The first element is the NORMAL cursor, second is ASSUMED.
212 : : std::array<std::optional<BlockfileCursor>, BlockfileType::NUM_TYPES>
213 : 1 : m_blockfile_cursors GUARDED_BY(cs_LastBlockFile) = {
214 : 1 : BlockfileCursor{},
215 : : std::nullopt,
216 : : };
217 : 1 : int MaxBlockfileNum() const EXCLUSIVE_LOCKS_REQUIRED(cs_LastBlockFile)
218 : : {
219 : : static const BlockfileCursor empty_cursor;
220 : 1 : const auto& normal = m_blockfile_cursors[BlockfileType::NORMAL].value_or(empty_cursor);
221 : 1 : const auto& assumed = m_blockfile_cursors[BlockfileType::ASSUMED].value_or(empty_cursor);
222 : 1 : return std::max(normal.file_num, assumed.file_num);
223 : : }
224 : :
225 : : /** Global flag to indicate we should check to see if there are
226 : : * block/undo files that should be deleted. Set on startup
227 : : * or if we allocate more file space when we're in prune mode
228 : : */
229 : 1 : bool m_check_for_pruning = false;
230 : :
231 : : const bool m_prune_mode;
232 : :
233 : : /** Dirty block index entries. */
234 : : std::set<CBlockIndex*> m_dirty_blockindex;
235 : :
236 : : /** Dirty block file entries. */
237 : : std::set<int> m_dirty_fileinfo;
238 : :
239 : : /**
240 : : * Map from external index name to oldest block that must not be pruned.
241 : : *
242 : : * @note Internally, only blocks at height (height_first - PRUNE_LOCK_BUFFER - 1) and
243 : : * below will be pruned, but callers should avoid assuming any particular buffer size.
244 : : */
245 : : std::unordered_map<std::string, PruneLockInfo> m_prune_locks GUARDED_BY(::cs_main);
246 : :
247 : : BlockfileType BlockfileTypeForHeight(int height);
248 : :
249 : : const kernel::BlockManagerOpts m_opts;
250 : :
251 : : public:
252 : : using Options = kernel::BlockManagerOpts;
253 : :
254 : 2 : explicit BlockManager(const util::SignalInterrupt& interrupt, Options opts)
255 : 1 : : m_prune_mode{opts.prune_target > 0},
256 [ + - ]: 1 : m_opts{std::move(opts)},
257 : 2 : m_interrupt{interrupt} {};
258 : :
259 : : const util::SignalInterrupt& m_interrupt;
260 : 1 : std::atomic<bool> m_importing{false};
261 : :
262 : : BlockMap m_block_index GUARDED_BY(cs_main);
263 : :
264 : : /**
265 : : * The height of the base block of an assumeutxo snapshot, if one is in use.
266 : : *
267 : : * This controls how blockfiles are segmented by chainstate type to avoid
268 : : * comingling different height regions of the chain when an assumedvalid chainstate
269 : : * is in use. If heights are drastically different in the same blockfile, pruning
270 : : * suffers.
271 : : *
272 : : * This is set during ActivateSnapshot() or upon LoadBlockIndex() if a snapshot
273 : : * had been previously loaded. After the snapshot is validated, this is unset to
274 : : * restore normal LoadBlockIndex behavior.
275 : : */
276 : : std::optional<int> m_snapshot_height;
277 : :
278 : : std::vector<CBlockIndex*> GetAllBlockIndices() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
279 : :
280 : : /**
281 : : * All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
282 : : * Pruned nodes may have entries where B is missing data.
283 : : */
284 : : std::multimap<CBlockIndex*, CBlockIndex*> m_blocks_unlinked;
285 : :
286 : : std::unique_ptr<BlockTreeDB> m_block_tree_db GUARDED_BY(::cs_main);
287 : :
288 : : bool WriteBlockIndexDB() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
289 : : bool LoadBlockIndexDB(const std::optional<uint256>& snapshot_blockhash)
290 : : EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
291 : :
292 : : /**
293 : : * Remove any pruned block & undo files that are still on disk.
294 : : * This could happen on some systems if the file was still being read while unlinked,
295 : : * or if we crash before unlinking.
296 : : */
297 : : void ScanAndUnlinkAlreadyPrunedFiles() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
298 : :
299 : : CBlockIndex* AddToBlockIndex(const CBlockHeader& block, CBlockIndex*& best_header) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
300 : : /** Create a new block index entry for a given block hash */
301 : : CBlockIndex* InsertBlockIndex(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
302 : :
303 : : //! Mark one block file as pruned (modify associated database entries)
304 : : void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
305 : :
306 : : CBlockIndex* LookupBlockIndex(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
307 : : const CBlockIndex* LookupBlockIndex(const uint256& hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
308 : :
309 : : /** Get block file info entry for one block file */
310 : : CBlockFileInfo* GetBlockFileInfo(size_t n);
311 : :
312 : : bool WriteUndoDataForBlock(const CBlockUndo& blockundo, BlockValidationState& state, CBlockIndex& block)
313 : : EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
314 : :
315 : : /** Store block on disk. If dbp is not nullptr, then it provides the known position of the block within a block file on disk. */
316 : : FlatFilePos SaveBlockToDisk(const CBlock& block, int nHeight, const FlatFilePos* dbp);
317 : :
318 : : /** Whether running in -prune mode. */
319 : 40510 : [[nodiscard]] bool IsPruneMode() const { return m_prune_mode; }
320 : :
321 : : /** Attempt to stay below this number of bytes of block files. */
322 : 2 : [[nodiscard]] uint64_t GetPruneTarget() const { return m_opts.prune_target; }
323 : : static constexpr auto PRUNE_TARGET_MANUAL{std::numeric_limits<uint64_t>::max()};
324 : :
325 [ - + ]: 1406 : [[nodiscard]] bool LoadingBlocks() const { return m_importing || fReindex; }
326 : :
327 : : /** Calculate the amount of disk space the block & undo files currently use */
328 : : uint64_t CalculateCurrentUsage();
329 : :
330 : : //! Returns last CBlockIndex* that is a checkpoint
331 : : const CBlockIndex* GetLastCheckpoint(const CCheckpointData& data) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
332 : :
333 : : //! Check if all blocks in the [upper_block, lower_block] range have data available.
334 : : //! The caller is responsible for ensuring that lower_block is an ancestor of upper_block
335 : : //! (part of the same chain).
336 : : bool CheckBlockDataAvailability(const CBlockIndex& upper_block LIFETIMEBOUND, const CBlockIndex& lower_block LIFETIMEBOUND) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
337 : :
338 : : //! Find the first stored ancestor of start_block immediately after the last
339 : : //! pruned ancestor. Return value will never be null. Caller is responsible
340 : : //! for ensuring that start_block has data is not pruned.
341 : : const CBlockIndex* GetFirstStoredBlock(const CBlockIndex& start_block LIFETIMEBOUND, const CBlockIndex* lower_block=nullptr) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
342 : :
343 : : /** True if any block files have ever been pruned. */
344 : 1 : bool m_have_pruned = false;
345 : :
346 : : //! Check whether the block associated with this index entry is pruned or not.
347 : : bool IsBlockPruned(const CBlockIndex* pblockindex) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
348 : :
349 : : //! Create or update a prune lock identified by its name
350 : : void UpdatePruneLock(const std::string& name, const PruneLockInfo& lock_info) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
351 : :
352 : : /** Open a block file (blk?????.dat) */
353 : : CAutoFile OpenBlockFile(const FlatFilePos& pos, bool fReadOnly = false) const;
354 : :
355 : : /** Translation to a filesystem path */
356 : : fs::path GetBlockPosFilename(const FlatFilePos& pos) const;
357 : :
358 : : /**
359 : : * Actually unlink the specified files
360 : : */
361 : : void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune) const;
362 : :
363 : : /** Functions for disk access for blocks */
364 : : bool ReadBlockFromDisk(CBlock& block, const FlatFilePos& pos) const;
365 : : bool ReadBlockFromDisk(CBlock& block, const CBlockIndex& index) const;
366 : : bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const FlatFilePos& pos) const;
367 : :
368 : : bool UndoReadFromDisk(CBlockUndo& blockundo, const CBlockIndex& index) const;
369 : :
370 : : void CleanupBlockRevFiles() const;
371 : : };
372 : :
373 : : void ImportBlocks(ChainstateManager& chainman, std::vector<fs::path> vImportFiles);
374 : : } // namespace node
375 : :
376 : : #endif // BITCOIN_NODE_BLOCKSTORAGE_H
|