LCOV - code coverage report
Current view: top level - src/node - blockstorage.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 90.8 % 683 620
Test Date: 2026-06-09 07:27:18 Functions: 100.0 % 58 58
Branches: 61.4 % 955 586

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

Generated by: LCOV version 2.0-1