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