LCOV - code coverage report
Current view: top level - src/node - blockstorage.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 48.4 % 674 326
Test Date: 2025-07-10 04:10:27 Functions: 63.3 % 60 38
Branches: 24.4 % 1025 250

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

Generated by: LCOV version 2.0-1