LCOV - code coverage report
Current view: top level - src/node - blockstorage.cpp (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 242 723 33.5 %
Date: 2023-11-10 23:46:46 Functions: 29 65 44.6 %
Branches: 152 1114 13.6 %

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

Generated by: LCOV version 1.14