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