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