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 : : #include <node/blockstorage.h>
6 : :
7 : : #include <arith_uint256.h>
8 : : #include <chain.h>
9 : : #include <consensus/params.h>
10 : : #include <consensus/validation.h>
11 : : #include <dbwrapper.h>
12 : : #include <flatfile.h>
13 : : #include <hash.h>
14 : : #include <kernel/blockmanager_opts.h>
15 : : #include <kernel/chainparams.h>
16 : : #include <kernel/messagestartchars.h>
17 : : #include <kernel/notifications_interface.h>
18 : : #include <logging.h>
19 : : #include <pow.h>
20 : : #include <primitives/block.h>
21 : : #include <primitives/transaction.h>
22 : : #include <random.h>
23 : : #include <serialize.h>
24 : : #include <signet.h>
25 : : #include <span.h>
26 : : #include <streams.h>
27 : : #include <sync.h>
28 : : #include <tinyformat.h>
29 : : #include <uint256.h>
30 : : #include <undo.h>
31 : : #include <util/batchpriority.h>
32 : : #include <util/check.h>
33 : : #include <util/fs.h>
34 : : #include <util/signalinterrupt.h>
35 : : #include <util/strencodings.h>
36 : : #include <util/translation.h>
37 : : #include <validation.h>
38 : :
39 : : #include <cstddef>
40 : : #include <map>
41 : : #include <optional>
42 : : #include <unordered_map>
43 : :
44 : : namespace kernel {
45 : : static constexpr uint8_t DB_BLOCK_FILES{'f'};
46 : : static constexpr uint8_t DB_BLOCK_INDEX{'b'};
47 : : static constexpr uint8_t DB_FLAG{'F'};
48 : : static constexpr uint8_t DB_REINDEX_FLAG{'R'};
49 : : static constexpr uint8_t DB_LAST_BLOCK{'l'};
50 : : // Keys used in previous version that might still be found in the DB:
51 : : // BlockTreeDB::DB_TXINDEX_BLOCK{'T'};
52 : : // BlockTreeDB::DB_TXINDEX{'t'}
53 : : // BlockTreeDB::ReadFlag("txindex")
54 : :
55 : 2357 : bool BlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo& info)
56 : : {
57 : 2357 : return Read(std::make_pair(DB_BLOCK_FILES, nFile), info);
58 : : }
59 : :
60 : 35 : bool BlockTreeDB::WriteReindexing(bool fReindexing)
61 : : {
62 [ + + ]: 35 : if (fReindexing) {
63 : 18 : return Write(DB_REINDEX_FLAG, uint8_t{'1'});
64 : : } else {
65 : 17 : return Erase(DB_REINDEX_FLAG);
66 : : }
67 : : }
68 : :
69 : 1111 : void BlockTreeDB::ReadReindexing(bool& fReindexing)
70 : : {
71 : 1111 : fReindexing = Exists(DB_REINDEX_FLAG);
72 : 1111 : }
73 : :
74 : 1112 : bool BlockTreeDB::ReadLastBlockFile(int& nFile)
75 : : {
76 : 1112 : return Read(DB_LAST_BLOCK, nFile);
77 : : }
78 : :
79 : 3214 : bool BlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*>>& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo)
80 : : {
81 : 3214 : CDBBatch batch(*this);
82 [ + - + + ]: 4950 : for (const auto& [file, info] : fileInfo) {
83 [ + - ]: 1736 : batch.Write(std::make_pair(DB_BLOCK_FILES, file), *info);
84 : : }
85 [ + - ]: 3214 : batch.Write(DB_LAST_BLOCK, nLastFile);
86 [ + + ]: 157950 : for (const CBlockIndex* bi : blockinfo) {
87 [ + - ]: 154736 : batch.Write(std::make_pair(DB_BLOCK_INDEX, bi->GetBlockHash()), CDiskBlockIndex{bi});
88 : : }
89 [ + - ]: 6428 : return WriteBatch(batch, true);
90 : 3214 : }
91 : :
92 : 15 : bool BlockTreeDB::WriteFlag(const std::string& name, bool fValue)
93 : : {
94 [ - + + - ]: 15 : return Write(std::make_pair(DB_FLAG, name), fValue ? uint8_t{'1'} : uint8_t{'0'});
95 : : }
96 : :
97 : 1111 : bool BlockTreeDB::ReadFlag(const std::string& name, bool& fValue)
98 : : {
99 : 1111 : uint8_t ch;
100 [ + - + + ]: 1111 : if (!Read(std::make_pair(DB_FLAG, name), ch)) {
101 : : return false;
102 : : }
103 : 16 : fValue = ch == uint8_t{'1'};
104 : 16 : return true;
105 : : }
106 : :
107 : 1116 : bool BlockTreeDB::LoadBlockIndexGuts(const Consensus::Params& consensusParams, std::function<CBlockIndex*(const uint256&)> insertBlockIndex, const util::SignalInterrupt& interrupt)
108 : : {
109 : 1116 : AssertLockHeld(::cs_main);
110 [ + - ]: 1116 : std::unique_ptr<CDBIterator> pcursor(NewIterator());
111 [ + - ]: 1116 : pcursor->Seek(std::make_pair(DB_BLOCK_INDEX, uint256()));
112 : :
113 : : // Load m_block_index
114 [ + - + + ]: 145707 : while (pcursor->Valid()) {
115 [ + - + + ]: 145261 : if (interrupt) return false;
116 : 145259 : std::pair<uint8_t, uint256> key;
117 [ + - + + : 145259 : if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) {
+ - ]
118 : 144591 : CDiskBlockIndex diskindex;
119 [ + - + - ]: 144591 : if (pcursor->GetValue(diskindex)) {
120 : : // Construct block index object
121 [ + - + - ]: 144591 : CBlockIndex* pindexNew = insertBlockIndex(diskindex.ConstructBlockHash());
122 [ + - ]: 144591 : pindexNew->pprev = insertBlockIndex(diskindex.hashPrev);
123 : 144591 : pindexNew->nHeight = diskindex.nHeight;
124 : 144591 : pindexNew->nFile = diskindex.nFile;
125 : 144591 : pindexNew->nDataPos = diskindex.nDataPos;
126 : 144591 : pindexNew->nUndoPos = diskindex.nUndoPos;
127 : 144591 : pindexNew->nVersion = diskindex.nVersion;
128 : 144591 : pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
129 : 144591 : pindexNew->nTime = diskindex.nTime;
130 : 144591 : pindexNew->nBits = diskindex.nBits;
131 : 144591 : pindexNew->nNonce = diskindex.nNonce;
132 : 144591 : pindexNew->nStatus = diskindex.nStatus;
133 : 144591 : pindexNew->nTx = diskindex.nTx;
134 : :
135 [ + - - + ]: 144591 : if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, consensusParams)) {
136 [ # # # # ]: 0 : LogError("%s: CheckProofOfWork failed: %s\n", __func__, pindexNew->ToString());
137 : 0 : return false;
138 : : }
139 : :
140 [ + - ]: 144591 : pcursor->Next();
141 : : } else {
142 [ # # ]: 0 : LogError("%s: failed to read value\n", __func__);
143 : : return false;
144 : : }
145 : : } else {
146 : : break;
147 : : }
148 : : }
149 : :
150 : : return true;
151 : 1116 : }
152 : : } // namespace kernel
153 : :
154 : : namespace node {
155 : :
156 : 789262316 : bool CBlockIndexWorkComparator::operator()(const CBlockIndex* pa, const CBlockIndex* pb) const
157 : : {
158 : : // First sort by most total work, ...
159 [ + + ]: 789262316 : if (pa->nChainWork > pb->nChainWork) return false;
160 [ + + ]: 518767942 : if (pa->nChainWork < pb->nChainWork) return true;
161 : :
162 : : // ... then by earliest time received, ...
163 [ + + ]: 7232914 : if (pa->nSequenceId < pb->nSequenceId) return false;
164 [ + + ]: 7193710 : if (pa->nSequenceId > pb->nSequenceId) return true;
165 : :
166 : : // Use pointer address as tie breaker (should only happen with blocks
167 : : // loaded from disk, as those all have id 0).
168 [ + + ]: 7177751 : if (pa < pb) return false;
169 [ + + ]: 7175914 : if (pa > pb) return true;
170 : :
171 : : // Identical blocks.
172 : : return false;
173 : : }
174 : :
175 : 2850380 : bool CBlockIndexHeightOnlyComparator::operator()(const CBlockIndex* pa, const CBlockIndex* pb) const
176 : : {
177 : 2850380 : return pa->nHeight < pb->nHeight;
178 : : }
179 : :
180 : 2224 : std::vector<CBlockIndex*> BlockManager::GetAllBlockIndices()
181 : : {
182 : 2224 : AssertLockHeld(cs_main);
183 : 2224 : std::vector<CBlockIndex*> rv;
184 [ + - ]: 2224 : rv.reserve(m_block_index.size());
185 [ + + + - ]: 290688 : for (auto& [_, block_index] : m_block_index) {
186 [ + - ]: 288464 : rv.push_back(&block_index);
187 : : }
188 : 2224 : return rv;
189 : 0 : }
190 : :
191 : 660167 : CBlockIndex* BlockManager::LookupBlockIndex(const uint256& hash)
192 : : {
193 : 660167 : AssertLockHeld(cs_main);
194 : 660167 : BlockMap::iterator it = m_block_index.find(hash);
195 [ + + ]: 660167 : return it == m_block_index.end() ? nullptr : &it->second;
196 : : }
197 : :
198 : 6 : const CBlockIndex* BlockManager::LookupBlockIndex(const uint256& hash) const
199 : : {
200 : 6 : AssertLockHeld(cs_main);
201 : 6 : BlockMap::const_iterator it = m_block_index.find(hash);
202 [ + + ]: 6 : return it == m_block_index.end() ? nullptr : &it->second;
203 : : }
204 : :
205 : 144007 : CBlockIndex* BlockManager::AddToBlockIndex(const CBlockHeader& block, CBlockIndex*& best_header)
206 : : {
207 : 144007 : AssertLockHeld(cs_main);
208 : :
209 [ + + ]: 144007 : auto [mi, inserted] = m_block_index.try_emplace(block.GetHash(), block);
210 [ + + ]: 144007 : if (!inserted) {
211 : 3 : return &mi->second;
212 : : }
213 : 144004 : CBlockIndex* pindexNew = &(*mi).second;
214 : :
215 : : // We assign the sequence id to blocks only when the full data is available,
216 : : // to avoid miners withholding blocks but broadcasting headers, to get a
217 : : // competitive advantage.
218 : 144004 : pindexNew->nSequenceId = 0;
219 : :
220 : 144004 : pindexNew->phashBlock = &((*mi).first);
221 : 144004 : BlockMap::iterator miPrev = m_block_index.find(block.hashPrevBlock);
222 [ + + ]: 144004 : if (miPrev != m_block_index.end()) {
223 : 143541 : pindexNew->pprev = &(*miPrev).second;
224 : 143541 : pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
225 : 143541 : pindexNew->BuildSkip();
226 : : }
227 [ + + + + ]: 144004 : pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
228 [ + + + - ]: 432012 : pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
229 : 144004 : pindexNew->RaiseValidity(BLOCK_VALID_TREE);
230 [ + + + + ]: 144004 : if (best_header == nullptr || best_header->nChainWork < pindexNew->nChainWork) {
231 : 123341 : best_header = pindexNew;
232 : : }
233 : :
234 : 144004 : m_dirty_blockindex.insert(pindexNew);
235 : :
236 : 144004 : return pindexNew;
237 : : }
238 : :
239 : 72 : void BlockManager::PruneOneBlockFile(const int fileNumber)
240 : : {
241 : 72 : AssertLockHeld(cs_main);
242 : 72 : LOCK(cs_LastBlockFile);
243 : :
244 [ + + + + ]: 127485 : for (auto& entry : m_block_index) {
245 : 127413 : CBlockIndex* pindex = &entry.second;
246 [ + + ]: 127413 : if (pindex->nFile == fileNumber) {
247 : 17419 : pindex->nStatus &= ~BLOCK_HAVE_DATA;
248 : 17419 : pindex->nStatus &= ~BLOCK_HAVE_UNDO;
249 : 17419 : pindex->nFile = 0;
250 : 17419 : pindex->nDataPos = 0;
251 : 17419 : pindex->nUndoPos = 0;
252 [ + - ]: 17419 : m_dirty_blockindex.insert(pindex);
253 : :
254 : : // Prune from m_blocks_unlinked -- any block we prune would have
255 : : // to be downloaded again in order to consider its chain, at which
256 : : // point it would be considered as a candidate for
257 : : // m_blocks_unlinked or setBlockIndexCandidates.
258 : 17419 : auto range = m_blocks_unlinked.equal_range(pindex->pprev);
259 [ - + ]: 17419 : while (range.first != range.second) {
260 : 0 : std::multimap<CBlockIndex*, CBlockIndex*>::iterator _it = range.first;
261 : 0 : range.first++;
262 [ # # ]: 0 : if (_it->second == pindex) {
263 : 0 : m_blocks_unlinked.erase(_it);
264 : : }
265 : : }
266 : : }
267 : : }
268 : :
269 [ + - ]: 72 : m_blockfile_info.at(fileNumber) = CBlockFileInfo{};
270 [ + - ]: 72 : m_dirty_fileinfo.insert(fileNumber);
271 : 72 : }
272 : :
273 : 27 : void BlockManager::FindFilesToPruneManual(
274 : : std::set<int>& setFilesToPrune,
275 : : int nManualPruneHeight,
276 : : const Chainstate& chain,
277 : : ChainstateManager& chainman)
278 : : {
279 [ + - - + ]: 27 : assert(IsPruneMode() && nManualPruneHeight > 0);
280 : :
281 [ + - ]: 27 : LOCK2(cs_main, cs_LastBlockFile);
282 [ - + ]: 27 : if (chain.m_chain.Height() < 0) {
283 [ # # ]: 0 : return;
284 : : }
285 : :
286 [ + - ]: 27 : const auto [min_block_to_prune, last_block_can_prune] = chainman.GetPruneRange(chain, nManualPruneHeight);
287 : :
288 : 27 : int count = 0;
289 [ + + ]: 149 : for (int fileNumber = 0; fileNumber < this->MaxBlockfileNum(); fileNumber++) {
290 [ + + ]: 122 : const auto& fileinfo = m_blockfile_info[fileNumber];
291 [ + + + + : 122 : if (fileinfo.nSize == 0 || fileinfo.nHeightLast > (unsigned)last_block_can_prune || fileinfo.nHeightFirst < (unsigned)min_block_to_prune) {
- + ]
292 : 69 : continue;
293 : : }
294 : :
295 [ + - ]: 53 : PruneOneBlockFile(fileNumber);
296 [ + - ]: 53 : setFilesToPrune.insert(fileNumber);
297 : 53 : count++;
298 : : }
299 [ + - + - ]: 27 : LogPrintf("[%s] Prune (Manual): prune_height=%d removed %d blk/rev pairs\n",
300 : : chain.GetRole(), last_block_can_prune, count);
301 [ - - + - ]: 54 : }
302 : :
303 : 592 : void BlockManager::FindFilesToPrune(
304 : : std::set<int>& setFilesToPrune,
305 : : int last_prune,
306 : : const Chainstate& chain,
307 : : ChainstateManager& chainman)
308 : : {
309 [ + - ]: 592 : LOCK2(cs_main, cs_LastBlockFile);
310 : : // Distribute our -prune budget over all chainstates.
311 [ + - ]: 592 : const auto target = std::max(
312 [ + - + + ]: 785 : MIN_DISK_SPACE_FOR_BLOCK_FILES, GetPruneTarget() / chainman.GetAll().size());
313 : 592 : const uint64_t target_sync_height = chainman.m_best_header->nHeight;
314 : :
315 [ + + + - ]: 592 : if (chain.m_chain.Height() < 0 || target == 0) {
316 : : return;
317 : : }
318 [ + + ]: 573 : if (static_cast<uint64_t>(chain.m_chain.Height()) <= chainman.GetParams().PruneAfterHeight()) {
319 : : return;
320 : : }
321 : :
322 [ + - + - ]: 463 : const auto [min_block_to_prune, last_block_can_prune] = chainman.GetPruneRange(chain, last_prune);
323 : :
324 [ + - ]: 463 : uint64_t nCurrentUsage = CalculateCurrentUsage();
325 : : // We don't check to prune until after we've allocated new space for files
326 : : // So we should leave a buffer under our target to account for another allocation
327 : : // before the next pruning.
328 : 463 : uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
329 : 463 : uint64_t nBytesToPrune;
330 : 463 : int count = 0;
331 : :
332 [ + + ]: 463 : if (nCurrentUsage + nBuffer >= target) {
333 : : // On a prune event, the chainstate DB is flushed.
334 : : // To avoid excessive prune events negating the benefit of high dbcache
335 : : // values, we should not prune too rapidly.
336 : : // So when pruning in IBD, increase the buffer to avoid a re-prune too soon.
337 [ + - ]: 23 : const auto chain_tip_height = chain.m_chain.Height();
338 [ + - - + : 23 : if (chainman.IsInitialBlockDownload() && target_sync_height > (uint64_t)chain_tip_height) {
- - ]
339 : : // Since this is only relevant during IBD, we assume blocks are at least 1 MB on average
340 : 0 : static constexpr uint64_t average_block_size = 1000000; /* 1 MB */
341 : 0 : const uint64_t remaining_blocks = target_sync_height - chain_tip_height;
342 : 0 : nBuffer += average_block_size * remaining_blocks;
343 : : }
344 : :
345 [ + + ]: 169 : for (int fileNumber = 0; fileNumber < this->MaxBlockfileNum(); fileNumber++) {
346 [ + + ]: 158 : const auto& fileinfo = m_blockfile_info[fileNumber];
347 : 158 : nBytesToPrune = fileinfo.nSize + fileinfo.nUndoSize;
348 : :
349 [ + + ]: 158 : if (fileinfo.nSize == 0) {
350 : 86 : continue;
351 : : }
352 : :
353 [ + + ]: 72 : if (nCurrentUsage + nBuffer < target) { // are we below our target?
354 : : break;
355 : : }
356 : :
357 : : // don't prune files that could have a block that's not within the allowable
358 : : // prune range for the chain being pruned.
359 [ + + - + ]: 60 : if (fileinfo.nHeightLast > (unsigned)last_block_can_prune || fileinfo.nHeightFirst < (unsigned)min_block_to_prune) {
360 : 44 : continue;
361 : : }
362 : :
363 [ + - ]: 16 : PruneOneBlockFile(fileNumber);
364 : : // Queue up the files for removal
365 [ + - ]: 16 : setFilesToPrune.insert(fileNumber);
366 : 16 : nCurrentUsage -= nBytesToPrune;
367 : 16 : count++;
368 : : }
369 : : }
370 : :
371 [ + - + - : 463 : LogDebug(BCLog::PRUNE, "[%s] target=%dMiB actual=%dMiB diff=%dMiB min_height=%d max_prune_height=%d removed %d blk/rev pairs\n",
+ - + - +
- ]
372 : : chain.GetRole(), target / 1024 / 1024, nCurrentUsage / 1024 / 1024,
373 : : (int64_t(target) - int64_t(nCurrentUsage)) / 1024 / 1024,
374 : : min_block_to_prune, last_block_can_prune, count);
375 [ + - + - ]: 1184 : }
376 : :
377 : 20534 : void BlockManager::UpdatePruneLock(const std::string& name, const PruneLockInfo& lock_info) {
378 : 20534 : AssertLockHeld(::cs_main);
379 : 20534 : m_prune_locks[name] = lock_info;
380 : 20534 : }
381 : :
382 : 289182 : CBlockIndex* BlockManager::InsertBlockIndex(const uint256& hash)
383 : : {
384 : 289182 : AssertLockHeld(cs_main);
385 : :
386 [ + + ]: 289182 : if (hash.IsNull()) {
387 : : return nullptr;
388 : : }
389 : :
390 [ + + ]: 288514 : const auto [mi, inserted]{m_block_index.try_emplace(hash)};
391 [ + + ]: 288514 : CBlockIndex* pindex = &(*mi).second;
392 [ + + ]: 288514 : if (inserted) {
393 : 143620 : pindex->phashBlock = &((*mi).first);
394 : : }
395 : : return pindex;
396 : : }
397 : :
398 : 1116 : bool BlockManager::LoadBlockIndex(const std::optional<uint256>& snapshot_blockhash)
399 : : {
400 [ + - + + ]: 1116 : if (!m_block_tree_db->LoadBlockIndexGuts(
401 [ + - ]: 290298 : GetConsensus(), [this](const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return this->InsertBlockIndex(hash); }, m_interrupt)) {
402 : : return false;
403 : : }
404 : :
405 [ + + ]: 1114 : if (snapshot_blockhash) {
406 : 11 : const std::optional<AssumeutxoData> maybe_au_data = GetParams().AssumeutxoForBlockhash(*snapshot_blockhash);
407 [ + + ]: 11 : if (!maybe_au_data) {
408 [ + - + - ]: 2 : m_opts.notifications.fatalError(strprintf(_("Assumeutxo data not found for the given blockhash '%s'."), snapshot_blockhash->ToString()));
409 : 1 : return false;
410 : : }
411 : 10 : const AssumeutxoData& au_data = *Assert(maybe_au_data);
412 : 10 : m_snapshot_height = au_data.height;
413 : 10 : CBlockIndex* base{LookupBlockIndex(*snapshot_blockhash)};
414 : :
415 : : // Since m_chain_tx_count (responsible for estimated progress) isn't persisted
416 : : // to disk, we must bootstrap the value for assumedvalid chainstates
417 : : // from the hardcoded assumeutxo chainparams.
418 : 10 : base->m_chain_tx_count = au_data.m_chain_tx_count;
419 [ + - ]: 20 : LogPrintf("[snapshot] set m_chain_tx_count=%d for %s\n", au_data.m_chain_tx_count, snapshot_blockhash->ToString());
420 : : } else {
421 : : // If this isn't called with a snapshot blockhash, make sure the cached snapshot height
422 : : // is null. This is relevant during snapshot completion, when the blockman may be loaded
423 : : // with a height that then needs to be cleared after the snapshot is fully validated.
424 [ + + ]: 1103 : m_snapshot_height.reset();
425 : : }
426 : :
427 : 1113 : Assert(m_snapshot_height.has_value() == snapshot_blockhash.has_value());
428 : :
429 : : // Calculate nChainWork
430 : 1113 : std::vector<CBlockIndex*> vSortedByHeight{GetAllBlockIndices()};
431 [ + - ]: 1113 : std::sort(vSortedByHeight.begin(), vSortedByHeight.end(),
432 : : CBlockIndexHeightOnlyComparator());
433 : :
434 : 1113 : CBlockIndex* previous_index{nullptr};
435 [ + + ]: 145375 : for (CBlockIndex* pindex : vSortedByHeight) {
436 [ + - + - ]: 144263 : if (m_interrupt) return false;
437 [ + + + + ]: 144263 : if (previous_index && pindex->nHeight > previous_index->nHeight + 1) {
438 [ + - ]: 1 : LogError("%s: block index is non-contiguous, index of height %d missing\n", __func__, previous_index->nHeight + 1);
439 : : return false;
440 : : }
441 : 144262 : previous_index = pindex;
442 [ + - + + : 432786 : pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
+ - ]
443 [ + + + + ]: 144262 : pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
444 : :
445 : : // We can link the chain of blocks for which we've received transactions at some point, or
446 : : // blocks that are assumed-valid on the basis of snapshot load (see
447 : : // PopulateAndValidateSnapshot()).
448 : : // Pruned nodes may have deleted the block.
449 [ + + ]: 144262 : if (pindex->nTx > 0) {
450 [ + + ]: 143090 : if (pindex->pprev) {
451 [ + + + + : 142426 : if (m_snapshot_height && pindex->nHeight == *m_snapshot_height &&
+ - ]
452 [ + - ]: 4 : pindex->GetBlockHash() == *snapshot_blockhash) {
453 : : // Should have been set above; don't disturb it with code below.
454 [ + - ]: 4 : Assert(pindex->m_chain_tx_count > 0);
455 [ + + ]: 142418 : } else if (pindex->pprev->m_chain_tx_count > 0) {
456 : 142411 : pindex->m_chain_tx_count = pindex->pprev->m_chain_tx_count + pindex->nTx;
457 : : } else {
458 : 7 : pindex->m_chain_tx_count = 0;
459 [ + - ]: 7 : m_blocks_unlinked.insert(std::make_pair(pindex->pprev, pindex));
460 : : }
461 : : } else {
462 : 668 : pindex->m_chain_tx_count = pindex->nTx;
463 : : }
464 : : }
465 [ + + + + : 144262 : if (!(pindex->nStatus & BLOCK_FAILED_MASK) && pindex->pprev && (pindex->pprev->nStatus & BLOCK_FAILED_MASK)) {
- + ]
466 : 0 : pindex->nStatus |= BLOCK_FAILED_CHILD;
467 [ # # ]: 0 : m_dirty_blockindex.insert(pindex);
468 : : }
469 [ + + ]: 144262 : if (pindex->pprev) {
470 [ + - ]: 143571 : pindex->BuildSkip();
471 : : }
472 : : }
473 : :
474 : : return true;
475 : 1113 : }
476 : :
477 : 3214 : bool BlockManager::WriteBlockIndexDB()
478 : : {
479 : 3214 : AssertLockHeld(::cs_main);
480 : 3214 : std::vector<std::pair<int, const CBlockFileInfo*>> vFiles;
481 [ + - ]: 3214 : vFiles.reserve(m_dirty_fileinfo.size());
482 [ + + ]: 4950 : for (std::set<int>::iterator it = m_dirty_fileinfo.begin(); it != m_dirty_fileinfo.end();) {
483 [ + - ]: 1736 : vFiles.emplace_back(*it, &m_blockfile_info[*it]);
484 : 1736 : m_dirty_fileinfo.erase(it++);
485 : : }
486 : 3214 : std::vector<const CBlockIndex*> vBlocks;
487 [ + - ]: 3214 : vBlocks.reserve(m_dirty_blockindex.size());
488 [ + + ]: 157950 : for (std::set<CBlockIndex*>::iterator it = m_dirty_blockindex.begin(); it != m_dirty_blockindex.end();) {
489 [ + - ]: 154736 : vBlocks.push_back(*it);
490 : 154736 : m_dirty_blockindex.erase(it++);
491 : : }
492 [ + - + - ]: 6428 : int max_blockfile = WITH_LOCK(cs_LastBlockFile, return this->MaxBlockfileNum());
493 [ + - - + ]: 3214 : if (!m_block_tree_db->WriteBatchSync(vFiles, max_blockfile, vBlocks)) {
494 : 0 : return false;
495 : : }
496 : : return true;
497 : 3214 : }
498 : :
499 : 1116 : bool BlockManager::LoadBlockIndexDB(const std::optional<uint256>& snapshot_blockhash)
500 : : {
501 [ + + ]: 1116 : if (!LoadBlockIndex(snapshot_blockhash)) {
502 : : return false;
503 : : }
504 : 1112 : int max_blockfile_num{0};
505 : :
506 : : // Load block file info
507 : 1112 : m_block_tree_db->ReadLastBlockFile(max_blockfile_num);
508 : 1112 : m_blockfile_info.resize(max_blockfile_num + 1);
509 : 1112 : LogPrintf("%s: last block file = %i\n", __func__, max_blockfile_num);
510 [ + + ]: 2357 : for (int nFile = 0; nFile <= max_blockfile_num; nFile++) {
511 : 1245 : m_block_tree_db->ReadBlockFileInfo(nFile, m_blockfile_info[nFile]);
512 : : }
513 [ + - ]: 1112 : LogPrintf("%s: last block file info: %s\n", __func__, m_blockfile_info[max_blockfile_num].ToString());
514 : 1112 : for (int nFile = max_blockfile_num + 1; true; nFile++) {
515 : 1112 : CBlockFileInfo info;
516 [ - + ]: 1112 : if (m_block_tree_db->ReadBlockFileInfo(nFile, info)) {
517 : 0 : m_blockfile_info.push_back(info);
518 : : } else {
519 : : break;
520 : : }
521 : 0 : }
522 : :
523 : : // Check presence of blk files
524 : 1112 : LogPrintf("Checking all blk files are present...\n");
525 : 1112 : std::set<int> setBlkDataFiles;
526 [ + + + + ]: 145348 : for (const auto& [_, block_index] : m_block_index) {
527 [ + + ]: 144236 : if (block_index.nStatus & BLOCK_HAVE_DATA) {
528 [ + - ]: 128514 : setBlkDataFiles.insert(block_index.nFile);
529 : : }
530 : : }
531 [ + + ]: 1851 : for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) {
532 [ + - ]: 740 : FlatFilePos pos(*it, 0);
533 [ + - + + ]: 1480 : if (OpenBlockFile(pos, /*fReadOnly=*/true).IsNull()) {
534 : : return false;
535 : : }
536 : : }
537 : :
538 : 1111 : {
539 : : // Initialize the blockfile cursors.
540 [ + - ]: 1111 : LOCK(cs_LastBlockFile);
541 [ + + ]: 2355 : for (size_t i = 0; i < m_blockfile_info.size(); ++i) {
542 [ + - ]: 1244 : const auto last_height_in_file = m_blockfile_info[i].nHeightLast;
543 [ + - + + ]: 2488 : m_blockfile_cursors[BlockfileTypeForHeight(last_height_in_file)] = {static_cast<int>(i), 0};
544 : : }
545 : 0 : }
546 : :
547 : : // Check whether we have ever pruned block & undo files
548 [ + - + - ]: 1111 : m_block_tree_db->ReadFlag("prunedblockfiles", m_have_pruned);
549 [ + + ]: 1111 : if (m_have_pruned) {
550 [ + - ]: 16 : LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
551 : : }
552 : :
553 : : // Check whether we need to continue reindexing
554 : 1111 : bool fReindexing = false;
555 [ + - ]: 1111 : m_block_tree_db->ReadReindexing(fReindexing);
556 [ + + ]: 1111 : if (fReindexing) m_blockfiles_indexed = false;
557 : :
558 : : return true;
559 : 1112 : }
560 : :
561 : 1114 : void BlockManager::ScanAndUnlinkAlreadyPrunedFiles()
562 : : {
563 : 1114 : AssertLockHeld(::cs_main);
564 [ + - ]: 2228 : int max_blockfile = WITH_LOCK(cs_LastBlockFile, return this->MaxBlockfileNum());
565 [ + + ]: 1114 : if (!m_have_pruned) {
566 : : return;
567 : : }
568 : :
569 : 18 : std::set<int> block_files_to_prune;
570 [ + + ]: 111 : for (int file_number = 0; file_number < max_blockfile; file_number++) {
571 [ + + ]: 93 : if (m_blockfile_info[file_number].nSize == 0) {
572 [ + - ]: 63 : block_files_to_prune.insert(file_number);
573 : : }
574 : : }
575 : :
576 [ + - ]: 18 : UnlinkPrunedFiles(block_files_to_prune);
577 : 18 : }
578 : :
579 : 227 : bool BlockManager::IsBlockPruned(const CBlockIndex& block) const
580 : : {
581 : 227 : AssertLockHeld(::cs_main);
582 [ + + + - : 227 : return m_have_pruned && !(block.nStatus & BLOCK_HAVE_DATA) && (block.nTx > 0);
- + ]
583 : : }
584 : :
585 : 107 : const CBlockIndex* BlockManager::GetFirstBlock(const CBlockIndex& upper_block, uint32_t status_mask, const CBlockIndex* lower_block) const
586 : : {
587 : 107 : AssertLockHeld(::cs_main);
588 : 107 : const CBlockIndex* last_block = &upper_block;
589 [ - + ]: 107 : assert((last_block->nStatus & status_mask) == status_mask); // 'upper_block' must satisfy the status mask
590 [ + + + + ]: 39966 : while (last_block->pprev && ((last_block->pprev->nStatus & status_mask) == status_mask)) {
591 [ + + ]: 39871 : if (lower_block) {
592 : : // Return if we reached the lower_block
593 [ + + ]: 39722 : if (last_block == lower_block) return lower_block;
594 : : // if range was surpassed, means that 'lower_block' is not part of the 'upper_block' chain
595 : : // and so far this is not allowed.
596 [ - + ]: 39710 : assert(last_block->nHeight >= lower_block->nHeight);
597 : : }
598 : : last_block = last_block->pprev;
599 : : }
600 [ - + ]: 95 : assert(last_block != nullptr);
601 : : return last_block;
602 : : }
603 : :
604 : 36 : bool BlockManager::CheckBlockDataAvailability(const CBlockIndex& upper_block, const CBlockIndex& lower_block)
605 : : {
606 [ + - ]: 36 : if (!(upper_block.nStatus & BLOCK_HAVE_DATA)) return false;
607 : 36 : return GetFirstBlock(upper_block, BLOCK_HAVE_DATA, &lower_block) == &lower_block;
608 : : }
609 : :
610 : : // If we're using -prune with -reindex, then delete block files that will be ignored by the
611 : : // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
612 : : // is missing, do the same here to delete any later block files after a gap. Also delete all
613 : : // rev files since they'll be rewritten by the reindex anyway. This ensures that m_blockfile_info
614 : : // is in sync with what's actually on disk by the time we start downloading, so that pruning
615 : : // works correctly.
616 : 5 : void BlockManager::CleanupBlockRevFiles() const
617 : : {
618 [ + - ]: 5 : std::map<std::string, fs::path> mapBlockFiles;
619 : :
620 : : // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
621 : : // Remove the rev files immediately and insert the blk file paths into an
622 : : // ordered map keyed by block file index.
623 [ + - ]: 5 : LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
624 [ + - + + : 49 : for (fs::directory_iterator it(m_opts.blocks_dir); it != fs::directory_iterator(); it++) {
+ + ]
625 [ + - + - ]: 156 : const std::string path = fs::PathToString(it->path().filename());
626 [ + - ]: 39 : if (fs::is_regular_file(*it) &&
627 [ + + + + ]: 39 : path.length() == 12 &&
628 [ + - ]: 24 : path.ends_with(".dat"))
629 : : {
630 [ + + ]: 24 : if (path.starts_with("blk")) {
631 [ + - + - : 24 : mapBlockFiles[path.substr(3, 5)] = it->path();
+ - ]
632 [ + - ]: 12 : } else if (path.starts_with("rev")) {
633 [ + - ]: 12 : remove(it->path());
634 : : }
635 : : }
636 [ + - ]: 39 : }
637 : :
638 : : // Remove all block files that aren't part of a contiguous set starting at
639 : : // zero by walking the ordered map (keys are block file indices) by
640 : : // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
641 : : // start removing block files.
642 : 5 : int nContigCounter = 0;
643 [ + + ]: 17 : for (const std::pair<const std::string, fs::path>& item : mapBlockFiles) {
644 [ + - + + ]: 12 : if (LocaleIndependentAtoi<int>(item.first) == nContigCounter) {
645 : 1 : nContigCounter++;
646 : 1 : continue;
647 : : }
648 [ + - ]: 11 : remove(item.second);
649 : : }
650 : 5 : }
651 : :
652 : 3 : CBlockFileInfo* BlockManager::GetBlockFileInfo(size_t n)
653 : : {
654 : 3 : LOCK(cs_LastBlockFile);
655 : :
656 [ + - + - ]: 3 : return &m_blockfile_info.at(n);
657 : 3 : }
658 : :
659 : 53587 : bool BlockManager::ReadBlockUndo(CBlockUndo& blockundo, const CBlockIndex& index) const
660 : : {
661 [ + - ]: 107174 : const FlatFilePos pos{WITH_LOCK(::cs_main, return index.GetUndoPos())};
662 : :
663 : : // Open history file to read
664 : 53587 : AutoFile file{OpenUndoFile(pos, true)};
665 [ + + ]: 53587 : if (file.IsNull()) {
666 [ + - + - ]: 7 : LogError("OpenUndoFile failed for %s while reading block undo", pos.ToString());
667 : 7 : return false;
668 : : }
669 [ + - ]: 53580 : BufferedReader filein{std::move(file)};
670 : :
671 : 53580 : try {
672 : : // Read block
673 [ + - ]: 53580 : HashVerifier verifier{filein}; // Use HashVerifier, as reserializing may lose data, c.f. commit d3424243
674 : :
675 [ + - ]: 53580 : verifier << index.pprev->GetBlockHash();
676 [ + + ]: 53580 : verifier >> blockundo;
677 : :
678 : 53579 : uint256 hashChecksum;
679 [ + - ]: 53579 : filein >> hashChecksum;
680 : :
681 : : // Verify checksum
682 [ + - - + ]: 53579 : if (hashChecksum != verifier.GetHash()) {
683 [ # # # # ]: 0 : LogError("Checksum mismatch at %s while reading block undo", pos.ToString());
684 : 0 : return false;
685 : : }
686 [ - + ]: 1 : } catch (const std::exception& e) {
687 [ + - + - ]: 1 : LogError("Deserialize or I/O error - %s at %s while reading block undo", e.what(), pos.ToString());
688 : 1 : return false;
689 : 1 : }
690 : :
691 : : return true;
692 : 107167 : }
693 : :
694 : 3318 : bool BlockManager::FlushUndoFile(int block_file, bool finalize)
695 : : {
696 : 3318 : FlatFilePos undo_pos_old(block_file, m_blockfile_info[block_file].nUndoSize);
697 [ - + ]: 3318 : if (!m_undo_file_seq.Flush(undo_pos_old, finalize)) {
698 [ # # ]: 0 : m_opts.notifications.flushError(_("Flushing undo file to disk failed. This is likely the result of an I/O error."));
699 : 0 : return false;
700 : : }
701 : : return true;
702 : : }
703 : :
704 : 3317 : bool BlockManager::FlushBlockFile(int blockfile_num, bool fFinalize, bool finalize_undo)
705 : : {
706 : 3317 : bool success = true;
707 : 3317 : LOCK(cs_LastBlockFile);
708 : :
709 [ + - ]: 3317 : if (m_blockfile_info.size() < 1) {
710 : : // Return if we haven't loaded any blockfiles yet. This happens during
711 : : // chainstate init, when we call ChainstateManager::MaybeRebalanceCaches() (which
712 : : // then calls FlushStateToDisk()), resulting in a call to this function before we
713 : : // have populated `m_blockfile_info` via LoadBlockIndexDB().
714 : : return true;
715 : : }
716 [ - + ]: 3317 : assert(static_cast<int>(m_blockfile_info.size()) > blockfile_num);
717 : :
718 [ + - ]: 3317 : FlatFilePos block_pos_old(blockfile_num, m_blockfile_info[blockfile_num].nSize);
719 [ + - - + ]: 3317 : if (!m_block_file_seq.Flush(block_pos_old, fFinalize)) {
720 [ # # # # ]: 0 : m_opts.notifications.flushError(_("Flushing block file to disk failed. This is likely the result of an I/O error."));
721 : 0 : success = false;
722 : : }
723 : : // we do not always flush the undo file, as the chain tip may be lagging behind the incoming blocks,
724 : : // e.g. during IBD or a sync after a node going offline
725 [ + - ]: 3317 : if (!fFinalize || finalize_undo) {
726 [ + - - + ]: 3317 : if (!FlushUndoFile(blockfile_num, finalize_undo)) {
727 : 0 : success = false;
728 : : }
729 : : }
730 : : return success;
731 : 3317 : }
732 : :
733 : 265076 : BlockfileType BlockManager::BlockfileTypeForHeight(int height)
734 : : {
735 [ + + ]: 265076 : if (!m_snapshot_height) {
736 : : return BlockfileType::NORMAL;
737 : : }
738 [ + + ]: 3725 : return (height >= *m_snapshot_height) ? BlockfileType::ASSUMED : BlockfileType::NORMAL;
739 : : }
740 : :
741 : 3214 : bool BlockManager::FlushChainstateBlockFile(int tip_height)
742 : : {
743 : 3214 : LOCK(cs_LastBlockFile);
744 [ + - + + ]: 3214 : auto& cursor = m_blockfile_cursors[BlockfileTypeForHeight(tip_height)];
745 : : // If the cursor does not exist, it means an assumeutxo snapshot is loaded,
746 : : // but no blocks past the snapshot height have been written yet, so there
747 : : // is no data associated with the chainstate, and it is safe not to flush.
748 [ + + ]: 3214 : if (cursor) {
749 [ + - ]: 3189 : return FlushBlockFile(cursor->file_num, /*fFinalize=*/false, /*finalize_undo=*/false);
750 : : }
751 : : // No need to log warnings in this case.
752 : : return true;
753 : 3214 : }
754 : :
755 : 20461 : uint64_t BlockManager::CalculateCurrentUsage()
756 : : {
757 : 20461 : LOCK(cs_LastBlockFile);
758 : :
759 : 20461 : uint64_t retval = 0;
760 [ + + ]: 43212 : for (const CBlockFileInfo& file : m_blockfile_info) {
761 : 22751 : retval += file.nSize + file.nUndoSize;
762 : : }
763 [ + - ]: 20461 : return retval;
764 : 20461 : }
765 : :
766 : 55 : void BlockManager::UnlinkPrunedFiles(const std::set<int>& setFilesToPrune) const
767 : : {
768 : 55 : std::error_code ec;
769 [ + + ]: 189 : for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
770 : 134 : FlatFilePos pos(*it, 0);
771 : 134 : const bool removed_blockfile{fs::remove(m_block_file_seq.FileName(pos), ec)};
772 : 134 : const bool removed_undofile{fs::remove(m_undo_file_seq.FileName(pos), ec)};
773 [ + + ]: 134 : if (removed_blockfile || removed_undofile) {
774 [ + - ]: 72 : LogDebug(BCLog::BLOCKSTORAGE, "Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
775 : : }
776 : : }
777 : 55 : }
778 : :
779 : 292221 : AutoFile BlockManager::OpenBlockFile(const FlatFilePos& pos, bool fReadOnly) const
780 : : {
781 [ + - ]: 584442 : return AutoFile{m_block_file_seq.Open(pos, fReadOnly), m_xor_key};
782 : : }
783 : :
784 : : /** Open an undo file (rev?????.dat) */
785 : 178373 : AutoFile BlockManager::OpenUndoFile(const FlatFilePos& pos, bool fReadOnly) const
786 : : {
787 [ + - ]: 356746 : return AutoFile{m_undo_file_seq.Open(pos, fReadOnly), m_xor_key};
788 : : }
789 : :
790 : 33 : fs::path BlockManager::GetBlockPosFilename(const FlatFilePos& pos) const
791 : : {
792 : 33 : return m_block_file_seq.FileName(pos);
793 : : }
794 : :
795 : 126037 : FlatFilePos BlockManager::FindNextBlockPos(unsigned int nAddSize, unsigned int nHeight, uint64_t nTime)
796 : : {
797 : 126037 : LOCK(cs_LastBlockFile);
798 : :
799 [ + - ]: 126037 : const BlockfileType chain_type = BlockfileTypeForHeight(nHeight);
800 : :
801 [ + + ]: 126037 : if (!m_blockfile_cursors[chain_type]) {
802 : : // If a snapshot is loaded during runtime, we may not have initialized this cursor yet.
803 [ - + ]: 11 : assert(chain_type == BlockfileType::ASSUMED);
804 : 11 : const auto new_cursor = BlockfileCursor{this->MaxBlockfileNum() + 1};
805 [ + - ]: 11 : m_blockfile_cursors[chain_type] = new_cursor;
806 [ + - + - : 11 : LogDebug(BCLog::BLOCKSTORAGE, "[%s] initializing blockfile cursor to %s\n", chain_type, new_cursor);
+ - ]
807 : : }
808 [ + + ]: 126037 : const int last_blockfile = m_blockfile_cursors[chain_type]->file_num;
809 : :
810 : 126037 : int nFile = last_blockfile;
811 [ + + ]: 126037 : if (static_cast<int>(m_blockfile_info.size()) <= nFile) {
812 [ + - ]: 18 : m_blockfile_info.resize(nFile + 1);
813 : : }
814 : :
815 : 126037 : bool finalize_undo = false;
816 : 126037 : unsigned int max_blockfile_size{MAX_BLOCKFILE_SIZE};
817 : : // Use smaller blockfiles in test-only -fastprune mode - but avoid
818 : : // the possibility of having a block not fit into the block file.
819 [ + + ]: 126037 : if (m_opts.fast_prune) {
820 : 17888 : max_blockfile_size = 0x10000; // 64kiB
821 [ + + ]: 17888 : if (nAddSize >= max_blockfile_size) {
822 : : // dynamically adjust the blockfile size to be larger than the added size
823 : 2 : max_blockfile_size = nAddSize + 1;
824 : : }
825 : : }
826 [ - + ]: 126037 : assert(nAddSize < max_blockfile_size);
827 : :
828 [ + + ]: 126165 : while (m_blockfile_info[nFile].nSize + nAddSize >= max_blockfile_size) {
829 : : // when the undo file is keeping up with the block file, we want to flush it explicitly
830 : : // when it is lagging behind (more blocks arrive than are being connected), we let the
831 : : // undo block write case handle it
832 : 256 : finalize_undo = (static_cast<int>(m_blockfile_info[nFile].nHeightLast) ==
833 [ + - + - ]: 128 : Assert(m_blockfile_cursors[chain_type])->undo_height);
834 : :
835 : : // Try the next unclaimed blockfile number
836 : 128 : nFile = this->MaxBlockfileNum() + 1;
837 : : // Set to increment MaxBlockfileNum() for next iteration
838 [ + - ]: 128 : m_blockfile_cursors[chain_type] = BlockfileCursor{nFile};
839 : :
840 [ + - ]: 128 : if (static_cast<int>(m_blockfile_info.size()) <= nFile) {
841 [ + - ]: 128 : m_blockfile_info.resize(nFile + 1);
842 : : }
843 : : }
844 : 126037 : FlatFilePos pos;
845 : 126037 : pos.nFile = nFile;
846 : 126037 : pos.nPos = m_blockfile_info[nFile].nSize;
847 : :
848 [ + + ]: 126037 : if (nFile != last_blockfile) {
849 [ + - + - : 256 : LogDebug(BCLog::BLOCKSTORAGE, "Leaving block file %i: %s (onto %i) (height %i)\n",
+ - + - ]
850 : : last_blockfile, m_blockfile_info[last_blockfile].ToString(), nFile, nHeight);
851 : :
852 : : // Do not propagate the return code. The flush concerns a previous block
853 : : // and undo file that has already been written to. If a flush fails
854 : : // here, and we crash, there is no expected additional block data
855 : : // inconsistency arising from the flush failure here. However, the undo
856 : : // data may be inconsistent after a crash if the flush is called during
857 : : // a reindex. A flush error might also leave some of the data files
858 : : // untrimmed.
859 [ + - - + ]: 128 : if (!FlushBlockFile(last_blockfile, /*fFinalize=*/true, finalize_undo)) {
860 [ # # # # : 0 : LogPrintLevel(BCLog::BLOCKSTORAGE, BCLog::Level::Warning,
# # ]
861 : : "Failed to flush previous block file %05i (finalize=1, finalize_undo=%i) before opening new block file %05i\n",
862 : : last_blockfile, finalize_undo, nFile);
863 : : }
864 : : // No undo data yet in the new file, so reset our undo-height tracking.
865 [ + - ]: 128 : m_blockfile_cursors[chain_type] = BlockfileCursor{nFile};
866 : : }
867 : :
868 : 126037 : m_blockfile_info[nFile].AddBlock(nHeight, nTime);
869 [ + - ]: 126037 : m_blockfile_info[nFile].nSize += nAddSize;
870 : :
871 : 126037 : bool out_of_space;
872 [ + - ]: 126037 : size_t bytes_allocated = m_block_file_seq.Allocate(pos, nAddSize, out_of_space);
873 [ - + ]: 126037 : if (out_of_space) {
874 [ # # # # ]: 0 : m_opts.notifications.fatalError(_("Disk space is too low!"));
875 : 0 : return {};
876 : : }
877 [ + + + + ]: 126037 : if (bytes_allocated != 0 && IsPruneMode()) {
878 : 446 : m_check_for_pruning = true;
879 : : }
880 : :
881 [ + - ]: 126037 : m_dirty_fileinfo.insert(nFile);
882 : 126037 : return pos;
883 : 126037 : }
884 : :
885 : 3478 : void BlockManager::UpdateBlockInfo(const CBlock& block, unsigned int nHeight, const FlatFilePos& pos)
886 : : {
887 : 3478 : LOCK(cs_LastBlockFile);
888 : :
889 : : // Update the cursor so it points to the last file.
890 [ + - ]: 3478 : const BlockfileType chain_type{BlockfileTypeForHeight(nHeight)};
891 [ + - ]: 3478 : auto& cursor{m_blockfile_cursors[chain_type]};
892 [ + - + + ]: 3478 : if (!cursor || cursor->file_num < pos.nFile) {
893 [ + - ]: 1 : m_blockfile_cursors[chain_type] = BlockfileCursor{pos.nFile};
894 : : }
895 : :
896 : : // Update the file information with the current block.
897 : 3478 : const unsigned int added_size = ::GetSerializeSize(TX_WITH_WITNESS(block));
898 : 3478 : const int nFile = pos.nFile;
899 [ + + ]: 3478 : if (static_cast<int>(m_blockfile_info.size()) <= nFile) {
900 [ + - ]: 15 : m_blockfile_info.resize(nFile + 1);
901 : : }
902 : 3478 : m_blockfile_info[nFile].AddBlock(nHeight, block.GetBlockTime());
903 [ + + ]: 3478 : m_blockfile_info[nFile].nSize = std::max(pos.nPos + added_size, m_blockfile_info[nFile].nSize);
904 [ + - ]: 3478 : m_dirty_fileinfo.insert(nFile);
905 : 3478 : }
906 : :
907 : 124786 : bool BlockManager::FindUndoPos(BlockValidationState& state, int nFile, FlatFilePos& pos, unsigned int nAddSize)
908 : : {
909 : 124786 : pos.nFile = nFile;
910 : :
911 : 124786 : LOCK(cs_LastBlockFile);
912 : :
913 [ + - ]: 124786 : pos.nPos = m_blockfile_info[nFile].nUndoSize;
914 : 124786 : m_blockfile_info[nFile].nUndoSize += nAddSize;
915 [ + - ]: 124786 : m_dirty_fileinfo.insert(nFile);
916 : :
917 : 124786 : bool out_of_space;
918 [ + - ]: 124786 : size_t bytes_allocated = m_undo_file_seq.Allocate(pos, nAddSize, out_of_space);
919 [ - + ]: 124786 : if (out_of_space) {
920 [ # # # # ]: 0 : return FatalError(m_opts.notifications, state, _("Disk space is too low!"));
921 : : }
922 [ + + + + ]: 124786 : if (bytes_allocated != 0 && IsPruneMode()) {
923 : 100 : m_check_for_pruning = true;
924 : : }
925 : :
926 : : return true;
927 : 124786 : }
928 : :
929 : 131103 : bool BlockManager::WriteBlockUndo(const CBlockUndo& blockundo, BlockValidationState& state, CBlockIndex& block)
930 : : {
931 : 131103 : AssertLockHeld(::cs_main);
932 : 131103 : const BlockfileType type = BlockfileTypeForHeight(block.nHeight);
933 [ + + + - ]: 262206 : auto& cursor = *Assert(WITH_LOCK(cs_LastBlockFile, return m_blockfile_cursors[type]));
934 : :
935 : : // Write undo information to disk
936 [ + + ]: 131103 : if (block.GetUndoPos().IsNull()) {
937 : 124786 : FlatFilePos pos;
938 : 124786 : const auto blockundo_size{static_cast<uint32_t>(GetSerializeSize(blockundo))};
939 [ - + ]: 124786 : if (!FindUndoPos(state, block.nFile, pos, blockundo_size + UNDO_DATA_DISK_OVERHEAD)) {
940 [ # # ]: 0 : LogError("FindUndoPos failed for %s while writing block undo", pos.ToString());
941 : 0 : return false;
942 : : }
943 : :
944 : 124786 : {
945 : : // Open history file to append
946 : 124786 : AutoFile file{OpenUndoFile(pos)};
947 [ - + ]: 124786 : if (file.IsNull()) {
948 [ # # # # ]: 0 : LogError("OpenUndoFile failed for %s while writing block undo", pos.ToString());
949 [ # # # # ]: 0 : return FatalError(m_opts.notifications, state, _("Failed to write undo data."));
950 : : }
951 [ + - ]: 124786 : BufferedWriter fileout{file};
952 : :
953 : : // Write index header
954 [ + - + - ]: 124786 : fileout << GetParams().MessageStart() << blockundo_size;
955 : 124786 : pos.nPos += STORAGE_HEADER_BYTES;
956 : 124786 : {
957 : : // Calculate checksum
958 [ + - ]: 124786 : HashWriter hasher{};
959 [ + - + - ]: 124786 : hasher << block.pprev->GetBlockHash() << blockundo;
960 : : // Write undo data & checksum
961 [ + - + - ]: 124786 : fileout << blockundo << hasher.GetHash();
962 : : }
963 : :
964 [ + - ]: 124786 : fileout.flush(); // Make sure `AutoFile`/`BufferedWriter` go out of scope before we call `FlushUndoFile`
965 : 124786 : }
966 : :
967 : : // rev files are written in block height order, whereas blk files are written as blocks come in (often out of order)
968 : : // we want to flush the rev (undo) file once we've written the last block, which is indicated by the last height
969 : : // in the block file info as below; note that this does not catch the case where the undo writes are keeping up
970 : : // with the block writes (usually when a synced up node is getting newly mined blocks) -- this case is caught in
971 : : // the FindNextBlockPos function
972 [ + + + + ]: 124786 : if (pos.nFile < cursor.file_num && static_cast<uint32_t>(block.nHeight) == m_blockfile_info[pos.nFile].nHeightLast) {
973 : : // Do not propagate the return code, a failed flush here should not
974 : : // be an indication for a failed write. If it were propagated here,
975 : : // the caller would assume the undo data not to be written, when in
976 : : // fact it is. Note though, that a failed flush might leave the data
977 : : // file untrimmed.
978 [ - + ]: 1 : if (!FlushUndoFile(pos.nFile, true)) {
979 [ # # ]: 0 : LogPrintLevel(BCLog::BLOCKSTORAGE, BCLog::Level::Warning, "Failed to flush undo file %05i\n", pos.nFile);
980 : : }
981 [ + + + + ]: 124785 : } else if (pos.nFile == cursor.file_num && block.nHeight > cursor.undo_height) {
982 : 115310 : cursor.undo_height = block.nHeight;
983 : : }
984 : : // update nUndoPos in block index
985 : 124786 : block.nUndoPos = pos.nPos;
986 : 124786 : block.nStatus |= BLOCK_HAVE_UNDO;
987 : 124786 : m_dirty_blockindex.insert(&block);
988 : : }
989 : :
990 : : return true;
991 : : }
992 : :
993 : 126061 : bool BlockManager::ReadBlock(CBlock& block, const FlatFilePos& pos, const std::optional<uint256>& expected_hash) const
994 : : {
995 : 126061 : block.SetNull();
996 : :
997 : : // Open history file to read
998 : 126061 : std::vector<uint8_t> block_data;
999 [ + - + + ]: 126061 : if (!ReadRawBlock(block_data, pos)) {
1000 : : return false;
1001 : : }
1002 : :
1003 : 125955 : try {
1004 : : // Read block
1005 [ + - ]: 125955 : SpanReader{block_data} >> TX_WITH_WITNESS(block);
1006 [ - - ]: 0 : } catch (const std::exception& e) {
1007 [ - - - - ]: 0 : LogError("Deserialize or I/O error - %s at %s while reading block", e.what(), pos.ToString());
1008 : 0 : return false;
1009 : 0 : }
1010 : :
1011 [ + - ]: 125955 : const auto block_hash{block.GetHash()};
1012 : :
1013 : : // Check the header
1014 [ + - + + ]: 125955 : if (!CheckProofOfWork(block_hash, block.nBits, GetConsensus())) {
1015 [ + - + - ]: 3 : LogError("Errors in block header at %s while reading block", pos.ToString());
1016 : 3 : return false;
1017 : : }
1018 : :
1019 : : // Signet only: check block solution
1020 [ + + + - : 125952 : if (GetConsensus().signet_blocks && !CheckSignetBlockSolution(block, GetConsensus())) {
- + ]
1021 [ # # # # ]: 0 : LogError("Errors in block solution at %s while reading block", pos.ToString());
1022 : 0 : return false;
1023 : : }
1024 : :
1025 [ + + + + ]: 125952 : if (expected_hash && block_hash != *expected_hash) {
1026 [ + - + - : 2 : LogError("GetHash() doesn't match index at %s while reading block (%s != %s)",
+ - + - ]
1027 : : pos.ToString(), block_hash.ToString(), expected_hash->ToString());
1028 : 1 : return false;
1029 : : }
1030 : :
1031 : : return true;
1032 : 126061 : }
1033 : :
1034 : 120208 : bool BlockManager::ReadBlock(CBlock& block, const CBlockIndex& index) const
1035 : : {
1036 [ + - ]: 240416 : const FlatFilePos block_pos{WITH_LOCK(cs_main, return index.GetBlockPos())};
1037 : 120208 : return ReadBlock(block, block_pos, index.GetBlockHash());
1038 : : }
1039 : :
1040 : 165385 : bool BlockManager::ReadRawBlock(std::vector<uint8_t>& block, const FlatFilePos& pos) const
1041 : : {
1042 [ + + ]: 165385 : if (pos.nPos < STORAGE_HEADER_BYTES) {
1043 : : // If nPos is less than STORAGE_HEADER_BYTES, we can't read the header that precedes the block data
1044 : : // This would cause an unsigned integer underflow when trying to position the file cursor
1045 : : // This can happen after pruning or default constructed positions
1046 [ + - ]: 103 : LogError("Failed for %s while reading raw block storage header", pos.ToString());
1047 : 103 : return false;
1048 : : }
1049 : 165282 : AutoFile filein{OpenBlockFile({pos.nFile, pos.nPos - STORAGE_HEADER_BYTES}, /*fReadOnly=*/true)};
1050 [ + + ]: 165282 : if (filein.IsNull()) {
1051 [ + - + - ]: 4 : LogError("OpenBlockFile failed for %s while reading raw block", pos.ToString());
1052 : 4 : return false;
1053 : : }
1054 : :
1055 : 165278 : try {
1056 : 165278 : MessageStartChars blk_start;
1057 : 165278 : unsigned int blk_size;
1058 : :
1059 [ + - + - ]: 165278 : filein >> blk_start >> blk_size;
1060 : :
1061 [ + + ]: 165278 : if (blk_start != GetParams().MessageStart()) {
1062 [ + - + - : 2 : LogError("Block magic mismatch for %s: %s versus expected %s while reading raw block",
+ - + - ]
1063 : : pos.ToString(), HexStr(blk_start), HexStr(GetParams().MessageStart()));
1064 : 1 : return false;
1065 : : }
1066 : :
1067 [ - + ]: 165277 : if (blk_size > MAX_SIZE) {
1068 [ # # # # ]: 0 : LogError("Block data is larger than maximum deserialization size for %s: %s versus %s while reading raw block",
1069 : : pos.ToString(), blk_size, MAX_SIZE);
1070 : 0 : return false;
1071 : : }
1072 : :
1073 [ + - ]: 165277 : block.resize(blk_size); // Zeroing of memory is intentional here
1074 [ + - ]: 165277 : filein.read(MakeWritableByteSpan(block));
1075 [ - - ]: 0 : } catch (const std::exception& e) {
1076 [ - - - - ]: 0 : LogError("Read from block file failed: %s for %s while reading raw block", e.what(), pos.ToString());
1077 : 0 : return false;
1078 : 0 : }
1079 : :
1080 : : return true;
1081 : 165282 : }
1082 : :
1083 : 126037 : FlatFilePos BlockManager::WriteBlock(const CBlock& block, int nHeight)
1084 : : {
1085 : 126037 : const unsigned int block_size{static_cast<unsigned int>(GetSerializeSize(TX_WITH_WITNESS(block)))};
1086 : 126037 : FlatFilePos pos{FindNextBlockPos(block_size + STORAGE_HEADER_BYTES, nHeight, block.GetBlockTime())};
1087 [ - + ]: 126037 : if (pos.IsNull()) {
1088 [ # # ]: 0 : LogError("FindNextBlockPos failed for %s while writing block", pos.ToString());
1089 : 0 : return FlatFilePos();
1090 : : }
1091 : 126037 : AutoFile file{OpenBlockFile(pos, /*fReadOnly=*/false)};
1092 [ - + ]: 126037 : if (file.IsNull()) {
1093 [ # # # # ]: 0 : LogError("OpenBlockFile failed for %s while writing block", pos.ToString());
1094 [ # # # # ]: 0 : m_opts.notifications.fatalError(_("Failed to write block."));
1095 : 0 : return FlatFilePos();
1096 : : }
1097 [ + - ]: 126037 : BufferedWriter fileout{file};
1098 : :
1099 : : // Write index header
1100 [ + - + - ]: 126037 : fileout << GetParams().MessageStart() << block_size;
1101 : 126037 : pos.nPos += STORAGE_HEADER_BYTES;
1102 : : // Write block
1103 [ + - ]: 126037 : fileout << TX_WITH_WITNESS(block);
1104 : 126037 : return pos;
1105 : 252074 : }
1106 : :
1107 : 1142 : static auto InitBlocksdirXorKey(const BlockManager::Options& opts)
1108 : : {
1109 : : // Bytes are serialized without length indicator, so this is also the exact
1110 : : // size of the XOR-key file.
1111 : 1142 : std::array<std::byte, 8> xor_key{};
1112 : :
1113 : : // Consider this to be the first run if the blocksdir contains only hidden
1114 : : // files (those which start with a .). Checking for a fully-empty dir would
1115 : : // be too aggressive as a .lock file may have already been written.
1116 : 1142 : bool first_run = true;
1117 [ + + + + : 4994 : for (const auto& entry : fs::directory_iterator(opts.blocks_dir)) {
+ + + + +
+ ]
1118 [ + - + - ]: 3852 : const std::string path = fs::PathToString(entry.path().filename());
1119 [ + - + - ]: 1234 : if (!entry.is_regular_file() || !path.starts_with('.')) {
1120 : 692 : first_run = false;
1121 : 692 : break;
1122 : : }
1123 [ + - + + : 2105 : }
+ + - - ]
1124 : :
1125 [ + + + + ]: 1142 : if (opts.use_xor && first_run) {
1126 : : // Only use random fresh key when the boolean option is set and on the
1127 : : // very first start of the program.
1128 : 450 : FastRandomContext{}.fillrand(xor_key);
1129 : : }
1130 : :
1131 [ + - ]: 2284 : const fs::path xor_key_path{opts.blocks_dir / "xor.dat"};
1132 [ + - + + ]: 1142 : if (fs::exists(xor_key_path)) {
1133 : : // A pre-existing xor key file has priority.
1134 [ + - + - ]: 690 : AutoFile xor_key_file{fsbridge::fopen(xor_key_path, "rb")};
1135 [ + - ]: 1380 : xor_key_file >> xor_key;
1136 : 690 : } else {
1137 : : // Create initial or missing xor key file
1138 : 452 : AutoFile xor_key_file{fsbridge::fopen(xor_key_path,
1139 : : #ifdef __MINGW64__
1140 : : "wb" // Temporary workaround for https://github.com/bitcoin/bitcoin/issues/30210
1141 : : #else
1142 : : "wbx"
1143 : : #endif
1144 [ + - + - ]: 452 : )};
1145 [ + - ]: 904 : xor_key_file << xor_key;
1146 : 452 : }
1147 : : // If the user disabled the key, it must be zero.
1148 [ + + + + ]: 1144 : if (!opts.use_xor && xor_key != decltype(xor_key){}) {
1149 : 1 : throw std::runtime_error{
1150 [ + - ]: 2 : strprintf("The blocksdir XOR-key can not be disabled when a random key was already stored! "
1151 : : "Stored key: '%s', stored path: '%s'.",
1152 [ + - ]: 2 : HexStr(xor_key), fs::PathToString(xor_key_path)),
1153 [ + - + - ]: 3 : };
1154 : : }
1155 [ + - + - : 3423 : LogInfo("Using obfuscation key for blocksdir *.dat files (%s): '%s'\n", fs::PathToString(opts.blocks_dir), HexStr(xor_key));
+ - ]
1156 [ + - ]: 1141 : return std::vector<std::byte>{xor_key.begin(), xor_key.end()};
1157 : 1141 : }
1158 : :
1159 : 1142 : BlockManager::BlockManager(const util::SignalInterrupt& interrupt, Options opts)
1160 : 1142 : : m_prune_mode{opts.prune_target > 0},
1161 [ + + ]: 1143 : m_xor_key{InitBlocksdirXorKey(opts)},
1162 [ + - ]: 1141 : m_opts{std::move(opts)},
1163 [ + - + + : 2251 : m_block_file_seq{FlatFileSeq{m_opts.blocks_dir, "blk", m_opts.fast_prune ? 0x4000 /* 16kB */ : BLOCKFILE_CHUNK_SIZE}},
+ - ]
1164 [ + - + - ]: 1142 : m_undo_file_seq{FlatFileSeq{m_opts.blocks_dir, "rev", UNDOFILE_CHUNK_SIZE}},
1165 [ + + + - : 2283 : m_interrupt{interrupt}
+ + ]
1166 : : {
1167 [ + + ]: 1141 : m_block_tree_db = std::make_unique<BlockTreeDB>(m_opts.block_tree_db_params);
1168 : :
1169 [ + + ]: 1140 : if (m_opts.block_tree_db_params.wipe_data) {
1170 [ + - ]: 18 : m_block_tree_db->WriteReindexing(true);
1171 [ + + ]: 18 : m_blockfiles_indexed = false;
1172 : : // If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1173 [ + + ]: 18 : if (m_prune_mode) {
1174 [ + - ]: 5 : CleanupBlockRevFiles();
1175 : : }
1176 : : }
1177 : 1147 : }
1178 : :
1179 : : class ImportingNow
1180 : : {
1181 : : std::atomic<bool>& m_importing;
1182 : :
1183 : : public:
1184 : 932 : ImportingNow(std::atomic<bool>& importing) : m_importing{importing}
1185 : : {
1186 [ - + ]: 932 : assert(m_importing == false);
1187 : 932 : m_importing = true;
1188 : 932 : }
1189 : 932 : ~ImportingNow()
1190 : : {
1191 [ - + ]: 932 : assert(m_importing == true);
1192 : 932 : m_importing = false;
1193 : 932 : }
1194 : : };
1195 : :
1196 : 932 : void ImportBlocks(ChainstateManager& chainman, std::span<const fs::path> import_paths)
1197 : : {
1198 : 932 : ImportingNow imp{chainman.m_blockman.m_importing};
1199 : :
1200 : : // -reindex
1201 [ + + ]: 932 : if (!chainman.m_blockman.m_blockfiles_indexed) {
1202 : 19 : int nFile = 0;
1203 : : // Map of disk positions for blocks with unknown parent (only used for reindex);
1204 : : // parent hash -> child disk position, multiple children can have the same parent.
1205 : 19 : std::multimap<uint256, FlatFilePos> blocks_with_unknown_parent;
1206 : 47 : while (true) {
1207 [ + - ]: 33 : FlatFilePos pos(nFile, 0);
1208 [ + - + + ]: 99 : if (!fs::exists(chainman.m_blockman.GetBlockPosFilename(pos))) {
1209 : : break; // No block files left to reindex
1210 : : }
1211 [ + - ]: 16 : AutoFile file{chainman.m_blockman.OpenBlockFile(pos, /*fReadOnly=*/true)};
1212 [ + - ]: 16 : if (file.IsNull()) {
1213 : : break; // This error is logged in OpenBlockFile
1214 : : }
1215 [ + - ]: 16 : LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
1216 [ + - ]: 16 : chainman.LoadExternalBlockFile(file, &pos, &blocks_with_unknown_parent);
1217 [ + - + + ]: 16 : if (chainman.m_interrupt) {
1218 [ + - ]: 2 : LogPrintf("Interrupt requested. Exit %s\n", __func__);
1219 : 2 : return;
1220 : : }
1221 : 14 : nFile++;
1222 : 16 : }
1223 [ + - + - ]: 51 : WITH_LOCK(::cs_main, chainman.m_blockman.m_block_tree_db->WriteReindexing(false));
1224 [ + - ]: 17 : chainman.m_blockman.m_blockfiles_indexed = true;
1225 [ + - ]: 17 : LogPrintf("Reindexing finished\n");
1226 : : // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
1227 [ + - + - ]: 17 : chainman.ActiveChainstate().LoadGenesisBlock();
1228 : 19 : }
1229 : :
1230 : : // -loadblock=
1231 [ + + ]: 931 : for (const fs::path& path : import_paths) {
1232 [ + - + - ]: 1 : AutoFile file{fsbridge::fopen(path, "rb")};
1233 [ + - ]: 1 : if (!file.IsNull()) {
1234 [ + - + - ]: 2 : LogPrintf("Importing blocks file %s...\n", fs::PathToString(path));
1235 [ + - ]: 1 : chainman.LoadExternalBlockFile(file);
1236 [ + - - + ]: 1 : if (chainman.m_interrupt) {
1237 [ # # ]: 0 : LogPrintf("Interrupt requested. Exit %s\n", __func__);
1238 : 0 : return;
1239 : : }
1240 : : } else {
1241 [ # # # # ]: 0 : LogPrintf("Warning: Could not open blocks file %s\n", fs::PathToString(path));
1242 : : }
1243 : 1 : }
1244 : :
1245 : : // scan for better chains in the block chain database, that are not yet connected in the active best chain
1246 : :
1247 : : // We can't hold cs_main during ActivateBestChain even though we're accessing
1248 : : // the chainman unique_ptrs since ABC requires us not to be holding cs_main, so retrieve
1249 : : // the relevant pointers before the ABC call.
1250 [ + - + + : 3725 : for (Chainstate* chainstate : WITH_LOCK(::cs_main, return chainman.GetAll())) {
+ - ]
1251 [ + - ]: 935 : BlockValidationState state;
1252 [ + - - + : 935 : if (!chainstate->ActivateBestChain(state, nullptr)) {
- + ]
1253 [ # # # # : 0 : chainman.GetNotifications().fatalError(strprintf(_("Failed to connect best block (%s)."), state.ToString()));
# # ]
1254 : 0 : return;
1255 : : }
1256 : 935 : }
1257 : : // End scope of ImportingNow
1258 : 932 : }
1259 : :
1260 : 11 : std::ostream& operator<<(std::ostream& os, const BlockfileType& type) {
1261 [ - + - ]: 11 : switch(type) {
1262 : 0 : case BlockfileType::NORMAL: os << "normal"; break;
1263 : 11 : case BlockfileType::ASSUMED: os << "assumed"; break;
1264 : 0 : default: os.setstate(std::ios_base::failbit);
1265 : : }
1266 : 11 : return os;
1267 : : }
1268 : :
1269 : 11 : std::ostream& operator<<(std::ostream& os, const BlockfileCursor& cursor) {
1270 [ + - ]: 11 : os << strprintf("BlockfileCursor(file_num=%d, undo_height=%d)", cursor.file_num, cursor.undo_height);
1271 : 11 : return os;
1272 : : }
1273 : : } // namespace node
|