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