LCOV - code coverage report
Current view: top level - src/node - blockstorage.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 69.4 % 677 470
Test Date: 2025-11-13 04:35:55 Functions: 85.2 % 61 52
Branches: 39.0 % 1047 408

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

Generated by: LCOV version 2.0-1