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-11-01 04:07:19 Functions: 63.3 % 60 38
Branches: 24.4 % 1041 254

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

Generated by: LCOV version 2.0-1