LCOV - code coverage report
Current view: top level - src - validation.cpp (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 2032 2265 89.7 %
Date: 2000-01-01 12:00:00 Functions: 137 140 97.9 %
Branches: 3370 7022 48.0 %

           Branch data     Line data    Source code
       1                 :            : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2                 :            : // Copyright (c) 2009-2018 The Bitcoin Core developers
       3                 :            : // Distributed under the MIT software license, see the accompanying
       4                 :            : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       5                 :            : 
       6                 :            : #include <validation.h>
       7                 :            : 
       8                 :            : #include <arith_uint256.h>
       9                 :            : #include <chain.h>
      10                 :            : #include <chainparams.h>
      11                 :            : #include <checkqueue.h>
      12                 :            : #include <consensus/consensus.h>
      13                 :            : #include <consensus/merkle.h>
      14                 :            : #include <consensus/tx_check.h>
      15                 :            : #include <consensus/tx_verify.h>
      16                 :            : #include <consensus/validation.h>
      17                 :            : #include <cuckoocache.h>
      18                 :            : #include <flatfile.h>
      19                 :            : #include <hash.h>
      20                 :            : #include <index/txindex.h>
      21                 :            : #include <policy/fees.h>
      22                 :            : #include <policy/policy.h>
      23                 :            : #include <policy/settings.h>
      24                 :            : #include <pow.h>
      25                 :            : #include <primitives/block.h>
      26                 :            : #include <primitives/transaction.h>
      27                 :            : #include <random.h>
      28                 :            : #include <reverse_iterator.h>
      29                 :            : #include <script/script.h>
      30                 :            : #include <script/sigcache.h>
      31                 :            : #include <script/standard.h>
      32                 :            : #include <shutdown.h>
      33                 :            : #include <timedata.h>
      34                 :            : #include <tinyformat.h>
      35                 :            : #include <txdb.h>
      36                 :            : #include <txmempool.h>
      37                 :            : #include <ui_interface.h>
      38                 :            : #include <uint256.h>
      39                 :            : #include <undo.h>
      40                 :            : #include <util/moneystr.h>
      41                 :            : #include <util/rbf.h>
      42                 :            : #include <util/strencodings.h>
      43                 :            : #include <util/system.h>
      44                 :            : #include <util/translation.h>
      45                 :            : #include <util/validation.h>
      46                 :            : #include <validationinterface.h>
      47                 :            : #include <warnings.h>
      48                 :            : 
      49                 :            : #include <future>
      50                 :            : #include <sstream>
      51                 :            : #include <string>
      52                 :            : 
      53                 :            : #include <boost/algorithm/string/replace.hpp>
      54                 :            : #include <boost/thread.hpp>
      55                 :            : 
      56                 :            : #if defined(NDEBUG)
      57                 :            : # error "Bitcoin cannot be compiled without assertions."
      58                 :            : #endif
      59                 :            : 
      60                 :            : #define MICRO 0.000001
      61                 :            : #define MILLI 0.001
      62                 :            : 
      63                 :  161476685 : bool CBlockIndexWorkComparator::operator()(const CBlockIndex *pa, const CBlockIndex *pb) const {
      64                 :            :     // First sort by most total work, ...
      65         [ +  + ]:  161476685 :     if (pa->nChainWork > pb->nChainWork) return false;
      66         [ +  + ]:  102837363 :     if (pa->nChainWork < pb->nChainWork) return true;
      67                 :            : 
      68                 :            :     // ... then by earliest time received, ...
      69         [ +  + ]:     799443 :     if (pa->nSequenceId < pb->nSequenceId) return false;
      70         [ +  + ]:     789584 :     if (pa->nSequenceId > pb->nSequenceId) return true;
      71                 :            : 
      72                 :            :     // Use pointer address as tie breaker (should only happen with blocks
      73                 :            :     // loaded from disk, as those all have id 0).
      74         [ +  + ]:     780678 :     if (pa < pb) return false;
      75         [ +  + ]:     780673 :     if (pa > pb) return true;
      76                 :            : 
      77                 :            :     // Identical blocks.
      78                 :            :     return false;
      79                 :            : }
      80                 :            : 
      81                 :            : namespace {
      82                 :            : BlockManager g_blockman;
      83                 :            : } // anon namespace
      84                 :            : 
      85                 :            : static CChainState g_chainstate(g_blockman);
      86                 :            : 
      87                 :     610391 : CChainState& ChainstateActive() { return g_chainstate; }
      88                 :            : 
      89                 :    4139141 : CChain& ChainActive() { return g_chainstate.m_chain; }
      90                 :            : 
      91                 :            : /**
      92                 :            :  * Mutex to guard access to validation specific variables, such as reading
      93                 :            :  * or changing the chainstate.
      94                 :            :  *
      95                 :            :  * This may also need to be locked when updating the transaction pool, e.g. on
      96                 :            :  * AcceptToMemoryPool. See CTxMemPool::cs comment for details.
      97                 :            :  *
      98                 :            :  * The transaction pool has a separate lock to allow reading from it and the
      99                 :            :  * chainstate at the same time.
     100                 :            :  */
     101                 :            : RecursiveMutex cs_main;
     102                 :            : 
     103                 :            : CBlockIndex *pindexBestHeader = nullptr;
     104                 :            : Mutex g_best_block_mutex;
     105                 :            : std::condition_variable g_best_block_cv;
     106                 :            : uint256 g_best_block;
     107                 :            : int nScriptCheckThreads = 0;
     108                 :            : std::atomic_bool fImporting(false);
     109                 :            : std::atomic_bool fReindex(false);
     110                 :            : bool fHavePruned = false;
     111                 :            : bool fPruneMode = false;
     112                 :            : bool fRequireStandard = true;
     113                 :            : bool fCheckBlockIndex = false;
     114                 :            : bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
     115                 :            : size_t nCoinCacheUsage = 5000 * 300;
     116                 :            : uint64_t nPruneTarget = 0;
     117                 :            : int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
     118                 :            : 
     119                 :            : uint256 hashAssumeValid;
     120                 :            : arith_uint256 nMinimumChainWork;
     121                 :            : 
     122                 :            : CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
     123                 :            : 
     124                 :            : CBlockPolicyEstimator feeEstimator;
     125                 :            : CTxMemPool mempool(&feeEstimator);
     126                 :            : 
     127                 :            : /** Constant stuff for coinbase transactions we create: */
     128                 :            : CScript COINBASE_FLAGS;
     129                 :            : 
     130                 :            : // Internal stuff
     131                 :            : namespace {
     132                 :            :     CBlockIndex* pindexBestInvalid = nullptr;
     133                 :            : 
     134                 :            :     CCriticalSection cs_LastBlockFile;
     135                 :            :     std::vector<CBlockFileInfo> vinfoBlockFile;
     136                 :            :     int nLastBlockFile = 0;
     137                 :            :     /** Global flag to indicate we should check to see if there are
     138                 :            :      *  block/undo files that should be deleted.  Set on startup
     139                 :            :      *  or if we allocate more file space when we're in prune mode
     140                 :            :      */
     141                 :            :     bool fCheckForPruning = false;
     142                 :            : 
     143                 :            :     /** Dirty block index entries. */
     144                 :            :     std::set<CBlockIndex*> setDirtyBlockIndex;
     145                 :            : 
     146                 :            :     /** Dirty block file entries. */
     147                 :            :     std::set<int> setDirtyFileInfo;
     148                 :            : } // anon namespace
     149                 :            : 
     150                 :    1258998 : CBlockIndex* LookupBlockIndex(const uint256& hash)
     151                 :            : {
     152                 :    1258998 :     AssertLockHeld(cs_main);
     153         [ +  + ]:    1258998 :     BlockMap::const_iterator it = g_blockman.m_block_index.find(hash);
     154   [ +  +  +  + ]:    2517996 :     return it == g_blockman.m_block_index.end() ? nullptr : it->second;
     155                 :            : }
     156                 :            : 
     157                 :       1617 : CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
     158                 :            : {
     159                 :       1617 :     AssertLockHeld(cs_main);
     160                 :            : 
     161                 :            :     // Find the latest block common to locator and chain - we expect that
     162                 :            :     // locator.vHave is sorted descending by height.
     163 [ +  + ][ +  + ]:       5221 :     for (const uint256& hash : locator.vHave) {
     164                 :       1838 :         CBlockIndex* pindex = LookupBlockIndex(hash);
     165         [ +  + ]:       1838 :         if (pindex) {
     166 [ +  - ][ +  + ]:       3240 :             if (chain.Contains(pindex))
     167                 :            :                 return pindex;
     168 [ +  + ][ +  + ]:        484 :             if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
     169                 :            :                 return chain.Tip();
     170                 :            :             }
     171                 :            :         }
     172                 :            :     }
     173         [ +  + ]:        149 :     return chain.Genesis();
     174                 :            : }
     175                 :            : 
     176                 :            : std::unique_ptr<CCoinsViewDB> pcoinsdbview;
     177                 :            : std::unique_ptr<CCoinsViewCache> pcoinsTip;
     178                 :            : std::unique_ptr<CBlockTreeDB> pblocktree;
     179                 :            : 
     180                 :            : // See definition for documentation
     181                 :            : static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight);
     182                 :            : static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight);
     183                 :            : bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks = nullptr);
     184                 :            : static FILE* OpenUndoFile(const FlatFilePos &pos, bool fReadOnly = false);
     185                 :            : static FlatFileSeq BlockFileSeq();
     186                 :            : static FlatFileSeq UndoFileSeq();
     187                 :            : 
     188                 :     315216 : bool CheckFinalTx(const CTransaction &tx, int flags)
     189                 :            : {
     190                 :     315216 :     AssertLockHeld(cs_main);
     191                 :            : 
     192                 :            :     // By convention a negative value for flags indicates that the
     193                 :            :     // current network-enforced consensus rules should be used. In
     194                 :            :     // a future soft-fork scenario that would mean checking which
     195                 :            :     // rules would be enforced for the next block and setting the
     196                 :            :     // appropriate flags. At the present time no soft-forks are
     197                 :            :     // scheduled, so no flags are set.
     198         [ +  + ]:     315216 :     flags = std::max(flags, 0);
     199                 :            : 
     200                 :            :     // CheckFinalTx() uses ::ChainActive().Height()+1 to evaluate
     201                 :            :     // nLockTime because when IsFinalTx() is called within
     202                 :            :     // CBlock::AcceptBlock(), the height of the block *being*
     203                 :            :     // evaluated is what is used. Thus if we want to know if a
     204                 :            :     // transaction can be part of the *next* block, we need to call
     205                 :            :     // IsFinalTx() with one more than ::ChainActive().Height().
     206         [ +  + ]:     315216 :     const int nBlockHeight = ::ChainActive().Height() + 1;
     207                 :            : 
     208                 :            :     // BIP113 requires that time-locked transactions have nLockTime set to
     209                 :            :     // less than the median time of the previous block they're contained in.
     210                 :            :     // When the next block is created its previous block will be the current
     211                 :            :     // chain tip, so we use that to calculate the median time passed to
     212                 :            :     // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
     213                 :     315216 :     const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
     214 [ +  + ][ +  - ]:     336170 :                              ? ::ChainActive().Tip()->GetMedianTimePast()
     215                 :     294262 :                              : GetAdjustedTime();
     216                 :            : 
     217                 :     315216 :     return IsFinalTx(tx, nBlockHeight, nBlockTime);
     218                 :            : }
     219                 :            : 
     220                 :        526 : bool TestLockPointValidity(const LockPoints* lp)
     221                 :            : {
     222                 :        526 :     AssertLockHeld(cs_main);
     223         [ -  + ]:        526 :     assert(lp);
     224                 :            :     // If there are relative lock times then the maxInputBlock will be set
     225                 :            :     // If there are no relative lock times, the LockPoints don't depend on the chain
     226         [ +  - ]:        526 :     if (lp->maxInputBlock) {
     227                 :            :         // Check whether ::ChainActive() is an extension of the block at which the LockPoints
     228                 :            :         // calculation was valid.  If not LockPoints are no longer valid
     229 [ +  - ][ +  + ]:       1052 :         if (!::ChainActive().Contains(lp->maxInputBlock)) {
     230                 :          2 :             return false;
     231                 :            :         }
     232                 :            :     }
     233                 :            : 
     234                 :            :     // LockPoints still valid
     235                 :            :     return true;
     236                 :            : }
     237                 :            : 
     238                 :      17460 : bool CheckSequenceLocks(const CTxMemPool& pool, const CTransaction& tx, int flags, LockPoints* lp, bool useExistingLockPoints)
     239                 :            : {
     240                 :      17460 :     AssertLockHeld(cs_main);
     241                 :      17460 :     AssertLockHeld(pool.cs);
     242                 :            : 
     243         [ +  - ]:      17460 :     CBlockIndex* tip = ::ChainActive().Tip();
     244         [ -  + ]:      17460 :     assert(tip != nullptr);
     245                 :            : 
     246                 :      17460 :     CBlockIndex index;
     247                 :      17460 :     index.pprev = tip;
     248                 :            :     // CheckSequenceLocks() uses ::ChainActive().Height()+1 to evaluate
     249                 :            :     // height based locks because when SequenceLocks() is called within
     250                 :            :     // ConnectBlock(), the height of the block *being*
     251                 :            :     // evaluated is what is used.
     252                 :            :     // Thus if we want to know if a transaction can be part of the
     253                 :            :     // *next* block, we need to use one more than ::ChainActive().Height()
     254                 :      17460 :     index.nHeight = tip->nHeight + 1;
     255                 :            : 
     256                 :      17460 :     std::pair<int, int64_t> lockPair;
     257         [ +  + ]:      17460 :     if (useExistingLockPoints) {
     258         [ -  + ]:        522 :         assert(lp);
     259                 :        522 :         lockPair.first = lp->height;
     260                 :        522 :         lockPair.second = lp->time;
     261                 :            :     }
     262                 :            :     else {
     263                 :            :         // pcoinsTip contains the UTXO set for ::ChainActive().Tip()
     264                 :      33876 :         CCoinsViewMemPool viewMemPool(pcoinsTip.get(), pool);
     265 [ +  - ][ #  # ]:      50814 :         std::vector<int> prevheights;
                 [ +  - ]
     266   [ +  -  +  - ]:      33876 :         prevheights.resize(tx.vin.size());
     267 [ +  + ][ +  + ]:      86074 :         for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
     268                 :      26099 :             const CTxIn& txin = tx.vin[txinIndex];
     269 [ +  + ][ #  # ]:      52782 :             Coin coin;
     270 [ -  + ][ +  - ]:      26099 :             if (!viewMemPool.GetCoin(txin.prevout, coin)) {
     271 [ #  # ][ #  # ]:          0 :                 return error("%s: Missing input", __func__);
                 [ #  # ]
     272                 :            :             }
     273         [ +  + ]:      26099 :             if (coin.nHeight == MEMPOOL_HEIGHT) {
     274                 :            :                 // Assume all mempool transaction confirm in the next block
     275                 :       2498 :                 prevheights[txinIndex] = tip->nHeight + 1;
     276                 :            :             } else {
     277                 :      49700 :                 prevheights[txinIndex] = coin.nHeight;
     278                 :            :             }
     279                 :            :         }
     280 [ +  - ][ +  + ]:      16938 :         lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
     281         [ +  + ]:      16938 :         if (lp) {
     282                 :      16930 :             lp->height = lockPair.first;
     283                 :      16930 :             lp->time = lockPair.second;
     284                 :            :             // Also store the hash of the block with the highest height of
     285                 :            :             // all the blocks which have sequence locked prevouts.
     286                 :            :             // This hash needs to still be on the chain
     287                 :            :             // for these LockPoint calculations to be valid
     288                 :            :             // Note: It is impossible to correctly calculate a maxInputBlock
     289                 :            :             // if any of the sequence locked inputs depend on unconfirmed txs,
     290                 :            :             // except in the special case where the relative lock time/height
     291                 :            :             // is 0, which is equivalent to no sequence lock. Since we assume
     292                 :            :             // input height of tip+1 for mempool txs and test the resulting
     293                 :            :             // lockPair from CalculateSequenceLocks against tip+1.  We know
     294                 :            :             // EvaluateSequenceLocks will fail if there was a non-zero sequence
     295                 :            :             // lock on a mempool input, so we can use the return value of
     296                 :            :             // CheckSequenceLocks to indicate the LockPoints validity
     297                 :      16930 :             int maxInputHeight = 0;
     298 [ +  + ][ +  + ]:      76881 :             for (const int height : prevheights) {
     299                 :            :                 // Can ignore mempool inputs since we'll fail if they had non-zero locks
     300         [ +  + ]:      26091 :                 if (height != tip->nHeight+1) {
     301         [ +  + ]:      41198 :                     maxInputHeight = std::max(maxInputHeight, height);
     302                 :            :                 }
     303                 :            :             }
     304         [ +  - ]:      16930 :             lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
     305                 :            :         }
     306                 :            :     }
     307                 :      17460 :     return EvaluateSequenceLocks(index, lockPair);
     308                 :            : }
     309                 :            : 
     310                 :            : // Returns the script flags which should be checked for a given block
     311                 :            : static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& chainparams);
     312                 :            : 
     313                 :      16664 : static void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) EXCLUSIVE_LOCKS_REQUIRED(pool.cs)
     314                 :            : {
     315                 :      16664 :     int expired = pool.Expire(GetTime() - age);
     316         [ -  + ]:      16664 :     if (expired != 0) {
     317                 :          0 :         LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
     318                 :            :     }
     319                 :            : 
     320 [ +  - ][ +  + ]:      33328 :     std::vector<COutPoint> vNoSpendsRemaining;
                 [ #  # ]
     321         [ +  - ]:      16664 :     pool.TrimToSize(limit, &vNoSpendsRemaining);
     322 [ +  + ][ +  + ]:      50018 :     for (const COutPoint& removed : vNoSpendsRemaining)
     323 [ +  - ][ +  - ]:         52 :         pcoinsTip->Uncache(removed);
     324                 :      16664 : }
     325                 :            : 
     326                 :      16109 : static bool IsCurrentForFeeEstimation() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
     327                 :            : {
     328                 :      16109 :     AssertLockHeld(cs_main);
     329         [ +  + ]:      16109 :     if (::ChainstateActive().IsInitialBlockDownload())
     330                 :            :         return false;
     331 [ +  - ][ +  + ]:      48129 :     if (::ChainActive().Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE))
     332                 :            :         return false;
     333 [ +  + ][ +  + ]:      31892 :     if (::ChainActive().Height() < pindexBestHeader->nHeight - 1)
     334                 :          5 :         return false;
     335                 :            :     return true;
     336                 :            : }
     337                 :            : 
     338                 :            : /* Make mempool consistent after a reorg, by re-adding or recursively erasing
     339                 :            :  * disconnected block transactions from the mempool, and also removing any
     340                 :            :  * other transactions from the mempool that are no longer valid given the new
     341                 :            :  * tip/height.
     342                 :            :  *
     343                 :            :  * Note: we assume that disconnectpool only contains transactions that are NOT
     344                 :            :  * confirmed in the current chain nor already in the mempool (otherwise,
     345                 :            :  * in-mempool descendants of such transactions would be removed).
     346                 :            :  *
     347                 :            :  * Passing fAddToMempool=false will skip trying to add the transactions back,
     348                 :            :  * and instead just erase from the mempool as needed.
     349                 :            :  */
     350                 :            : 
     351                 :        471 : static void UpdateMempoolForReorg(DisconnectedBlockTransactions& disconnectpool, bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, ::mempool.cs)
     352                 :            : {
     353                 :        471 :     AssertLockHeld(cs_main);
     354         [ #  # ]:        471 :     std::vector<uint256> vHashUpdate;
     355                 :            :     // disconnectpool's insertion_order index sorts the entries from
     356                 :            :     // oldest to newest, but the oldest entry will be the last tx from the
     357                 :            :     // latest mined block that was disconnected.
     358                 :            :     // Iterate disconnectpool in reverse, so that we add transactions
     359                 :            :     // back to the mempool starting with the earliest transaction that had
     360                 :            :     // been previously seen in a block.
     361                 :        942 :     auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
     362   [ +  +  +  + ]:       6416 :     while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
     363                 :            :         // ignore validation errors in resurrected transactions
     364         [ +  + ]:       5945 :         CValidationState stateDummy;
     365 [ +  + ][ +  - ]:      21074 :         if (!fAddToMempool || (*it)->IsCoinBase() ||
         [ +  + ][ +  + ]
                 [ +  + ]
     366 [ +  - ][ +  - ]:       7762 :             !AcceptToMemoryPool(mempool, stateDummy, *it, nullptr /* pfMissingInputs */,
     367                 :            :                                 nullptr /* plTxnReplaced */, true /* bypass_limits */, 0 /* nAbsurdFee */)) {
     368                 :            :             // If the transaction doesn't make it in to the mempool, remove any
     369                 :            :             // transactions that depend on it (which would now be orphans).
     370 [ +  - ][ +  - ]:      17175 :             mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
                 [ +  - ]
     371 [ +  - ][ +  - ]:        880 :         } else if (mempool.exists((*it)->GetHash())) {
         [ +  - ][ +  - ]
                 [ +  - ]
     372 [ +  - ][ +  - ]:        880 :             vHashUpdate.push_back((*it)->GetHash());
         [ +  - ][ +  - ]
     373                 :            :         }
     374         [ +  - ]:      11890 :         ++it;
     375                 :            :     }
     376                 :        471 :     disconnectpool.queuedTx.clear();
     377                 :            :     // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
     378                 :            :     // no in-mempool children, which is generally not true when adding
     379                 :            :     // previously-confirmed transactions back to the mempool.
     380                 :            :     // UpdateTransactionsFromBlock finds descendants of any transactions in
     381                 :            :     // the disconnectpool that were added back and cleans up the mempool state.
     382         [ +  - ]:        471 :     mempool.UpdateTransactionsFromBlock(vHashUpdate);
     383                 :            : 
     384                 :            :     // We also need to remove any now-immature transactions
     385 [ +  - ][ +  - ]:       1413 :     mempool.removeForReorg(pcoinsTip.get(), ::ChainActive().Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
                 [ +  - ]
     386                 :            :     // Re-limit mempool size, in case we added any transactions
     387 [ +  - ][ +  - ]:        942 :     LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ +  - ][ -  + ]
         [ -  + ][ -  + ]
         [ +  + ][ +  + ]
         [ #  # ][ #  # ]
     388                 :        471 : }
     389                 :            : 
     390                 :            : // Used to avoid mempool polluting consensus critical paths if CCoinsViewMempool
     391                 :            : // were somehow broken and returning the wrong scriptPubKeys
     392                 :      16424 : static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& view, const CTxMemPool& pool,
     393                 :            :                  unsigned int flags, bool cacheSigStore, PrecomputedTransactionData& txdata) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
     394                 :      16424 :     AssertLockHeld(cs_main);
     395                 :            : 
     396                 :            :     // pool.cs should be locked already, but go ahead and re-take the lock here
     397                 :            :     // to enforce that mempool doesn't change between when we check the view
     398                 :            :     // and when we actually call through to CheckInputs
     399 [ +  - ][ #  # ]:      49272 :     LOCK(pool.cs);
     400                 :            : 
     401         [ +  + ]:      16424 :     assert(!tx.IsCoinBase());
     402 [ +  + ][ +  + ]:      96176 :     for (const CTxIn& txin : tx.vin) {
     403         [ +  - ]:      23452 :         const Coin& coin = view.AccessCoin(txin.prevout);
     404                 :            : 
     405                 :            :         // At this point we haven't actually checked if the coins are all
     406                 :            :         // available (or shouldn't assume we have, since CheckInputs does).
     407                 :            :         // So we just return failure if the inputs are not available here,
     408                 :            :         // and then only have to check equivalence for available inputs.
     409 [ +  - ][ +  - ]:      46904 :         if (coin.IsSpent()) return false;
     410                 :            : 
     411 [ +  - ][ +  + ]:      47990 :         const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
                 [ #  # ]
     412 [ +  + ][ +  + ]:      46904 :         if (txFrom) {
     413 [ -  + ][ -  + ]:       4344 :             assert(txFrom->GetHash() == txin.prevout.hash);
         [ -  + ][ -  + ]
     414 [ -  + ][ -  + ]:       3258 :             assert(txFrom->vout.size() > txin.prevout.n);
                 [ -  + ]
     415 [ +  - ][ +  - ]:       3258 :             assert(txFrom->vout[txin.prevout.n] == coin.out);
                 [ +  - ]
     416                 :            :         } else {
     417 [ +  - ][ +  - ]:      44732 :             const Coin& coinFromDisk = pcoinsTip->AccessCoin(txin.prevout);
     418 [ -  + ][ -  + ]:      44732 :             assert(!coinFromDisk.IsSpent());
     419         [ +  - ]:      22366 :             assert(coinFromDisk.out == coin.out);
     420                 :            :         }
     421                 :            :     }
     422                 :            : 
     423         [ +  - ]:      16424 :     return CheckInputs(tx, state, view, true, flags, cacheSigStore, true, txdata);
     424                 :            : }
     425                 :            : 
     426                 :            : /**
     427                 :            :  * @param[out] coins_to_uncache   Return any outpoints which were not previously present in the
     428                 :            :  *                                coins cache, but were added as a result of validating the tx
     429                 :            :  *                                for mempool acceptance. This allows the caller to optionally
     430                 :            :  *                                remove the cache additions if the associated transaction ends
     431                 :            :  *                                up being rejected by the mempool.
     432                 :            :  */
     433                 :      20736 : static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx,
     434                 :            :                               bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
     435                 :            :                               bool bypass_limits, const CAmount& nAbsurdFee, std::vector<COutPoint>& coins_to_uncache, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
     436                 :            : {
     437                 :      20736 :     const CTransaction& tx = *ptx;
     438                 :      20736 :     const uint256 hash = tx.GetHash();
     439                 :      20736 :     AssertLockHeld(cs_main);
     440 [ +  - ][ #  # ]:      62208 :     LOCK(pool.cs); // mempool "read lock" (held through GetMainSignals().TransactionAddedToMempool())
     441         [ +  + ]:      20736 :     if (pfMissingInputs) {
     442                 :      16810 :         *pfMissingInputs = false;
     443                 :            :     }
     444                 :            : 
     445 [ +  - ][ +  + ]:      20736 :     if (!CheckTransaction(tx, state))
     446                 :            :         return false; // state filled in by CheckTransaction
     447                 :            : 
     448                 :            :     // Coinbase is only valid in a block, not as a loose transaction
     449         [ +  + ]:      20726 :     if (tx.IsCoinBase())
     450 [ +  - ][ +  - ]:         81 :         return state.Invalid(ValidationInvalidReason::CONSENSUS, false, REJECT_INVALID, "coinbase");
         [ +  - ][ +  - ]
         [ +  - ][ -  + ]
         [ -  + ][ -  + ]
         [ #  # ][ #  # ]
                 [ #  # ]
     451                 :            : 
     452                 :            :     // Rather not work on nonstandard transactions (unless -testnet/-regtest)
     453 [ +  + ][ +  + ]:      41398 :     std::string reason;
                 [ #  # ]
     454 [ +  + ][ +  - ]:      20699 :     if (fRequireStandard && !IsStandardTx(tx, reason))
                 [ +  + ]
     455 [ +  - ][ +  - ]:        810 :         return state.Invalid(ValidationInvalidReason::TX_NOT_STANDARD, false, REJECT_NONSTANDARD, reason);
         [ +  - ][ -  + ]
                 [ #  # ]
     456                 :            : 
     457                 :            :     // Do not work on transactions that are too small.
     458                 :            :     // A transaction with 1 segwit input and 1 P2WPHK output has non-witness size of 82 bytes.
     459                 :            :     // Transactions smaller than this are not relayed to reduce unnecessary malloc overhead.
     460         [ +  + ]:      20429 :     if (::GetSerializeSize(tx, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) < MIN_STANDARD_TX_NONWITNESS_SIZE)
     461 [ +  - ][ +  - ]:         18 :         return state.Invalid(ValidationInvalidReason::TX_NOT_STANDARD, false, REJECT_NONSTANDARD, "tx-size-small");
         [ +  - ][ +  - ]
         [ +  - ][ -  + ]
         [ -  + ][ -  + ]
         [ #  # ][ #  # ]
                 [ #  # ]
     462                 :            : 
     463                 :            :     // Only accept nLockTime-using transactions that can be mined in the next
     464                 :            :     // block; we don't want our mempool filled up with transactions that can't
     465                 :            :     // be mined yet.
     466 [ +  - ][ +  + ]:      20423 :     if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
     467 [ +  - ][ +  - ]:        114 :         return state.Invalid(ValidationInvalidReason::TX_PREMATURE_SPEND, false, REJECT_NONSTANDARD, "non-final");
         [ +  - ][ +  - ]
         [ +  - ][ -  + ]
         [ -  + ][ -  + ]
         [ #  # ][ #  # ]
                 [ #  # ]
     468                 :            : 
     469                 :            :     // is it already in the memory pool?
     470 [ +  - ][ +  + ]:      20385 :     if (pool.exists(hash)) {
     471 [ +  - ][ +  - ]:          5 :         return state.Invalid(ValidationInvalidReason::TX_CONFLICT, false, REJECT_DUPLICATE, "txn-already-in-mempool");
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ -  + ][ -  + ]
         [ #  # ][ #  # ]
                 [ #  # ]
     472                 :            :     }
     473                 :            : 
     474                 :            :     // Check for conflicts with in-memory transactions
     475                 :      40768 :     std::set<uint256> setConflicts;
     476 [ +  + ][ +  + ]:      94035 :     for (const CTxIn &txin : tx.vin)
     477                 :            :     {
     478         [ +  - ]:      32886 :         const CTransaction* ptxConflicting = pool.GetConflictTx(txin.prevout);
     479         [ +  + ]:      32886 :         if (ptxConflicting) {
     480                 :        618 :             if (!setConflicts.count(ptxConflicting->GetHash()))
     481                 :            :             {
     482                 :            :                 // Allow opt-out of transaction replacement by setting
     483                 :            :                 // nSequence > MAX_BIP125_RBF_SEQUENCE (SEQUENCE_FINAL-2) on all inputs.
     484                 :            :                 //
     485                 :            :                 // SEQUENCE_FINAL-1 is picked to still allow use of nLockTime by
     486                 :            :                 // non-replaceable transactions. All inputs rather than just one
     487                 :            :                 // is for the sake of multi-party protocols, where we don't
     488                 :            :                 // want a single party to be able to disable replacement.
     489                 :            :                 //
     490                 :            :                 // The opt-out ignores descendants as anyone relying on
     491                 :            :                 // first-seen mempool behavior should be checking all
     492                 :            :                 // unconfirmed ancestors anyway; doing otherwise is hopelessly
     493                 :            :                 // insecure.
     494                 :        307 :                 bool fReplacementOptOut = true;
     495 [ +  + ][ +  + ]:        925 :                 for (const CTxIn &_txin : ptxConflicting->vin)
     496                 :            :                 {
     497         [ +  + ]:        308 :                     if (_txin.nSequence <= MAX_BIP125_RBF_SEQUENCE)
     498                 :            :                     {
     499                 :            :                         fReplacementOptOut = false;
     500                 :            :                         break;
     501                 :            :                     }
     502                 :            :                 }
     503         [ +  + ]:        307 :                 if (fReplacementOptOut) {
     504 [ +  - ][ +  - ]:         15 :                     return state.Invalid(ValidationInvalidReason::TX_MEMPOOL_POLICY, false, REJECT_DUPLICATE, "txn-mempool-conflict");
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ -  + ][ -  + ]
         [ #  # ][ #  # ]
                 [ #  # ]
     505                 :            :                 }
     506                 :            : 
     507 [ +  - ][ +  - ]:        608 :                 setConflicts.insert(ptxConflicting->GetHash());
     508                 :            :             }
     509                 :            :         }
     510                 :            :     }
     511                 :            : 
     512                 :      20381 :     {
     513                 :      53213 :         CCoinsView dummy;
     514   [ +  -  +  - ]:      36797 :         CCoinsViewCache view(&dummy);
     515                 :            : 
     516         [ +  - ]:      20381 :         LockPoints lp;
     517 [ +  - ][ +  - ]:      57178 :         CCoinsViewMemPool viewMemPool(pcoinsTip.get(), pool);
     518         [ +  - ]:      20381 :         view.SetBackend(viewMemPool);
     519                 :            : 
     520                 :            :         // do all inputs exist?
     521 [ +  + ][ +  + ]:      87232 :         for (const CTxIn& txin : tx.vin) {
     522 [ +  - ][ +  - ]:      59084 :             if (!pcoinsTip->HaveCoinInCache(txin.prevout)) {
                 [ +  + ]
     523         [ +  - ]:       6554 :                 coins_to_uncache.push_back(txin.prevout);
     524                 :            :             }
     525                 :            : 
     526                 :            :             // Note: this call may add txin.prevout to the coins cache
     527                 :            :             // (pcoinsTip.cacheCoins) by way of FetchCoin(). It should be removed
     528                 :            :             // later (via coins_to_uncache) if this tx turns out to be invalid.
     529 [ +  - ][ +  + ]:      29542 :             if (!view.HaveCoin(txin.prevout)) {
     530                 :            :                 // Are inputs missing because we already have the tx?
     531 [ +  + ][ +  + ]:      10375 :                 for (size_t out = 0; out < tx.vout.size(); out++) {
     532                 :            :                     // Optimistically just do efficient check of cache for outputs
     533 [ +  - ][ +  - ]:      10410 :                     if (pcoinsTip->HaveCoinInCache(COutPoint(hash, out))) {
         [ +  - ][ +  + ]
     534 [ +  - ][ +  - ]:          5 :                         return state.Invalid(ValidationInvalidReason::TX_CONFLICT, false, REJECT_DUPLICATE, "txn-already-known");
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ -  + ][ -  + ]
         [ #  # ][ #  # ]
                 [ #  # ]
     535                 :            :                     }
     536                 :            :                 }
     537                 :            :                 // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
     538         [ +  + ]:       3452 :                 if (pfMissingInputs) {
     539                 :         40 :                     *pfMissingInputs = true;
     540                 :            :                 }
     541                 :       3452 :                 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
     542                 :            :             }
     543                 :            :         }
     544                 :            : 
     545                 :            :         // Bring the best block into scope
     546         [ +  - ]:      16928 :         view.GetBestBlock();
     547                 :            : 
     548                 :            :         // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
     549         [ +  - ]:      16928 :         view.SetBackend(dummy);
     550                 :            : 
     551                 :            :         // Only accept BIP68 sequence locked transactions that can be mined in the next
     552                 :            :         // block; we don't want our mempool filled up with transactions that can't
     553                 :            :         // be mined yet.
     554                 :            :         // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
     555                 :            :         // CoinsViewCache instead of create its own
     556 [ +  - ][ +  + ]:      16928 :         if (!CheckSequenceLocks(pool, tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
     557 [ +  - ][ +  - ]:       1140 :             return state.Invalid(ValidationInvalidReason::TX_PREMATURE_SPEND, false, REJECT_NONSTANDARD, "non-BIP68-final");
         [ +  - ][ +  - ]
         [ +  - ][ -  + ]
         [ -  + ][ -  + ]
         [ #  # ][ #  # ]
                 [ #  # ]
     558                 :            : 
     559                 :      16548 :         CAmount nFees = 0;
     560 [ +  - ][ +  - ]:      16548 :         if (!Consensus::CheckTxInputs(tx, state, view, GetSpendHeight(view), nFees)) {
                 [ +  + ]
     561 [ +  - ][ +  - ]:          6 :             return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), FormatStateMessage(state));
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
     562                 :            :         }
     563                 :            : 
     564                 :            :         // Check for non-standard pay-to-script-hash in inputs
     565 [ +  + ][ +  - ]:      16545 :         if (fRequireStandard && !AreInputsStandard(tx, view))
                 [ +  + ]
     566 [ +  - ][ +  - ]:         85 :             return state.Invalid(ValidationInvalidReason::TX_NOT_STANDARD, false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ -  + ][ -  + ]
         [ #  # ][ #  # ]
                 [ #  # ]
     567                 :            : 
     568                 :            :         // Check for non-standard witness in P2WSH
     569 [ +  + ][ +  + ]:      16528 :         if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, view))
         [ +  - ][ +  + ]
     570 [ +  - ][ +  - ]:         35 :             return state.Invalid(ValidationInvalidReason::TX_WITNESS_MUTATED, false, REJECT_NONSTANDARD, "bad-witness-nonstandard");
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ -  + ][ -  + ]
         [ #  # ][ #  # ]
                 [ #  # ]
     571                 :            : 
     572         [ +  - ]:      16521 :         int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
     573                 :            : 
     574                 :            :         // nModifiedFees includes any fee deltas from PrioritiseTransaction
     575                 :      16521 :         CAmount nModifiedFees = nFees;
     576         [ +  - ]:      16521 :         pool.ApplyDelta(hash, nModifiedFees);
     577                 :            : 
     578                 :            :         // Keep track of transactions that spend a coinbase, which we re-scan
     579                 :            :         // during reorgs to ensure COINBASE_MATURITY is still met.
     580                 :      16521 :         bool fSpendsCoinbase = false;
     581 [ +  + ][ +  + ]:      71049 :         for (const CTxIn &txin : tx.vin) {
     582         [ +  - ]:      22264 :             const Coin &coin = view.AccessCoin(txin.prevout);
     583 [ +  + ][ +  + ]:      44528 :             if (coin.IsCoinBase()) {
     584                 :            :                 fSpendsCoinbase = true;
     585                 :            :                 break;
     586                 :            :             }
     587                 :            :         }
     588                 :            : 
     589                 :      49563 :         CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, ::ChainActive().Height(),
     590 [ +  - ][ +  - ]:      49458 :                               fSpendsCoinbase, nSigOpsCost, lp);
                 [ #  # ]
     591         [ +  - ]:      16521 :         unsigned int nSize = entry.GetTxSize();
     592                 :            : 
     593         [ +  + ]:      16521 :         if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
     594 [ +  - ][ +  - ]:         16 :             return state.Invalid(ValidationInvalidReason::TX_NOT_STANDARD, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops",
         [ +  - ][ +  - ]
         [ -  + ][ #  # ]
                 [ #  # ]
     595 [ +  - ][ -  + ]:          8 :                 strprintf("%d", nSigOpsCost));
                 [ #  # ]
     596                 :            : 
     597 [ +  - ][ +  - ]:      33034 :         CAmount mempoolRejectFee = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
         [ +  - ][ +  - ]
         [ +  - ][ -  + ]
         [ +  + ][ #  # ]
     598 [ +  + ][ +  + ]:      16517 :         if (!bypass_limits && mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
                 [ +  + ]
     599 [ +  - ][ +  - ]:          4 :             return state.Invalid(ValidationInvalidReason::TX_MEMPOOL_POLICY, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", strprintf("%d < %d", nModifiedFees, mempoolRejectFee));
         [ +  - ][ +  - ]
         [ +  - ][ -  + ]
         [ -  + ][ #  # ]
         [ #  # ][ #  # ]
     600                 :            :         }
     601                 :            : 
     602                 :            :         // No transactions are allowed below minRelayTxFee except from disconnected blocks
     603 [ +  + ][ +  - ]:      16516 :         if (!bypass_limits && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) {
                 [ +  + ]
     604 [ +  - ][ +  - ]:         32 :             return state.Invalid(ValidationInvalidReason::TX_MEMPOOL_POLICY, false, REJECT_INSUFFICIENTFEE, "min relay fee not met", strprintf("%d < %d", nModifiedFees, ::minRelayTxFee.GetFee(nSize)));
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ -  + ][ -  + ]
         [ #  # ][ #  # ]
                 [ #  # ]
     605                 :            :         }
     606                 :            : 
     607 [ +  + ][ +  + ]:      16508 :         if (nAbsurdFee && nFees > nAbsurdFee)
     608 [ +  - ][ +  - ]:         12 :             return state.Invalid(ValidationInvalidReason::TX_NOT_STANDARD, false,
         [ +  - ][ +  - ]
         [ -  + ][ #  # ]
                 [ #  # ]
     609                 :            :                 REJECT_HIGHFEE, "absurdly-high-fee",
     610 [ +  - ][ -  + ]:          6 :                 strprintf("%d > %d", nFees, nAbsurdFee));
                 [ #  # ]
     611                 :            : 
     612                 :            :         // Calculate in-mempool ancestors, up to a limit.
     613   [ +  -  +  - ]:      32921 :         CTxMemPool::setEntries setAncestors;
     614 [ +  - ][ +  - ]:      49515 :         size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
         [ +  - ][ +  - ]
         [ +  - ][ #  # ]
     615 [ +  - ][ +  - ]:      49515 :         size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
         [ +  - ][ +  - ]
         [ +  - ][ #  # ]
     616 [ +  - ][ +  - ]:      49515 :         size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
         [ +  - ][ +  - ]
         [ +  - ][ #  # ]
     617 [ +  - ][ +  - ]:      49515 :         size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
         [ +  - ][ +  - ]
         [ +  - ][ #  # ]
     618 [ +  - ][ #  # ]:      32921 :         std::string errString;
     619 [ +  - ][ +  + ]:      16505 :         if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
     620                 :         36 :             setAncestors.clear();
     621                 :            :             // If CalculateMemPoolAncestors fails second time, we want the original error string.
     622 [ -  + ][ #  # ]:         37 :             std::string dummy_err_string;
                 [ +  + ]
     623                 :            :             // If the new transaction is relatively small (up to 40k weight)
     624                 :            :             // and has at most one ancestor (ie ancestor limit of 2, including
     625                 :            :             // the new transaction), allow it if its parent has exactly the
     626                 :            :             // descendant limit descendants.
     627                 :            :             //
     628                 :            :             // This allows protocols which rely on distrusting counterparties
     629                 :            :             // being able to broadcast descendants of an unconfirmed transaction
     630                 :            :             // to be secure by simply only having two immediately-spendable
     631                 :            :             // outputs - one for each counterparty. For more info on the uses for
     632                 :            :             // this, see https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-November/016518.html
     633 [ +  + ][ +  + ]:         52 :             if (nSize >  EXTRA_DESCENDANT_TX_SIZE_LIMIT ||
     634         [ +  - ]:         16 :                     !pool.CalculateMemPoolAncestors(entry, setAncestors, 2, nLimitAncestorSize, nLimitDescendants + 1, nLimitDescendantSize + EXTRA_DESCENDANT_TX_SIZE_LIMIT, dummy_err_string)) {
     635 [ +  - ][ +  - ]:        175 :                 return state.Invalid(ValidationInvalidReason::TX_MEMPOOL_POLICY, false, REJECT_NONSTANDARD, "too-long-mempool-chain", errString);
         [ +  - ][ +  - ]
         [ +  + ][ +  + ]
                 [ #  # ]
     636                 :            :             }
     637                 :            :         }
     638                 :            : 
     639                 :            :         // A transaction that spends outputs that would be replaced by it is invalid. Now
     640                 :            :         // that we have the set of all ancestors we can detect this
     641                 :            :         // pathological case by making sure setConflicts and setAncestors don't
     642                 :            :         // intersect.
     643 [ +  + ][ +  + ]:      59520 :         for (CTxMemPool::txiter ancestorIt : setAncestors)
     644                 :            :         {
     645                 :      15171 :             const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
     646                 :      10112 :             if (setConflicts.count(hashAncestor))
     647                 :            :             {
     648 [ +  - ][ +  - ]:          8 :                 return state.Invalid(ValidationInvalidReason::CONSENSUS, false, REJECT_INVALID, "bad-txns-spends-conflicting-tx",
         [ +  - ][ +  - ]
         [ +  - ][ #  # ]
                 [ #  # ]
     649 [ +  - ][ +  - ]:          4 :                                  strprintf("%s spends conflicting transaction %s",
                 [ #  # ]
     650 [ +  - ][ +  - ]:          4 :                                            hash.ToString(),
                 [ #  # ]
     651 [ +  - ][ +  - ]:          4 :                                            hashAncestor.ToString()));
                 [ #  # ]
     652                 :            :             }
     653                 :            :         }
     654                 :            : 
     655                 :            :         // Check if it's economically rational to mine this transaction rather
     656                 :            :         // than the ones it replaces.
     657                 :      16468 :         CAmount nConflictingFees = 0;
     658                 :      16468 :         size_t nConflictingSize = 0;
     659                 :      16468 :         uint64_t nConflictingCount = 0;
     660 [ +  + ][ +  + ]:      32884 :         CTxMemPool::setEntries allConflicting;
     661                 :            : 
     662                 :            :         // If we don't hold the lock allConflicting might be incomplete; the
     663                 :            :         // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
     664                 :            :         // mempool consistency for us.
     665         [ +  + ]:      16468 :         const bool fReplacementTransaction = setConflicts.size();
     666         [ +  + ]:      16468 :         if (fReplacementTransaction)
     667                 :            :         {
     668         [ +  - ]:        102 :             CFeeRate newFeeRate(nModifiedFees, nSize);
     669         [ +  - ]:        102 :             std::set<uint256> setConflictsParents;
     670                 :        102 :             const int maxDescendantsToVisit = 100;
     671         [ +  - ]:        188 :             const CTxMemPool::setEntries setIterConflicting = pool.GetIterSet(setConflicts);
     672 [ +  + ][ +  + ]:        888 :             for (const auto& mi : setIterConflicting) {
                 [ +  - ]
     673                 :            :                 // Don't allow the replacement to reduce the feerate of the
     674                 :            :                 // mempool.
     675                 :            :                 //
     676                 :            :                 // We usually don't want to accept replacements with lower
     677                 :            :                 // feerates than what they replaced as that would lower the
     678                 :            :                 // feerate of the next block. Requiring that the feerate always
     679                 :            :                 // be increased is also an easy-to-reason about way to prevent
     680                 :            :                 // DoS attacks via replacements.
     681                 :            :                 //
     682                 :            :                 // We only consider the feerates of transactions being directly
     683                 :            :                 // replaced, not their indirect descendants. While that does
     684                 :            :                 // mean high feerate children are ignored when deciding whether
     685                 :            :                 // or not to replace, we do require the replacement to pay more
     686                 :            :                 // overall fees too, mitigating most cases.
     687 [ +  - ][ +  - ]:        602 :                 CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
         [ +  - ][ +  - ]
                 [ +  - ]
     688 [ +  + ][ +  + ]:        602 :                 if (newFeeRate <= oldFeeRate)
     689                 :            :                 {
     690 [ +  - ][ +  - ]:         40 :                     return state.Invalid(ValidationInvalidReason::TX_MEMPOOL_POLICY, false, REJECT_INSUFFICIENTFEE, "insufficient fee",
         [ +  - ][ +  - ]
         [ +  - ][ #  # ]
                 [ #  # ]
     691 [ +  - ][ +  - ]:         20 :                             strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
                 [ #  # ]
     692 [ +  - ][ +  - ]:         20 :                                   hash.ToString(),
                 [ #  # ]
     693 [ +  - ][ +  - ]:         20 :                                   newFeeRate.ToString(),
                 [ #  # ]
     694 [ +  - ][ +  - ]:         20 :                                   oldFeeRate.ToString()));
                 [ #  # ]
     695                 :            :                 }
     696                 :            : 
     697 [ +  + ][ +  + ]:       2043 :                 for (const CTxIn &txin : mi->GetTx().vin)
     698                 :            :                 {
     699         [ +  - ]:        294 :                     setConflictsParents.insert(txin.prevout.hash);
     700                 :            :                 }
     701                 :            : 
     702                 :        873 :                 nConflictingCount += mi->GetCountWithDescendants();
     703                 :            :             }
     704                 :            :             // This potentially overestimates the number of actual descendants
     705                 :            :             // but we just want to be conservative to avoid doing too much
     706                 :            :             // work.
     707         [ +  + ]:         92 :             if (nConflictingCount <= maxDescendantsToVisit) {
     708                 :            :                 // If not too many to replace, then calculate the set of
     709                 :            :                 // transactions that would have to be evicted
     710 [ +  + ][ +  + ]:        455 :                 for (CTxMemPool::txiter it : setIterConflicting) {
                 [ +  - ]
     711         [ +  - ]:        188 :                     pool.CalculateDescendants(it, allConflicting);
     712                 :            :                 }
     713 [ +  + ][ +  + ]:       1203 :                 for (CTxMemPool::txiter it : allConflicting) {
                 [ +  - ]
     714 [ +  - ][ +  - ]:        936 :                     nConflictingFees += it->GetModifiedFee();
     715 [ +  - ][ +  - ]:        936 :                     nConflictingSize += it->GetTxSize();
     716                 :            :                 }
     717                 :            :             } else {
     718 [ +  - ][ +  - ]:         12 :                 return state.Invalid(ValidationInvalidReason::TX_MEMPOOL_POLICY, false, REJECT_NONSTANDARD, "too many potential replacements",
         [ +  - ][ +  - ]
         [ +  - ][ #  # ]
                 [ #  # ]
     719 [ +  - ][ +  - ]:          6 :                         strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
                 [ #  # ]
     720 [ +  - ][ +  - ]:          6 :                             hash.ToString(),
                 [ #  # ]
     721                 :            :                             nConflictingCount,
     722                 :            :                             maxDescendantsToVisit));
     723                 :            :             }
     724                 :            : 
     725 [ +  + ][ +  + ]:        293 :             for (unsigned int j = 0; j < tx.vin.size(); j++)
     726                 :            :             {
     727                 :            :                 // We don't want to accept replacements that require low
     728                 :            :                 // feerate junk to be mined first. Ideally we'd keep track of
     729                 :            :                 // the ancestor feerates and make the decision based on that,
     730                 :            :                 // but for now requiring all new inputs to be confirmed works.
     731                 :        410 :                 if (!setConflictsParents.count(tx.vin[j].prevout.hash))
     732                 :            :                 {
     733                 :            :                     // Rather than check the UTXO set - potentially expensive -
     734                 :            :                     // it's cheaper to just check if the new input refers to a
     735                 :            :                     // tx that's in the mempool.
     736 [ +  - ][ +  - ]:         30 :                     if (pool.exists(tx.vin[j].prevout.hash)) {
                 [ +  + ]
     737 [ +  - ][ +  - ]:          4 :                         return state.Invalid(ValidationInvalidReason::TX_MEMPOOL_POLICY, false, REJECT_NONSTANDARD, "replacement-adds-unconfirmed",
         [ +  - ][ +  - ]
         [ +  - ][ #  # ]
                 [ #  # ]
     738 [ +  - ][ +  - ]:          2 :                                          strprintf("replacement %s adds unconfirmed input, idx %d",
                 [ #  # ]
     739 [ +  - ][ +  - ]:          2 :                                                   hash.ToString(), j));
                 [ #  # ]
     740                 :            :                     }
     741                 :            :                 }
     742                 :            :             }
     743                 :            : 
     744                 :            :             // The replacement must pay greater fees than the transactions it
     745                 :            :             // replaces - if we did the bandwidth used by those conflicting
     746                 :            :             // transactions would not be paid for.
     747         [ +  + ]:         88 :             if (nModifiedFees < nConflictingFees)
     748                 :            :             {
     749 [ +  - ][ +  - ]:          8 :                 return state.Invalid(ValidationInvalidReason::TX_MEMPOOL_POLICY, false, REJECT_INSUFFICIENTFEE, "insufficient fee",
         [ +  - ][ +  - ]
         [ +  - ][ #  # ]
                 [ #  # ]
     750 [ +  - ][ +  - ]:          4 :                                  strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
                 [ #  # ]
     751 [ +  - ][ +  - ]:          6 :                                           hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
         [ +  - ][ +  - ]
         [ -  + ][ -  + ]
         [ #  # ][ #  # ]
                 [ #  # ]
     752                 :            :             }
     753                 :            : 
     754                 :            :             // Finally in addition to paying more fees than the conflicts the
     755                 :            :             // new transaction must pay for its own bandwidth.
     756                 :         86 :             CAmount nDeltaFees = nModifiedFees - nConflictingFees;
     757 [ +  - ][ -  + ]:         86 :             if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
     758                 :            :             {
     759 [ #  # ][ #  # ]:          0 :                 return state.Invalid(ValidationInvalidReason::TX_MEMPOOL_POLICY, false, REJECT_INSUFFICIENTFEE, "insufficient fee",
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
                 [ #  # ]
     760 [ #  # ][ #  # ]:          0 :                         strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
                 [ #  # ]
     761 [ #  # ][ #  # ]:          0 :                               hash.ToString(),
                 [ #  # ]
     762 [ #  # ][ #  # ]:          0 :                               FormatMoney(nDeltaFees),
                 [ #  # ]
     763 [ #  # ][ #  # ]:          0 :                               FormatMoney(::incrementalRelayFee.GetFee(nSize))));
         [ #  # ][ #  # ]
     764                 :            :             }
     765                 :            :         }
     766                 :            : 
     767                 :      16452 :         constexpr unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
     768                 :            : 
     769                 :            :         // Check against previous transactions
     770                 :            :         // This is done last to help prevent CPU exhaustion denial-of-service attacks.
     771         [ +  - ]:      16452 :         PrecomputedTransactionData txdata(tx);
     772 [ +  - ][ +  + ]:      16452 :         if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, false, txdata)) {
     773                 :            :             // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
     774                 :            :             // need to turn both off, and compare against just turning off CLEANSTACK
     775                 :            :             // to see if the failure is specifically due to witness validation.
     776                 :         28 :             CValidationState stateDummy; // Want reported failures to be from first CheckInputs
     777 [ +  + ][ +  - ]:         37 :             if (!tx.HasWitness() && CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, txdata) &&
         [ +  + ][ +  - ]
     778         [ +  - ]:          9 :                 !CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, txdata)) {
     779                 :            :                 // Only the witness is missing, so the transaction itself may be fine.
     780         [ +  - ]:          9 :                 state.Invalid(ValidationInvalidReason::TX_WITNESS_MUTATED, false,
     781 [ +  - ][ +  - ]:         27 :                         state.GetRejectCode(), state.GetRejectReason(), state.GetDebugMessage());
         [ +  - ][ +  - ]
         [ -  + ][ #  # ]
                 [ #  # ]
     782                 :            :             }
     783 [ +  + ][ +  + ]:         56 :             assert(IsTransactionReason(state.GetReason()));
     784                 :         28 :             return false; // state filled in by CheckInputs
     785                 :            :         }
     786                 :            : 
     787                 :            :         // Check again against the current block tip's script verification
     788                 :            :         // flags to cache our script execution flags. This is, of course,
     789                 :            :         // useless if the next block has different script flags from the
     790                 :            :         // previous one, but because the cache tracks script flags for us it
     791                 :            :         // will auto-invalidate and we'll just have a few blocks of extra
     792                 :            :         // misses on soft-fork activation.
     793                 :            :         //
     794                 :            :         // This is also useful in case of bugs in the standard flags that cause
     795                 :            :         // transactions to pass as valid when they're actually invalid. For
     796                 :            :         // instance the STRICTENC flag was incorrectly allowing certain
     797                 :            :         // CHECKSIG NOT scripts to pass, even though they were invalid.
     798                 :            :         //
     799                 :            :         // There is a similar check in CreateNewBlock() to prevent creating
     800                 :            :         // invalid blocks (using TestBlockValidity), however allowing such
     801                 :            :         // transactions into the mempool can be exploited as a DoS attack.
     802 [ +  - ][ +  - ]:      49272 :         unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(::ChainActive().Tip(), chainparams.GetConsensus());
                 [ +  - ]
     803 [ +  - ][ -  + ]:      16424 :         if (!CheckInputsFromMempoolAndCache(tx, state, view, pool, currentBlockScriptVerifyFlags, true, txdata)) {
     804         [ #  # ]:          0 :             return error("%s: BUG! PLEASE REPORT THIS! CheckInputs failed against latest-block but not STANDARD flags %s, %s",
     805 [ #  # ][ #  # ]:          0 :                     __func__, hash.ToString(), FormatStateMessage(state));
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
     806                 :            :         }
     807                 :            : 
     808         [ +  + ]:      16424 :         if (test_accept) {
     809                 :            :             // Tx was accepted, but not added
     810                 :            :             return true;
     811                 :            :         }
     812                 :            : 
     813                 :            :         // Remove conflicting transactions from the mempool
     814 [ +  + ][ +  + ]:      49572 :         for (CTxMemPool::txiter it : allConflicting)
                 [ +  - ]
     815                 :            :         {
     816         [ +  - ]:        324 :             LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
     817 [ +  - ][ +  - ]:       1620 :                     it->GetTx().GetHash().ToString(),
         [ +  - ][ +  - ]
         [ +  - ][ #  # ]
     818 [ +  - ][ +  - ]:        648 :                     hash.ToString(),
                 [ #  # ]
     819 [ -  + ][ #  # ]:        324 :                     FormatMoney(nModifiedFees - nConflictingFees),
     820         [ +  - ]:        324 :                     (int)nSize - (int)nConflictingSize);
     821         [ +  + ]:        324 :             if (plTxnReplaced)
     822 [ +  - ][ -  + ]:         10 :                 plTxnReplaced->push_back(it->GetSharedTx());
                 [ #  # ]
     823                 :            :         }
     824         [ +  - ]:      16416 :         pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
     825                 :            : 
     826                 :            :         // This transaction should only count for fee estimation if:
     827                 :            :         // - it isn't a BIP 125 replacement transaction (may not be widely supported)
     828                 :            :         // - it's not being re-added during a reorg which bypasses typical mempool fee limits
     829                 :            :         // - the node is not behind
     830                 :            :         // - the transaction is not dependent on any other transactions in the mempool
     831 [ +  + ][ +  - ]:      16416 :         bool validForFeeEstimation = !fReplacementTransaction && !bypass_limits && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
         [ +  + ][ +  - ]
                 [ +  + ]
     832                 :            : 
     833                 :            :         // Store transaction in memory
     834         [ +  - ]:      16416 :         pool.addUnchecked(entry, setAncestors, validForFeeEstimation);
     835                 :            : 
     836                 :            :         // trim mempool and check if tx was trimmed
     837         [ +  + ]:      16416 :         if (!bypass_limits) {
     838 [ +  - ][ +  - ]:      32386 :             LimitMempoolSize(pool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ +  - ][ -  + ]
         [ -  + ][ -  + ]
         [ +  - ][ #  # ]
                 [ #  # ]
     839 [ +  - ][ -  + ]:      16193 :             if (!pool.exists(hash))
     840 [ #  # ][ #  # ]:          0 :                 return state.Invalid(ValidationInvalidReason::TX_MEMPOOL_POLICY, false, REJECT_INSUFFICIENTFEE, "mempool full");
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
                 [ #  # ]
     841                 :            :         }
     842                 :            :     }
     843                 :            : 
     844 [ +  - ][ +  - ]:      16416 :     GetMainSignals().TransactionAddedToMempool(ptx);
     845                 :            : 
     846                 :            :     return true;
     847                 :            : }
     848                 :            : 
     849                 :            : /** (try to) add transaction to memory pool with a specified acceptance time **/
     850                 :      20736 : static bool AcceptToMemoryPoolWithTime(const CChainParams& chainparams, CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx,
     851                 :            :                         bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
     852                 :            :                         bool bypass_limits, const CAmount nAbsurdFee, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
     853                 :            : {
     854 [ +  - ][ #  # ]:      20736 :     std::vector<COutPoint> coins_to_uncache;
     855         [ +  - ]:      20736 :     bool res = AcceptToMemoryPoolWorker(chainparams, pool, state, tx, pfMissingInputs, nAcceptTime, plTxnReplaced, bypass_limits, nAbsurdFee, coins_to_uncache, test_accept);
     856         [ +  + ]:      20736 :     if (!res) {
     857                 :            :         // Remove coins that were not present in the coins cache before calling ATMPW;
     858                 :            :         // this is to prevent memory DoS in case we receive a large number of
     859                 :            :         // invalid transactions that attempt to overrun the in-memory coins cache
     860                 :            :         // (`CCoinsViewCache::cacheCoins`).
     861                 :            : 
     862 [ +  + ][ +  + ]:      16556 :         for (const COutPoint& hashTx : coins_to_uncache)
     863 [ +  - ][ +  - ]:       7240 :             pcoinsTip->Uncache(hashTx);
     864                 :            :     }
     865                 :            :     // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
     866   [ +  -  +  + ]:      41472 :     CValidationState stateDummy;
     867         [ +  - ]:      20736 :     ::ChainstateActive().FlushStateToDisk(chainparams, stateDummy, FlushStateMode::PERIODIC);
     868                 :      41472 :     return res;
     869                 :            : }
     870                 :            : 
     871                 :      20695 : bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx,
     872                 :            :                         bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
     873                 :            :                         bool bypass_limits, const CAmount nAbsurdFee, bool test_accept)
     874                 :            : {
     875                 :      20695 :     const CChainParams& chainparams = Params();
     876                 :      20695 :     return AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, pfMissingInputs, GetTime(), plTxnReplaced, bypass_limits, nAbsurdFee, test_accept);
     877                 :            : }
     878                 :            : 
     879                 :            : /**
     880                 :            :  * Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock.
     881                 :            :  * If blockIndex is provided, the transaction is fetched from the corresponding block.
     882                 :            :  */
     883                 :        585 : bool GetTransaction(const uint256& hash, CTransactionRef& txOut, const Consensus::Params& consensusParams, uint256& hashBlock, const CBlockIndex* const block_index)
     884                 :            : {
     885 [ +  - ][ #  # ]:       1755 :     LOCK(cs_main);
     886                 :            : 
     887         [ +  + ]:        585 :     if (!block_index) {
     888 [ +  - ][ -  + ]:        527 :         CTransactionRef ptx = mempool.get(hash);
                 [ #  # ]
     889 [ +  + ][ +  + ]:       1052 :         if (ptx) {
     890                 :        517 :             txOut = ptx;
     891         [ +  + ]:        525 :             return true;
     892                 :            :         }
     893                 :            : 
     894 [ +  + ][ +  + ]:         18 :         if (g_txindex) {
     895 [ +  - ][ +  - ]:         16 :             return g_txindex->FindTx(hash, hashBlock, txOut);
     896                 :            :         }
     897                 :            :     } else {
     898                 :         60 :         CBlock block;
     899 [ +  - ][ +  - ]:         59 :         if (ReadBlockFromDisk(block, block_index, consensusParams)) {
     900 [ +  + ][ +  + ]:        272 :             for (const auto& tx : block.vtx) {
     901 [ +  + ][ +  + ]:        612 :                 if (tx->GetHash() == hash) {
         [ +  + ][ +  + ]
     902                 :         58 :                     txOut = tx;
     903                 :         58 :                     hashBlock = block_index->GetBlockHash();
     904                 :         58 :                     return true;
     905                 :            :                 }
     906                 :            :             }
     907                 :            :         }
     908                 :            :     }
     909                 :            : 
     910                 :            :     return false;
     911                 :            : }
     912                 :            : 
     913                 :            : 
     914                 :            : 
     915                 :            : 
     916                 :            : 
     917                 :            : 
     918                 :            : //////////////////////////////////////////////////////////////////////////////
     919                 :            : //
     920                 :            : // CBlock and CBlockIndex
     921                 :            : //
     922                 :            : 
     923                 :      31354 : static bool WriteBlockToDisk(const CBlock& block, FlatFilePos& pos, const CMessageHeader::MessageStartChars& messageStart)
     924                 :            : {
     925                 :            :     // Open history file to append
     926 [ -  + ][ +  - ]:      94062 :     CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
                 [ #  # ]
     927   [ -  +  -  + ]:      62708 :     if (fileout.IsNull())
     928         [ #  # ]:          0 :         return error("WriteBlockToDisk: OpenBlockFile failed");
     929                 :            : 
     930                 :            :     // Write index header
     931                 :      62708 :     unsigned int nSize = GetSerializeSize(block, fileout.GetVersion());
     932 [ +  - ][ +  - ]:      31354 :     fileout << messageStart << nSize;
     933                 :            : 
     934                 :            :     // Write block
     935 [ +  - ][ +  - ]:      62708 :     long fileOutPos = ftell(fileout.Get());
     936         [ -  + ]:      31354 :     if (fileOutPos < 0)
     937         [ #  # ]:          0 :         return error("WriteBlockToDisk: ftell failed");
     938                 :      31354 :     pos.nPos = (unsigned int)fileOutPos;
     939         [ +  - ]:      31354 :     fileout << block;
     940                 :            : 
     941                 :            :     return true;
     942                 :            : }
     943                 :            : 
     944                 :      66652 : bool ReadBlockFromDisk(CBlock& block, const FlatFilePos& pos, const Consensus::Params& consensusParams)
     945                 :            : {
     946                 :      66652 :     block.SetNull();
     947                 :            : 
     948                 :            :     // Open history file to read
     949 [ +  + ][ #  # ]:     199848 :     CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
                 [ +  + ]
     950   [ +  +  +  + ]:     133304 :     if (filein.IsNull())
     951 [ +  - ][ +  - ]:        108 :         return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
         [ +  - ][ #  # ]
     952                 :            : 
     953                 :            :     // Read block
     954                 :      66544 :     try {
     955         [ +  - ]:      66544 :         filein >> block;
     956                 :            :     }
     957                 :          0 :     catch (const std::exception& e) {
     958 [ #  # ][ #  # ]:          0 :         return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
         [ #  # ][ #  # ]
     959                 :            :     }
     960                 :            : 
     961                 :            :     // Check the header
     962 [ +  - ][ +  - ]:      66544 :     if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
                 [ -  + ]
     963 [ #  # ][ #  # ]:          0 :         return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
         [ #  # ][ #  # ]
     964                 :            : 
     965                 :            :     return true;
     966                 :            : }
     967                 :            : 
     968                 :      66468 : bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
     969                 :            : {
     970                 :      66468 :     FlatFilePos blockPos;
     971                 :      66468 :     {
     972                 :      66468 :         LOCK(cs_main);
     973 [ +  - ][ +  + ]:     132828 :         blockPos = pindex->GetBlockPos();
     974                 :            :     }
     975                 :            : 
     976         [ +  + ]:      66468 :     if (!ReadBlockFromDisk(block, blockPos, consensusParams))
     977                 :            :         return false;
     978   [ -  +  -  + ]:     132720 :     if (block.GetHash() != pindex->GetBlockHash())
     979         [ #  # ]:          0 :         return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
     980 [ #  # ][ #  # ]:          0 :                 pindex->ToString(), pindex->GetBlockPos().ToString());
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
     981                 :            :     return true;
     982                 :            : }
     983                 :            : 
     984                 :       7068 : bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const FlatFilePos& pos, const CMessageHeader::MessageStartChars& message_start)
     985                 :            : {
     986                 :       7068 :     FlatFilePos hpos = pos;
     987                 :       7068 :     hpos.nPos -= 8; // Seek back 8 bytes for meta header
     988 [ -  + ][ +  - ]:      21204 :     CAutoFile filein(OpenBlockFile(hpos, true), SER_DISK, CLIENT_VERSION);
                 [ #  # ]
     989   [ -  +  -  + ]:      14136 :     if (filein.IsNull()) {
     990 [ #  # ][ #  # ]:          0 :         return error("%s: OpenBlockFile failed for %s", __func__, pos.ToString());
         [ #  # ][ #  # ]
     991                 :            :     }
     992                 :            : 
     993                 :       7068 :     try {
     994                 :       7068 :         CMessageHeader::MessageStartChars blk_start;
     995                 :       7068 :         unsigned int blk_size;
     996                 :            : 
     997 [ +  - ][ +  - ]:       7068 :         filein >> blk_start >> blk_size;
     998                 :            : 
     999         [ -  + ]:       7068 :         if (memcmp(blk_start, message_start, CMessageHeader::MESSAGE_START_SIZE)) {
    1000 [ #  # ][ #  # ]:          0 :             return error("%s: Block magic mismatch for %s: %s versus expected %s", __func__, pos.ToString(),
         [ #  # ][ #  # ]
    1001 [ #  # ][ #  # ]:          0 :                     HexStr(blk_start, blk_start + CMessageHeader::MESSAGE_START_SIZE),
                 [ #  # ]
    1002 [ #  # ][ #  # ]:          0 :                     HexStr(message_start, message_start + CMessageHeader::MESSAGE_START_SIZE));
                 [ #  # ]
    1003                 :            :         }
    1004                 :            : 
    1005         [ -  + ]:       7068 :         if (blk_size > MAX_SIZE) {
    1006 [ #  # ][ #  # ]:          0 :             return error("%s: Block data is larger than maximum deserialization size for %s: %s versus %s", __func__, pos.ToString(),
         [ #  # ][ #  # ]
    1007                 :            :                     blk_size, MAX_SIZE);
    1008                 :            :         }
    1009                 :            : 
    1010         [ +  - ]:       7068 :         block.resize(blk_size); // Zeroing of memory is intentional here
    1011 [ +  - ][ +  - ]:      14136 :         filein.read((char*)block.data(), blk_size);
    1012                 :          0 :     } catch(const std::exception& e) {
    1013 [ #  # ][ #  # ]:          0 :         return error("%s: Read from block file failed: %s for %s", __func__, e.what(), pos.ToString());
         [ #  # ][ #  # ]
    1014                 :            :     }
    1015                 :            : 
    1016                 :            :     return true;
    1017                 :            : }
    1018                 :            : 
    1019                 :       7068 : bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const CBlockIndex* pindex, const CMessageHeader::MessageStartChars& message_start)
    1020                 :            : {
    1021                 :       7068 :     FlatFilePos block_pos;
    1022                 :       7068 :     {
    1023                 :       7068 :         LOCK(cs_main);
    1024 [ +  - ][ +  - ]:      14136 :         block_pos = pindex->GetBlockPos();
    1025                 :            :     }
    1026                 :            : 
    1027                 :       7068 :     return ReadRawBlockFromDisk(block, block_pos, message_start);
    1028                 :            : }
    1029                 :            : 
    1030                 :      75732 : CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
    1031                 :            : {
    1032                 :      75732 :     int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
    1033                 :            :     // Force block reward to zero when right shift is undefined.
    1034         [ +  + ]:      75732 :     if (halvings >= 64)
    1035                 :            :         return 0;
    1036                 :            : 
    1037                 :      75169 :     CAmount nSubsidy = 50 * COIN;
    1038                 :            :     // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
    1039                 :      75169 :     nSubsidy >>= halvings;
    1040                 :      75169 :     return nSubsidy;
    1041                 :            : }
    1042                 :            : 
    1043                 :            : // Note that though this is marked const, we may end up modifying `m_cached_finished_ibd`, which
    1044                 :            : // is a performance-related implementation detail. This function must be marked
    1045                 :            : // `const` so that `CValidationInterface` clients (which are given a `const CChainState*`)
    1046                 :            : // can call it.
    1047                 :            : //
    1048                 :     510933 : bool CChainState::IsInitialBlockDownload() const
    1049                 :            : {
    1050                 :            :     // Optimization: pre-test latch before taking the lock.
    1051 [ +  + ][ +  + ]:    1021866 :     if (m_cached_finished_ibd.load(std::memory_order_relaxed))
    1052                 :            :         return false;
    1053                 :            : 
    1054 [ +  - ][ #  # ]:      71848 :     LOCK(cs_main);
    1055   [ +  +  +  + ]:      71848 :     if (m_cached_finished_ibd.load(std::memory_order_relaxed))
    1056                 :            :         return false;
    1057 [ +  + ][ +  + ]:      71846 :     if (fImporting || fReindex)
         [ -  + ][ -  + ]
    1058                 :       4658 :         return true;
    1059 [ +  - ][ +  - ]:      31265 :     if (m_chain.Tip() == nullptr)
    1060                 :            :         return true;
    1061 [ +  - ][ +  - ]:      62530 :     if (m_chain.Tip()->nChainWork < nMinimumChainWork)
                 [ +  + ]
    1062                 :            :         return true;
    1063 [ +  - ][ +  - ]:      91200 :     if (m_chain.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
         [ +  - ][ +  + ]
    1064                 :            :         return true;
    1065         [ +  - ]:        287 :     LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
    1066                 :        287 :     m_cached_finished_ibd.store(true, std::memory_order_relaxed);
    1067                 :        287 :     return false;
    1068                 :            : }
    1069                 :            : 
    1070                 :            : static CBlockIndex *pindexBestForkTip = nullptr, *pindexBestForkBase = nullptr;
    1071                 :            : 
    1072                 :        768 : BlockMap& BlockIndex()
    1073                 :            : {
    1074                 :        768 :     return g_blockman.m_block_index;
    1075                 :            : }
    1076                 :            : 
    1077                 :          3 : static void AlertNotify(const std::string& strMessage)
    1078                 :            : {
    1079                 :          3 :     uiInterface.NotifyAlertChanged();
    1080                 :            : #if HAVE_SYSTEM
    1081 [ +  - ][ #  # ]:          6 :     std::string strCmd = gArgs.GetArg("-alertnotify", "");
           [ +  -  +  - ]
    1082 [ +  + ][ +  + ]:          6 :     if (strCmd.empty()) return;
                 [ -  + ]
    1083                 :            : 
    1084                 :            :     // Alert text should be plain ascii coming from a trusted source, but to
    1085                 :            :     // be safe we first strip anything not in safeChars, then add single quotes around
    1086                 :            :     // the whole string before passing it to the shell:
    1087 [ +  - ][ +  - ]:          6 :     std::string singleQuote("'");
         [ +  - ][ #  # ]
    1088 [ +  - ][ -  + ]:          4 :     std::string safeStatus = SanitizeString(strMessage);
                 [ #  # ]
    1089 [ +  - ][ +  - ]:          4 :     safeStatus = singleQuote+safeStatus+singleQuote;
         [ +  - ][ -  + ]
                 [ #  # ]
    1090         [ +  - ]:          2 :     boost::replace_all(strCmd, "%s", safeStatus);
    1091                 :            : 
    1092 [ +  - ][ -  + ]:          4 :     std::thread t(runCommand, strCmd);
         [ +  - ][ #  # ]
    1093         [ +  - ]:          2 :     t.detach(); // thread runs free
    1094                 :            : #endif
    1095                 :            : }
    1096                 :            : 
    1097                 :      30834 : static void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
    1098                 :            : {
    1099                 :      30834 :     AssertLockHeld(cs_main);
    1100                 :            :     // Before we get past initial download, we cannot reliably alert about forks
    1101                 :            :     // (we assume we don't get stuck on a fork before finishing our initial sync)
    1102         [ +  + ]:      30834 :     if (::ChainstateActive().IsInitialBlockDownload())
    1103                 :            :         return;
    1104                 :            : 
    1105                 :            :     // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
    1106                 :            :     // of our head, drop it
    1107 [ -  + ][ #  # ]:      26472 :     if (pindexBestForkTip && ::ChainActive().Height() - pindexBestForkTip->nHeight >= 72)
                 [ #  # ]
    1108                 :          0 :         pindexBestForkTip = nullptr;
    1109                 :            : 
    1110 [ +  - ][ +  + ]:      35805 :     if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > ::ChainActive().Tip()->nChainWork + (GetBlockProof(*::ChainActive().Tip()) * 6)))
         [ +  - ][ +  - ]
                 [ +  + ]
    1111                 :            :     {
    1112 [ +  - ][ -  + ]:          6 :         if (!GetfLargeWorkForkFound() && pindexBestForkBase)
    1113                 :            :         {
    1114 [ #  # ][ #  # ]:          0 :             std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
                 [ #  # ]
    1115 [ #  # ][ #  # ]:          0 :                 pindexBestForkBase->phashBlock->ToString() + std::string("'");
         [ #  # ][ #  # ]
    1116         [ #  # ]:          0 :             AlertNotify(warning);
    1117                 :            :         }
    1118 [ -  + ][ #  # ]:          6 :         if (pindexBestForkTip && pindexBestForkBase)
    1119                 :            :         {
    1120                 :          0 :             LogPrintf("%s: Warning: Large valid fork found\n  forking the chain at height %d (%s)\n  lasting to height %d (%s).\nChain state database corruption likely.\n", __func__,
    1121 [ #  # ][ #  # ]:          0 :                    pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
                 [ #  # ]
    1122 [ #  # ][ #  # ]:          0 :                    pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
                 [ #  # ]
    1123                 :          0 :             SetfLargeWorkForkFound(true);
    1124                 :            :         }
    1125                 :            :         else
    1126                 :            :         {
    1127                 :          6 :             LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
    1128                 :          6 :             SetfLargeWorkInvalidChainFound(true);
    1129                 :            :         }
    1130                 :            :     }
    1131                 :            :     else
    1132                 :            :     {
    1133                 :      26466 :         SetfLargeWorkForkFound(false);
    1134                 :      26466 :         SetfLargeWorkInvalidChainFound(false);
    1135                 :            :     }
    1136                 :            : }
    1137                 :            : 
    1138                 :        170 : static void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
    1139                 :            : {
    1140                 :        170 :     AssertLockHeld(cs_main);
    1141                 :            :     // If we are on a fork that is sufficiently large, set a warning flag
    1142                 :        170 :     CBlockIndex* pfork = pindexNewForkTip;
    1143         [ +  - ]:        170 :     CBlockIndex* plonger = ::ChainActive().Tip();
    1144         [ +  + ]:        337 :     while (pfork && pfork != plonger)
    1145                 :            :     {
    1146 [ +  - ][ -  + ]:        167 :         while (plonger && plonger->nHeight > pfork->nHeight)
    1147                 :          0 :             plonger = plonger->pprev;
    1148         [ +  - ]:        167 :         if (pfork == plonger)
    1149                 :            :             break;
    1150                 :        167 :         pfork = pfork->pprev;
    1151                 :            :     }
    1152                 :            : 
    1153                 :            :     // We define a condition where we should warn the user about as a fork of at least 7 blocks
    1154                 :            :     // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
    1155                 :            :     // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
    1156                 :            :     // hash rate operating on the fork.
    1157                 :            :     // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
    1158                 :            :     // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
    1159                 :            :     // the 7-block condition and from this always have the most-likely-to-cause-warning fork
    1160 [ -  + ][ #  # ]:        170 :     if (pfork && (!pindexBestForkTip || pindexNewForkTip->nHeight > pindexBestForkTip->nHeight) &&
    1161 [ +  - ][ -  + ]:        340 :             pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
    1162 [ #  # ][ #  # ]:          0 :             ::ChainActive().Height() - pindexNewForkTip->nHeight < 72)
    1163                 :            :     {
    1164                 :          0 :         pindexBestForkTip = pindexNewForkTip;
    1165                 :          0 :         pindexBestForkBase = pfork;
    1166                 :            :     }
    1167                 :            : 
    1168                 :        170 :     CheckForkWarningConditions();
    1169                 :        170 : }
    1170                 :            : 
    1171                 :        389 : void static InvalidChainFound(CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
    1172                 :            : {
    1173 [ +  + ][ +  + ]:        389 :     if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
    1174                 :         88 :         pindexBestInvalid = pindexNew;
    1175                 :            : 
    1176         [ +  - ]:        389 :     LogPrintf("%s: invalid block=%s  height=%d  log2_work=%.8g  date=%s\n", __func__,
    1177 [ +  - ][ +  - ]:        778 :       pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
                 [ #  # ]
    1178 [ +  - ][ +  - ]:       1167 :       log(pindexNew->nChainWork.getdouble())/log(2.0), FormatISO8601DateTime(pindexNew->GetBlockTime()));
         [ +  - ][ #  # ]
    1179         [ +  - ]:        389 :     CBlockIndex *tip = ::ChainActive().Tip();
    1180         [ -  + ]:        389 :     assert (tip);
    1181         [ +  - ]:        389 :     LogPrintf("%s:  current best=%s  height=%d  log2_work=%.8g  date=%s\n", __func__,
    1182 [ +  - ][ +  - ]:        778 :       tip->GetBlockHash().ToString(), ::ChainActive().Height(), log(tip->nChainWork.getdouble())/log(2.0),
         [ +  - ][ +  - ]
         [ #  # ][ +  - ]
    1183 [ +  - ][ #  # ]:       1167 :       FormatISO8601DateTime(tip->GetBlockTime()));
    1184                 :        389 :     CheckForkWarningConditions();
    1185                 :        389 : }
    1186                 :            : 
    1187                 :        170 : void CChainState::InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
    1188 [ +  - ][ +  - ]:        340 :     if (state.GetReason() != ValidationInvalidReason::BLOCK_MUTATED) {
    1189                 :        170 :         pindex->nStatus |= BLOCK_FAILED_VALID;
    1190                 :        170 :         m_blockman.m_failed_blocks.insert(pindex);
    1191                 :        170 :         setDirtyBlockIndex.insert(pindex);
    1192                 :        170 :         setBlockIndexCandidates.erase(pindex);
    1193                 :        170 :         InvalidChainFound(pindex);
    1194                 :            :     }
    1195                 :        170 : }
    1196                 :            : 
    1197                 :    3137747 : void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
    1198                 :            : {
    1199                 :            :     // mark inputs spent
    1200         [ +  + ]:    3137747 :     if (!tx.IsCoinBase()) {
    1201                 :    6172344 :         txundo.vprevout.reserve(tx.vin.size());
    1202 [ +  + ][ +  + ]:   13397988 :         for (const CTxIn &txin : tx.vin) {
    1203                 :    4139472 :             txundo.vprevout.emplace_back();
    1204                 :    8278944 :             bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
    1205         [ -  + ]:    4139472 :             assert(is_spent);
    1206                 :            :         }
    1207                 :            :     }
    1208                 :            :     // add outputs
    1209                 :    3137747 :     AddCoins(inputs, tx, nHeight);
    1210                 :    3137747 : }
    1211                 :            : 
    1212                 :    2998602 : void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
    1213                 :            : {
    1214         [ +  - ]:    2998602 :     CTxUndo txundo;
    1215         [ +  - ]:    2998602 :     UpdateCoins(tx, inputs, txundo, nHeight);
    1216                 :    2998602 : }
    1217                 :            : 
    1218                 :     314998 : bool CScriptCheck::operator()() {
    1219                 :     314998 :     const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
    1220                 :     314998 :     const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
    1221                 :     629996 :     return VerifyScript(scriptSig, m_tx_out.scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, m_tx_out.nValue, cacheStore, *txdata), &error);
    1222                 :            : }
    1223                 :            : 
    1224                 :      55245 : int GetSpendHeight(const CCoinsViewCache& inputs)
    1225                 :            : {
    1226         [ #  # ]:      55245 :     LOCK(cs_main);
    1227         [ +  - ]:      55245 :     CBlockIndex* pindexPrev = LookupBlockIndex(inputs.GetBestBlock());
    1228         [ +  - ]:     110490 :     return pindexPrev->nHeight + 1;
    1229                 :            : }
    1230                 :            : 
    1231                 :            : 
    1232                 :            : static CuckooCache::cache<uint256, SignatureCacheHasher> scriptExecutionCache;
    1233                 :            : static uint256 scriptExecutionCacheNonce(GetRandHash());
    1234                 :            : 
    1235                 :        772 : void InitScriptExecutionCache() {
    1236                 :            :     // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
    1237                 :            :     // setup_bytes creates the minimum possible cache (2 elements).
    1238 [ +  - ][ +  - ]:       3088 :     size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
         [ -  + ][ +  - ]
                 [ #  # ]
    1239                 :        772 :     size_t nElems = scriptExecutionCache.setup_bytes(nMaxCacheSize);
    1240                 :       1544 :     LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
    1241                 :        772 :             (nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
    1242                 :        772 : }
    1243                 :            : 
    1244                 :            : /**
    1245                 :            :  * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
    1246                 :            :  * This does not modify the UTXO set.
    1247                 :            :  *
    1248                 :            :  * If pvChecks is not nullptr, script checks are pushed onto it instead of being performed inline. Any
    1249                 :            :  * script checks which are not necessary (eg due to script execution cache hits) are, obviously,
    1250                 :            :  * not pushed onto pvChecks/run.
    1251                 :            :  *
    1252                 :            :  * Setting cacheSigStore/cacheFullScriptStore to false will remove elements from the corresponding cache
    1253                 :            :  * which are matched. This is useful for checking blocks where we will likely never need the cache
    1254                 :            :  * entry again.
    1255                 :            :  *
    1256                 :            :  * Note that we may set state.reason to NOT_STANDARD for extra soft-fork flags in flags, block-checking
    1257                 :            :  * callers should probably reset it to CONSENSUS in such cases.
    1258                 :            :  *
    1259                 :            :  * Non-static (and re-declared) in src/test/txvalidationcache_tests.cpp
    1260                 :            :  */
    1261                 :     345103 : bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
    1262                 :            : {
    1263         [ +  + ]:     345103 :     if (!tx.IsCoinBase())
    1264                 :            :     {
    1265         [ +  + ]:     345103 :         if (pvChecks)
    1266                 :     366330 :             pvChecks->reserve(tx.vin.size());
    1267                 :            : 
    1268                 :            :         // The first loop above does all the inexpensive checks.
    1269                 :            :         // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
    1270                 :            :         // Helps prevent CPU exhaustion attacks.
    1271                 :            : 
    1272                 :            :         // Skip script verification when connecting blocks under the
    1273                 :            :         // assumevalid block. Assuming the assumevalid block is valid this
    1274                 :            :         // is safe because block merkle hashes are still computed and checked,
    1275                 :            :         // Of course, if an assumed valid block is invalid due to false scriptSigs
    1276                 :            :         // this optimization would allow an invalid chain to be accepted.
    1277         [ +  + ]:     345103 :         if (fScriptChecks) {
    1278                 :            :             // First check if script executions have been cached with the same
    1279                 :            :             // flags. Note that this assumes that the inputs provided are
    1280                 :            :             // correct (ie that the transaction hash which is in tx's prevouts
    1281                 :            :             // properly commits to the scriptPubKey in the inputs view of that
    1282                 :            :             // transaction).
    1283                 :     345102 :             uint256 hashCacheEntry;
    1284                 :            :             // We only use the first 19 bytes of nonce to avoid a second SHA
    1285                 :            :             // round - giving us 19 + 32 + 4 = 55 bytes (+ 8 + 1 = 64)
    1286                 :     345102 :             static_assert(55 - sizeof(flags) - 32 >= 128/8, "Want at least 128 bits of nonce for script execution cache");
    1287                 :     345102 :             CSHA256().Write(scriptExecutionCacheNonce.begin(), 55 - sizeof(flags) - 32).Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
    1288                 :     345102 :             AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
    1289         [ +  + ]:     345102 :             if (scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
    1290                 :            :                 return true;
    1291                 :            :             }
    1292                 :            : 
    1293 [ +  + ][ +  + ]:    1015956 :             for (unsigned int i = 0; i < tx.vin.size(); i++) {
    1294                 :     312698 :                 const COutPoint &prevout = tx.vin[i].prevout;
    1295                 :     312698 :                 const Coin& coin = inputs.AccessCoin(prevout);
    1296   [ -  +  -  + ]:     625396 :                 assert(!coin.IsSpent());
    1297                 :            : 
    1298                 :            :                 // We very carefully only pass in things to CScriptCheck which
    1299                 :            :                 // are clearly committed to by tx' witness hash. This provides
    1300                 :            :                 // a sanity check that our caching is not introducing consensus
    1301                 :            :                 // failures through additional data in, eg, the coins being
    1302                 :            :                 // spent being checked as a part of CScriptCheck.
    1303                 :            : 
    1304                 :            :                 // Verify signature
    1305 [ +  + ][ #  # ]:     585455 :                 CScriptCheck check(coin.out, tx, i, flags, cacheSigStore, &txdata);
    1306         [ +  + ]:     312698 :                 if (pvChecks) {
    1307 [ +  - ][ -  + ]:     118400 :                     pvChecks->push_back(CScriptCheck());
                 [ #  # ]
    1308                 :     236800 :                     check.swap(pvChecks->back());
    1309 [ +  - ][ +  + ]:     194298 :                 } else if (!check()) {
    1310         [ +  + ]:      63283 :                     if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
    1311                 :            :                         // Check whether the failure was caused by a
    1312                 :            :                         // non-mandatory script verification check, such as
    1313                 :            :                         // non-standard DER encodings or non-null dummy
    1314                 :            :                         // arguments; if so, ensure we return NOT_STANDARD
    1315                 :            :                         // instead of CONSENSUS to avoid downstream users
    1316                 :            :                         // splitting the network between upgraded and
    1317                 :            :                         // non-upgraded nodes by banning CONSENSUS-failing
    1318                 :            :                         // data providers.
    1319                 :     126562 :                         CScriptCheck check2(coin.out, tx, i,
    1320 [ -  + ][ #  # ]:      79675 :                                 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
    1321 [ +  + ][ +  - ]:      63281 :                         if (check2())
    1322 [ +  - ][ +  - ]:     187548 :                             return state.Invalid(ValidationInvalidReason::TX_NOT_STANDARD, false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ +  - ][ -  + ]
         [ +  + ][ +  + ]
         [ #  # ][ #  # ]
    1323                 :            :                     }
    1324                 :            :                     // MANDATORY flag failures correspond to
    1325                 :            :                     // ValidationInvalidReason::CONSENSUS. Because CONSENSUS
    1326                 :            :                     // failures are the most serious case of validation
    1327                 :            :                     // failures, we may need to consider using
    1328                 :            :                     // RECENT_CONSENSUS_CHANGE for any script failure that
    1329                 :            :                     // could be due to non-upgraded nodes which we may want to
    1330                 :            :                     // support, to avoid splitting the network (but this
    1331                 :            :                     // depends on the details of how net_processing handles
    1332                 :            :                     // such errors).
    1333 [ +  - ][ +  - ]:      65584 :                     return state.Invalid(ValidationInvalidReason::CONSENSUS, false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ +  - ][ -  + ]
         [ #  # ][ #  # ]
    1334                 :            :                 }
    1335                 :            :             }
    1336                 :            : 
    1337         [ +  + ]:     195280 :             if (cacheFullScriptStore && !pvChecks) {
    1338                 :            :                 // We executed all of the provided scripts, and were told to
    1339                 :            :                 // cache the result. Do so now.
    1340                 :      79792 :                 scriptExecutionCache.insert(hashCacheEntry);
    1341                 :            :             }
    1342                 :            :         }
    1343                 :            :     }
    1344                 :            : 
    1345                 :            :     return true;
    1346                 :            : }
    1347                 :            : 
    1348                 :      31411 : static bool UndoWriteToDisk(const CBlockUndo& blockundo, FlatFilePos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
    1349                 :            : {
    1350                 :            :     // Open history file to append
    1351 [ -  + ][ +  - ]:      94233 :     CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
                 [ #  # ]
    1352   [ -  +  -  + ]:      62822 :     if (fileout.IsNull())
    1353         [ #  # ]:          0 :         return error("%s: OpenUndoFile failed", __func__);
    1354                 :            : 
    1355                 :            :     // Write index header
    1356 [ +  - ][ +  - ]:      62822 :     unsigned int nSize = GetSerializeSize(blockundo, fileout.GetVersion());
    1357 [ +  - ][ +  - ]:      31411 :     fileout << messageStart << nSize;
    1358                 :            : 
    1359                 :            :     // Write undo data
    1360 [ +  - ][ +  - ]:      62822 :     long fileOutPos = ftell(fileout.Get());
    1361         [ -  + ]:      31411 :     if (fileOutPos < 0)
    1362         [ #  # ]:          0 :         return error("%s: ftell failed", __func__);
    1363                 :      31411 :     pos.nPos = (unsigned int)fileOutPos;
    1364         [ +  - ]:      31411 :     fileout << blockundo;
    1365                 :            : 
    1366                 :            :     // calculate & write checksum
    1367         [ +  - ]:      31411 :     CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
    1368         [ +  - ]:      31411 :     hasher << hashBlock;
    1369         [ +  - ]:      31411 :     hasher << blockundo;
    1370 [ +  - ][ +  - ]:      31411 :     fileout << hasher.GetHash();
    1371                 :            : 
    1372                 :            :     return true;
    1373                 :            : }
    1374                 :            : 
    1375                 :       6174 : bool UndoReadFromDisk(CBlockUndo& blockundo, const CBlockIndex* pindex)
    1376                 :            : {
    1377         [ +  - ]:       6174 :     FlatFilePos pos = pindex->GetUndoPos();
    1378 [ -  + ][ -  + ]:      12348 :     if (pos.IsNull()) {
    1379                 :          0 :         return error("%s: no undo data available", __func__);
    1380                 :            :     }
    1381                 :            : 
    1382                 :            :     // Open history file to read
    1383 [ +  + ][ +  + ]:      12348 :     CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
                 [ #  # ]
    1384   [ +  +  +  + ]:      12348 :     if (filein.IsNull())
    1385         [ +  - ]:          1 :         return error("%s: OpenUndoFile failed", __func__);
    1386                 :            : 
    1387                 :            :     // Read block
    1388         [ +  - ]:       6173 :     uint256 hashChecksum;
    1389         [ +  - ]:       6173 :     CHashVerifier<CAutoFile> verifier(&filein); // We need a CHashVerifier as reserializing may lose data
    1390                 :       6173 :     try {
    1391 [ +  - ][ +  - ]:      12346 :         verifier << pindex->pprev->GetBlockHash();
    1392         [ +  + ]:       6173 :         verifier >> blockundo;
    1393         [ +  - ]:       6172 :         filein >> hashChecksum;
    1394                 :            :     }
    1395                 :          2 :     catch (const std::exception& e) {
    1396         [ +  - ]:          1 :         return error("%s: Deserialize or I/O error - %s", __func__, e.what());
    1397                 :            :     }
    1398                 :            : 
    1399                 :            :     // Verify checksum
    1400 [ +  - ][ -  + ]:       6172 :     if (hashChecksum != verifier.GetHash())
                 [ -  + ]
    1401         [ #  # ]:          0 :         return error("%s: Checksum mismatch", __func__);
    1402                 :            : 
    1403                 :            :     return true;
    1404                 :            : }
    1405                 :            : 
    1406                 :            : /** Abort with a message */
    1407                 :          1 : static bool AbortNode(const std::string& strMessage, const std::string& userMessage = "", unsigned int prefix = 0)
    1408                 :            : {
    1409                 :          1 :     SetMiscWarning(strMessage);
    1410                 :          1 :     LogPrintf("*** %s\n", strMessage);
    1411   [ -  +  -  + ]:          2 :     if (!userMessage.empty()) {
    1412 [ #  # ][ #  # ]:          0 :         uiInterface.ThreadSafeMessageBox(userMessage, "", CClientUIInterface::MSG_ERROR | prefix);
                 [ #  # ]
    1413                 :            :     } else {
    1414 [ +  - ][ +  - ]:          2 :         uiInterface.ThreadSafeMessageBox(_("Error: A fatal internal error occurred, see debug.log for details").translated, "", CClientUIInterface::MSG_ERROR | CClientUIInterface::MSG_NOPREFIX);
         [ -  + ][ #  # ]
    1415                 :            :     }
    1416                 :          1 :     StartShutdown();
    1417                 :          1 :     return false;
    1418                 :            : }
    1419                 :            : 
    1420                 :          1 : static bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage = "", unsigned int prefix = 0)
    1421                 :            : {
    1422                 :          1 :     AbortNode(strMessage, userMessage, prefix);
    1423         [ +  - ]:          1 :     return state.Error(strMessage);
    1424                 :            : }
    1425                 :            : 
    1426                 :            : /**
    1427                 :            :  * Restore the UTXO in a Coin at a given COutPoint
    1428                 :            :  * @param undo The Coin to be restored.
    1429                 :            :  * @param view The coins view to which to apply the changes.
    1430                 :            :  * @param out The out point that corresponds to the tx input.
    1431                 :            :  * @return A DisconnectResult as an int
    1432                 :            :  */
    1433                 :      16431 : int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
    1434                 :            : {
    1435                 :      16431 :     bool fClean = true;
    1436                 :            : 
    1437         [ -  + ]:      16431 :     if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
    1438                 :            : 
    1439         [ -  + ]:      16431 :     if (undo.nHeight == 0) {
    1440                 :            :         // Missing undo metadata (height and coinbase). Older versions included this
    1441                 :            :         // information only in undo records for the last spend of a transactions'
    1442                 :            :         // outputs. This implies that it must be present for some other output of the same tx.
    1443                 :          0 :         const Coin& alternate = AccessByTxid(view, out.hash);
    1444   [ #  #  #  # ]:          0 :         if (!alternate.IsSpent()) {
    1445                 :          0 :             undo.nHeight = alternate.nHeight;
    1446                 :          0 :             undo.fCoinBase = alternate.fCoinBase;
    1447                 :            :         } else {
    1448                 :            :             return DISCONNECT_FAILED; // adding output for transaction without known metadata
    1449                 :            :         }
    1450                 :            :     }
    1451                 :            :     // The potential_overwrite parameter to AddCoin is only allowed to be false if we know for
    1452                 :            :     // sure that the coin did not already exist in the cache. As we have queried for that above
    1453                 :            :     // using HaveCoin, we don't need to guess. When fClean is false, a coin already existed and
    1454                 :            :     // it is an overwrite.
    1455                 :      16431 :     view.AddCoin(out, std::move(undo), !fClean);
    1456                 :            : 
    1457         [ -  + ]:      16431 :     return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
    1458                 :            : }
    1459                 :            : 
    1460                 :            : /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
    1461                 :            :  *  When FAILED is returned, view is left in an indeterminate state. */
    1462                 :       4560 : DisconnectResult CChainState::DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
    1463                 :            : {
    1464                 :       4560 :     bool fClean = true;
    1465                 :            : 
    1466         [ +  - ]:       9120 :     CBlockUndo blockUndo;
    1467 [ +  - ][ +  + ]:       4560 :     if (!UndoReadFromDisk(blockUndo, pindex)) {
    1468         [ +  - ]:          1 :         error("DisconnectBlock(): failure reading undo data");
    1469                 :            :         return DISCONNECT_FAILED;
    1470                 :            :     }
    1471                 :            : 
    1472 [ -  + ][ -  + ]:      13677 :     if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
                 [ -  + ]
    1473         [ #  # ]:          0 :         error("DisconnectBlock(): block and undo data inconsistent");
    1474                 :            :         return DISCONNECT_FAILED;
    1475                 :            :     }
    1476                 :            : 
    1477                 :            :     // undo transactions in reverse order
    1478         [ +  + ]:      16016 :     for (int i = block.vtx.size() - 1; i >= 0; i--) {
    1479 [ +  + ][ +  + ]:      22914 :         const CTransaction &tx = *(block.vtx[i]);
    1480         [ +  + ]:      11457 :         uint256 hash = tx.GetHash();
    1481         [ +  + ]:      11457 :         bool is_coinbase = tx.IsCoinBase();
    1482                 :            : 
    1483                 :            :         // Check that all outputs are available and match the outputs in the block itself
    1484                 :            :         // exactly.
    1485 [ +  + ][ +  + ]:      36487 :         for (size_t o = 0; o < tx.vout.size(); o++) {
    1486 [ +  + ][ +  + ]:      50060 :             if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
    1487                 :      14405 :                 COutPoint out(hash, o);
    1488 [ +  + ][ #  # ]:      28810 :                 Coin coin;
    1489         [ +  - ]:      14405 :                 bool is_spent = view.SpendCoin(out, &coin);
    1490 [ +  - ][ +  - ]:      28810 :                 if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
         [ +  - ][ +  - ]
                 [ +  - ]
    1491                 :            :                     fClean = false; // transaction output mismatch
    1492                 :            :                 }
    1493                 :            :             }
    1494                 :            :         }
    1495                 :            : 
    1496                 :            :         // restore inputs
    1497         [ +  + ]:      11457 :         if (i > 0) { // not coinbases
    1498         [ -  + ]:       6898 :             CTxUndo &txundo = blockUndo.vtxundo[i-1];
    1499 [ -  + ][ -  + ]:      20694 :             if (txundo.vprevout.size() != tx.vin.size()) {
                 [ -  + ]
    1500         [ #  # ]:          0 :                 error("DisconnectBlock(): transaction and undo data inconsistent");
    1501                 :            :                 return DISCONNECT_FAILED;
    1502                 :            :             }
    1503         [ +  + ]:      21565 :             for (unsigned int j = tx.vin.size(); j-- > 0;) {
    1504         [ +  - ]:      14667 :                 const COutPoint &out = tx.vin[j].prevout;
    1505 [ +  - ][ +  - ]:      29334 :                 int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
    1506         [ +  - ]:      14667 :                 if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
    1507                 :      14667 :                 fClean = fClean && res != DISCONNECT_UNCLEAN;
    1508                 :            :             }
    1509                 :            :             // At this point, all of txundo.vprevout should have been moved out.
    1510                 :            :         }
    1511                 :            :     }
    1512                 :            : 
    1513                 :            :     // move best block pointer to prevout block
    1514 [ +  - ][ +  - ]:       9118 :     view.SetBestBlock(pindex->pprev->GetBlockHash());
    1515                 :            : 
    1516         [ -  + ]:       4559 :     return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
    1517                 :            : }
    1518                 :            : 
    1519                 :       1010 : void static FlushBlockFile(bool fFinalize = false)
    1520                 :            : {
    1521 [ +  - ][ #  # ]:       2020 :     LOCK(cs_LastBlockFile);
    1522                 :            : 
    1523   [ +  -  +  - ]:       2020 :     FlatFilePos block_pos_old(nLastBlockFile, vinfoBlockFile[nLastBlockFile].nSize);
    1524         [ +  - ]:       1010 :     FlatFilePos undo_pos_old(nLastBlockFile, vinfoBlockFile[nLastBlockFile].nUndoSize);
    1525                 :            : 
    1526                 :       1010 :     bool status = true;
    1527 [ +  - ][ +  - ]:       1010 :     status &= BlockFileSeq().Flush(block_pos_old, fFinalize);
         [ #  # ][ +  - ]
    1528 [ +  - ][ +  - ]:       1010 :     status &= UndoFileSeq().Flush(undo_pos_old, fFinalize);
         [ +  - ][ #  # ]
    1529         [ -  + ]:       1010 :     if (!status) {
    1530 [ #  # ][ #  # ]:          0 :         AbortNode("Flushing block file to disk failed. This is likely the result of an I/O error.");
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
                 [ #  # ]
    1531                 :            :     }
    1532                 :       1010 : }
    1533                 :            : 
    1534                 :            : static bool FindUndoPos(CValidationState &state, int nFile, FlatFilePos &pos, unsigned int nAddSize);
    1535                 :            : 
    1536                 :      32964 : static bool WriteUndoDataForBlock(const CBlockUndo& blockundo, CValidationState& state, CBlockIndex* pindex, const CChainParams& chainparams)
    1537                 :            : {
    1538                 :            :     // Write undo information to disk
    1539 [ +  + ][ +  + ]:      36070 :     if (pindex->GetUndoPos().IsNull()) {
                 [ +  + ]
    1540                 :      31411 :         FlatFilePos _pos;
    1541         [ -  + ]:      31411 :         if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, CLIENT_VERSION) + 40))
    1542                 :          0 :             return error("ConnectBlock(): FindUndoPos failed");
    1543         [ -  + ]:      94233 :         if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
    1544   [ #  #  #  # ]:          0 :             return AbortNode(state, "Failed to write undo data");
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
                 [ #  # ]
    1545                 :            : 
    1546                 :            :         // update nUndoPos in block index
    1547                 :      31411 :         pindex->nUndoPos = _pos.nPos;
    1548                 :      31411 :         pindex->nStatus |= BLOCK_HAVE_UNDO;
    1549                 :      31411 :         setDirtyBlockIndex.insert(pindex);
    1550                 :            :     }
    1551                 :            : 
    1552                 :            :     return true;
    1553                 :            : }
    1554                 :            : 
    1555                 :            : static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
    1556                 :            : 
    1557                 :       2908 : void ThreadScriptCheck(int worker_num) {
    1558 [ +  - ][ -  + ]:       2908 :     util::ThreadRename(strprintf("scriptch.%i", worker_num));
                 [ #  # ]
    1559                 :       2908 :     scriptcheckqueue.Thread();
    1560                 :          0 : }
    1561                 :            : 
    1562                 :            : VersionBitsCache versionbitscache GUARDED_BY(cs_main);
    1563                 :            : 
    1564                 :    2624135 : int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
    1565                 :            : {
    1566         [ #  # ]:          0 :     LOCK(cs_main);
    1567                 :    2624135 :     int32_t nVersion = VERSIONBITS_TOP_BITS;
    1568                 :            : 
    1569         [ +  + ]:   10496540 :     for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
    1570         [ +  - ]:    7872405 :         ThresholdState state = VersionBitsState(pindexPrev, params, static_cast<Consensus::DeploymentPos>(i), versionbitscache);
    1571         [ +  + ]:    7872405 :         if (state == ThresholdState::LOCKED_IN || state == ThresholdState::STARTED) {
    1572         [ +  - ]:    2863394 :             nVersion |= VersionBitsMask(params, static_cast<Consensus::DeploymentPos>(i));
    1573                 :            :         }
    1574                 :            :     }
    1575                 :            : 
    1576         [ +  - ]:    5248270 :     return nVersion;
    1577                 :            : }
    1578                 :            : 
    1579                 :            : /**
    1580                 :            :  * Threshold condition checker that triggers when unknown versionbits are seen on the network.
    1581                 :            :  */
    1582                 :            : class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
    1583                 :            : {
    1584                 :            : private:
    1585                 :            :     int bit;
    1586                 :            : 
    1587                 :            : public:
    1588                 :     897376 :     explicit WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
    1589                 :            : 
    1590                 :     897376 :     int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
    1591                 :     897376 :     int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
    1592                 :     897376 :     int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; }
    1593                 :     897376 :     int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; }
    1594                 :            : 
    1595                 :     379440 :     bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
    1596                 :            :     {
    1597                 :     673139 :         return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
    1598 [ +  + ][ +  + ]:     379440 :                ((pindex->nVersion >> bit) & 1) != 0 &&
    1599         [ +  + ]:      17825 :                ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
    1600                 :            :     }
    1601                 :            : };
    1602                 :            : 
    1603                 :            : static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS] GUARDED_BY(cs_main);
    1604                 :            : 
    1605                 :            : // 0.13.0 was shipped with a segwit deployment defined for testnet, but not for
    1606                 :            : // mainnet. We no longer need to support disabling the segwit deployment
    1607                 :            : // except for testing purposes, due to limitations of the functional test
    1608                 :            : // environment. See test/functional/p2p-segwit.py.
    1609                 :      63733 : static bool IsScriptWitnessEnabled(const Consensus::Params& params)
    1610                 :            : {
    1611                 :      63733 :     return params.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0;
    1612                 :            : }
    1613                 :            : 
    1614                 :      63733 : static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& consensusparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
    1615                 :      63733 :     AssertLockHeld(cs_main);
    1616                 :            : 
    1617                 :      63733 :     unsigned int flags = SCRIPT_VERIFY_NONE;
    1618                 :            : 
    1619                 :            :     // BIP16 didn't become active until Apr 1 2012 (on mainnet, and
    1620                 :            :     // retroactively applied to testnet)
    1621                 :            :     // However, only one historical block violated the P2SH rules (on both
    1622                 :            :     // mainnet and testnet), so for simplicity, always leave P2SH
    1623                 :            :     // on except for the one violating block.
    1624                 :      63733 :     if (consensusparams.BIP16Exception.IsNull() || // no bip16 exception on this chain
    1625 [ +  + ][ +  - ]:      63733 :         pindex->phashBlock == nullptr || // this is a new candidate block, eg from TestBlockValidity()
    1626 [ +  - ][ +  - ]:        254 :         *pindex->phashBlock != consensusparams.BIP16Exception) // this block isn't the historical exception
    1627                 :            :     {
    1628                 :            :         flags |= SCRIPT_VERIFY_P2SH;
    1629                 :            :     }
    1630                 :            : 
    1631                 :            :     // Enforce WITNESS rules whenever P2SH is in effect (and the segwit
    1632                 :            :     // deployment is defined).
    1633 [ +  - ][ +  + ]:      63733 :     if (flags & SCRIPT_VERIFY_P2SH && IsScriptWitnessEnabled(consensusparams)) {
    1634                 :      63140 :         flags |= SCRIPT_VERIFY_WITNESS;
    1635                 :            :     }
    1636                 :            : 
    1637                 :            :     // Start enforcing the DERSIG (BIP66) rule
    1638         [ +  + ]:      63733 :     if (pindex->nHeight >= consensusparams.BIP66Height) {
    1639                 :       1155 :         flags |= SCRIPT_VERIFY_DERSIG;
    1640                 :            :     }
    1641                 :            : 
    1642                 :            :     // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
    1643         [ +  + ]:      63733 :     if (pindex->nHeight >= consensusparams.BIP65Height) {
    1644                 :        854 :         flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
    1645                 :            :     }
    1646                 :            : 
    1647                 :            :     // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
    1648         [ +  + ]:      63733 :     if (VersionBitsState(pindex->pprev, consensusparams, Consensus::DEPLOYMENT_CSV, versionbitscache) == ThresholdState::ACTIVE) {
    1649                 :       4616 :         flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
    1650                 :            :     }
    1651                 :            : 
    1652         [ +  + ]:      63733 :     if (IsNullDummyEnabled(pindex->pprev, consensusparams)) {
    1653                 :      56585 :         flags |= SCRIPT_VERIFY_NULLDUMMY;
    1654                 :            :     }
    1655                 :            : 
    1656                 :      63733 :     return flags;
    1657                 :            : }
    1658                 :            : 
    1659                 :            : 
    1660                 :            : 
    1661                 :            : static int64_t nTimeCheck = 0;
    1662                 :            : static int64_t nTimeForks = 0;
    1663                 :            : static int64_t nTimeVerify = 0;
    1664                 :            : static int64_t nTimeConnect = 0;
    1665                 :            : static int64_t nTimeIndex = 0;
    1666                 :            : static int64_t nTimeCallbacks = 0;
    1667                 :            : static int64_t nTimeTotal = 0;
    1668                 :            : static int64_t nBlocksTotal = 0;
    1669                 :            : 
    1670                 :            : /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
    1671                 :            :  *  Validity checks that depend on the UTXO set are also done; ConnectBlock()
    1672                 :            :  *  can fail if those validity checks fail (among other reasons). */
    1673                 :      47532 : bool CChainState::ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
    1674                 :            :                   CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck)
    1675                 :            : {
    1676                 :      47532 :     AssertLockHeld(cs_main);
    1677         [ -  + ]:      47532 :     assert(pindex);
    1678   [ -  +  -  + ]:      47532 :     assert(*pindex->phashBlock == block.GetHash());
    1679                 :      47532 :     int64_t nTimeStart = GetTimeMicros();
    1680                 :            : 
    1681                 :            :     // Check it again in case a previous version let a bad block in
    1682                 :            :     // NOTE: We don't currently (re-)invoke ContextualCheckBlock() or
    1683                 :            :     // ContextualCheckBlockHeader() here. This means that if we add a new
    1684                 :            :     // consensus rule that is enforced in one of those two functions, then we
    1685                 :            :     // may have let in a block that violates the rule prior to updating the
    1686                 :            :     // software, and we would NOT be enforcing the rule here. Fully solving
    1687                 :            :     // upgrade from one software version to the next after a consensus rule
    1688                 :            :     // change is potentially tricky and issue-specific (see RewindBlockIndex()
    1689                 :            :     // for one general approach that was used for BIP 141 deployment).
    1690                 :            :     // Also, currently the rule against blocks more than 2 hours in the future
    1691                 :            :     // is enforced in ContextualCheckBlockHeader(); we wouldn't want to
    1692                 :            :     // re-enforce that rule here (at least until we make it impossible for
    1693                 :            :     // GetAdjustedTime() to go backward).
    1694         [ -  + ]:      95064 :     if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck)) {
    1695 [ #  # ][ #  # ]:          0 :         if (state.GetReason() == ValidationInvalidReason::BLOCK_MUTATED) {
    1696                 :            :             // We don't write down blocks to disk if they may have been
    1697                 :            :             // corrupted, so this should be impossible unless we're having hardware
    1698                 :            :             // problems.
    1699   [ #  #  #  # ]:          0 :             return AbortNode(state, "Corrupt block found indicating potential hardware failure; shutting down");
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
                 [ #  # ]
    1700                 :            :         }
    1701 [ #  # ][ #  # ]:          0 :         return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
                 [ #  # ]
    1702                 :            :     }
    1703                 :            : 
    1704                 :            :     // verify that the view's current state corresponds to the previous block
    1705         [ +  + ]:      47532 :     uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
    1706   [ -  +  -  + ]:      47532 :     assert(hashPrevBlock == view.GetBestBlock());
    1707                 :            : 
    1708                 :            :     // Special case for the genesis block, skipping connection of its transactions
    1709                 :            :     // (its coinbase is unspendable)
    1710   [ +  +  +  + ]:      95064 :     if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
    1711         [ +  - ]:        222 :         if (!fJustCheck)
    1712                 :        444 :             view.SetBestBlock(pindex->GetBlockHash());
    1713                 :        222 :         return true;
    1714                 :            :     }
    1715                 :            : 
    1716                 :      47310 :     nBlocksTotal++;
    1717                 :            : 
    1718                 :      47310 :     bool fScriptChecks = true;
    1719         [ +  + ]:      94620 :     if (!hashAssumeValid.IsNull()) {
    1720                 :            :         // We've been configured with the hash of a block which has been externally verified to have a valid history.
    1721                 :            :         // A suitable default value is included with the software and updated from time to time.  Because validity
    1722                 :            :         //  relative to a piece of software is an objective fact these defaults can be easily reviewed.
    1723                 :            :         // This setting doesn't force the selection of any particular chain but makes validating some faster by
    1724                 :            :         //  effectively caching the result of part of the verification.
    1725         [ +  - ]:       2304 :         BlockMap::const_iterator  it = m_blockman.m_block_index.find(hashAssumeValid);
    1726   [ +  -  +  - ]:       4608 :         if (it != m_blockman.m_block_index.end()) {
    1727                 :       4608 :             if (it->second->GetAncestor(pindex->nHeight) == pindex &&
    1728 [ +  - ][ +  + ]:       2304 :                 pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
    1729         [ +  - ]:        204 :                 pindexBestHeader->nChainWork >= nMinimumChainWork) {
    1730                 :            :                 // This block is a member of the assumed verified chain and an ancestor of the best header.
    1731                 :            :                 // The equivalent time check discourages hash power from extorting the network via DOS attack
    1732                 :            :                 //  into accepting an invalid block through telling users they must manually set assumevalid.
    1733                 :            :                 //  Requiring a software change or burying the invalid block, regardless of the setting, makes
    1734                 :            :                 //  it hard to hide the implication of the demand.  This also avoids having release candidates
    1735                 :            :                 //  that are hardly doing any signature verification at all in testing without having to
    1736                 :            :                 //  artificially set the default assumed verified block further back.
    1737                 :            :                 // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
    1738                 :            :                 //  least as good as the expected chain.
    1739                 :        408 :                 fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
    1740                 :            :             }
    1741                 :            :         }
    1742                 :            :     }
    1743                 :            : 
    1744                 :      47310 :     int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
    1745                 :      47310 :     LogPrint(BCLog::BENCH, "    - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime1 - nTimeStart), nTimeCheck * MICRO, nTimeCheck * MILLI / nBlocksTotal);
    1746                 :            : 
    1747                 :            :     // Do not allow blocks that contain transactions which 'overwrite' older transactions,
    1748                 :            :     // unless those are already completely spent.
    1749                 :            :     // If such overwrites are allowed, coinbases and transactions depending upon those
    1750                 :            :     // can be duplicated to remove the ability to spend the first instance -- even after
    1751                 :            :     // being sent to another address.
    1752                 :            :     // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
    1753                 :            :     // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
    1754                 :            :     // already refuses previously-known transaction ids entirely.
    1755                 :            :     // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
    1756                 :            :     // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
    1757                 :            :     // two in the chain that violate it. This prevents exploiting the issue against nodes during their
    1758                 :            :     // initial block download.
    1759   [ #  #  #  #  :      47310 :     bool fEnforceBIP30 = !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
           #  # ][ -  + ]
    1760 [ -  + ][ #  #  :      47310 :                            (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
             #  #  #  # ]
    1761                 :            : 
    1762                 :            :     // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
    1763                 :            :     // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs.  But by the
    1764                 :            :     // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
    1765                 :            :     // before the first had been spent.  Since those coinbases are sufficiently buried it's no longer possible to create further
    1766                 :            :     // duplicate transactions descending from the known pairs either.
    1767                 :            :     // If we're on the known chain at height greater than where BIP34 activated, we can save the db accesses needed for the BIP30 check.
    1768                 :            : 
    1769                 :            :     // BIP34 requires that a block at height X (block X) has its coinbase
    1770                 :            :     // scriptSig start with a CScriptNum of X (indicated height X).  The above
    1771                 :            :     // logic of no longer requiring BIP30 once BIP34 activates is flawed in the
    1772                 :            :     // case that there is a block X before the BIP34 height of 227,931 which has
    1773                 :            :     // an indicated height Y where Y is greater than X.  The coinbase for block
    1774                 :            :     // X would also be a valid coinbase for block Y, which could be a BIP30
    1775                 :            :     // violation.  An exhaustive search of all mainnet coinbases before the
    1776                 :            :     // BIP34 height which have an indicated height greater than the block height
    1777                 :            :     // reveals many occurrences. The 3 lowest indicated heights found are
    1778                 :            :     // 209,921, 490,897, and 1,983,702 and thus coinbases for blocks at these 3
    1779                 :            :     // heights would be the first opportunity for BIP30 to be violated.
    1780                 :            : 
    1781                 :            :     // The search reveals a great many blocks which have an indicated height
    1782                 :            :     // greater than 1,983,702, so we simply remove the optimization to skip
    1783                 :            :     // BIP30 checking for blocks at height 1,983,702 or higher.  Before we reach
    1784                 :            :     // that block in another 25 years or so, we should take advantage of a
    1785                 :            :     // future consensus change to do a new and improved version of BIP34 that
    1786                 :            :     // will actually prevent ever creating any duplicate coinbases in the
    1787                 :            :     // future.
    1788                 :      47310 :     static constexpr int BIP34_IMPLIES_BIP30_LIMIT = 1983702;
    1789                 :            : 
    1790                 :            :     // There is no potential to create a duplicate coinbase at block 209,921
    1791                 :            :     // because this is still before the BIP34 height and so explicit BIP30
    1792                 :            :     // checking is still active.
    1793                 :            : 
    1794                 :            :     // The final case is block 176,684 which has an indicated height of
    1795                 :            :     // 490,897. Unfortunately, this issue was not discovered until about 2 weeks
    1796                 :            :     // before block 490,897 so there was not much opportunity to address this
    1797                 :            :     // case other than to carefully analyze it and determine it would not be a
    1798                 :            :     // problem. Block 490,897 was, in fact, mined with a different coinbase than
    1799                 :            :     // block 176,684, but it is important to note that even if it hadn't been or
    1800                 :            :     // is remined on an alternate fork with a duplicate coinbase, we would still
    1801                 :            :     // not run into a BIP30 violation.  This is because the coinbase for 176,684
    1802                 :            :     // is spent in block 185,956 in transaction
    1803                 :            :     // d4f7fbbf92f4a3014a230b2dc70b8058d02eb36ac06b4a0736d9d60eaa9e8781.  This
    1804                 :            :     // spending transaction can't be duplicated because it also spends coinbase
    1805                 :            :     // 0328dd85c331237f18e781d692c92de57649529bd5edf1d01036daea32ffde29.  This
    1806                 :            :     // coinbase has an indicated height of over 4.2 billion, and wouldn't be
    1807                 :            :     // duplicatable until that height, and it's currently impossible to create a
    1808                 :            :     // chain that long. Nevertheless we may wish to consider a future soft fork
    1809                 :            :     // which retroactively prevents block 490,897 from creating a duplicate
    1810                 :            :     // coinbase. The two historical BIP30 violations often provide a confusing
    1811                 :            :     // edge case when manipulating the UTXO and it would be simpler not to have
    1812                 :            :     // another edge case to deal with.
    1813                 :            : 
    1814                 :            :     // testnet3 has no blocks before the BIP34 height with indicated heights
    1815                 :            :     // post BIP34 before approximately height 486,000,000 and presumably will
    1816                 :            :     // be reset before it reaches block 1,983,702 and starts doing unnecessary
    1817                 :            :     // BIP30 checking again.
    1818         [ -  + ]:      47310 :     assert(pindex->pprev);
    1819                 :      94620 :     CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
    1820                 :            :     //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
    1821 [ +  + ][ -  + ]:      47310 :     fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
         [ -  + ][ -  + ]
         [ -  + ][ +  - ]
    1822                 :            : 
    1823                 :            :     // TODO: Remove BIP30 checking from block height 1,983,702 on, once we have a
    1824                 :            :     // consensus change that ensures coinbases at those heights can not
    1825                 :            :     // duplicate earlier coinbases.
    1826         [ #  # ]:          0 :     if (fEnforceBIP30 || pindex->nHeight >= BIP34_IMPLIES_BIP30_LIMIT) {
    1827 [ +  + ][ +  + ]:     243431 :         for (const auto& tx : block.vtx) {
    1828 [ +  + ][ +  + ]:     575077 :             for (size_t o = 0; o < tx->vout.size(); o++) {
                 [ +  + ]
    1829         [ +  + ]:    1082288 :                 if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
    1830   [ +  -  +  - ]:          3 :                     return state.Invalid(ValidationInvalidReason::CONSENSUS, error("ConnectBlock(): tried to overwrite transaction"),
         [ +  - ][ +  - ]
         [ -  + ][ -  + ]
         [ -  + ][ #  # ]
         [ #  # ][ #  # ]
    1831                 :            :                                      REJECT_INVALID, "bad-txns-BIP30");
    1832                 :            :                 }
    1833                 :            :             }
    1834                 :            :         }
    1835                 :            :     }
    1836                 :            : 
    1837                 :            :     // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
    1838                 :      47309 :     int nLockTimeFlags = 0;
    1839         [ +  + ]:      94618 :     if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == ThresholdState::ACTIVE) {
    1840                 :       4468 :         nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
    1841                 :            :     }
    1842                 :            : 
    1843                 :            :     // Get the script flags for this block
    1844                 :      94618 :     unsigned int flags = GetBlockScriptFlags(pindex, chainparams.GetConsensus());
    1845                 :            : 
    1846                 :      47309 :     int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
    1847                 :      47309 :     LogPrint(BCLog::BENCH, "    - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime2 - nTime1), nTimeForks * MICRO, nTimeForks * MILLI / nBlocksTotal);
    1848                 :            : 
    1849         [ +  + ]:      47309 :     CBlockUndo blockundo;
    1850                 :            : 
    1851 [ +  + ][ +  + ]:      99922 :     CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : nullptr);
                 [ +  + ]
    1852                 :            : 
    1853 [ +  - ][ #  # ]:      94618 :     std::vector<int> prevheights;
    1854                 :      47309 :     CAmount nFees = 0;
    1855                 :      47309 :     int nInputs = 0;
    1856                 :      47309 :     int64_t nSigOpsCost = 0;
    1857 [ +  - ][ +  - ]:      94618 :     blockundo.vtxundo.reserve(block.vtx.size() - 1);
    1858 [ +  - ][ +  - ]:     141927 :     std::vector<PrecomputedTransactionData> txdata;
         [ +  + ][ #  # ]
    1859 [ +  - ][ +  - ]:      94618 :     txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
    1860 [ +  + ][ +  + ]:     297522 :     for (unsigned int i = 0; i < block.vtx.size(); i++)
    1861                 :            :     {
    1862 [ +  + ][ +  + ]:     202998 :         const CTransaction &tx = *(block.vtx[i]);
    1863                 :            : 
    1864         [ +  + ]:     101499 :         nInputs += tx.vin.size();
    1865                 :            : 
    1866         [ +  + ]:     101499 :         if (!tx.IsCoinBase())
    1867                 :            :         {
    1868                 :      54190 :             CAmount txfee = 0;
    1869 [ +  - ][ +  + ]:      54190 :             if (!Consensus::CheckTxInputs(tx, state, view, pindex->nHeight, txfee)) {
    1870 [ +  + ][ +  + ]:         84 :                 if (!IsBlockReason(state.GetReason())) {
                 [ +  + ]
    1871                 :            :                     // CheckTxInputs may return MISSING_INPUTS or
    1872                 :            :                     // PREMATURE_SPEND but we can't return that, as it's not
    1873                 :            :                     // defined for a block, so we reset the reason flag to
    1874                 :            :                     // CONSENSUS here.
    1875         [ +  - ]:         26 :                     state.Invalid(ValidationInvalidReason::CONSENSUS, false,
    1876 [ +  - ][ +  - ]:         78 :                             state.GetRejectCode(), state.GetRejectReason(), state.GetDebugMessage());
         [ +  - ][ +  - ]
         [ +  - ][ #  # ]
                 [ #  # ]
    1877                 :            :                 }
    1878 [ +  - ][ +  - ]:         56 :                 return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), FormatStateMessage(state));
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
    1879                 :            :             }
    1880                 :      54162 :             nFees += txfee;
    1881 [ -  + ][ -  + ]:     108324 :             if (!MoneyRange(nFees)) {
    1882 [ #  # ][ #  # ]:          0 :                 return state.Invalid(ValidationInvalidReason::CONSENSUS, error("%s: accumulated fee in the block out of range.", __func__),
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
    1883                 :            :                                  REJECT_INVALID, "bad-txns-accumulated-fee-outofrange");
    1884                 :            :             }
    1885                 :            : 
    1886                 :            :             // Check that transaction is BIP68 final
    1887                 :            :             // BIP68 lock checks (as opposed to nLockTime checks) must
    1888                 :            :             // be in ConnectBlock because they require the UTXO set
    1889 [ +  - ][ +  - ]:     108324 :             prevheights.resize(tx.vin.size());
    1890 [ +  + ][ +  + ]:     280698 :             for (size_t j = 0; j < tx.vin.size(); j++) {
    1891 [ +  - ][ +  - ]:     172374 :                 prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
    1892                 :            :             }
    1893                 :            : 
    1894 [ +  - ][ +  + ]:      54162 :             if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
    1895 [ +  - ][ +  - ]:         60 :                 return state.Invalid(ValidationInvalidReason::CONSENSUS, error("%s: contains a non-BIP68-final transaction", __func__),
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ +  - ][ -  + ]
         [ -  + ][ #  # ]
         [ #  # ][ #  # ]
    1896                 :            :                                  REJECT_INVALID, "bad-txns-nonfinal");
    1897                 :            :             }
    1898                 :            :         }
    1899                 :            : 
    1900                 :            :         // GetTransactionSigOpCost counts 3 types of sigops:
    1901                 :            :         // * legacy (always)
    1902                 :            :         // * p2sh (when P2SH enabled in flags and excludes coinbase)
    1903                 :            :         // * witness (when witness enabled in flags and excludes coinbase)
    1904         [ +  - ]:     101459 :         nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
    1905         [ +  + ]:     101459 :         if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
    1906 [ +  - ][ +  - ]:         15 :             return state.Invalid(ValidationInvalidReason::CONSENSUS, error("ConnectBlock(): too many sigops"),
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ -  + ][ -  + ]
         [ -  + ][ #  # ]
         [ #  # ][ #  # ]
    1907                 :            :                              REJECT_INVALID, "bad-blk-sigops");
    1908                 :            : 
    1909         [ +  - ]:     101454 :         txdata.emplace_back(tx);
    1910         [ +  + ]:     101454 :         if (!tx.IsCoinBase())
    1911                 :            :         {
    1912         [ +  + ]:      54145 :             std::vector<CScriptCheck> vChecks;
    1913                 :      54145 :             bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
    1914 [ +  + ][ +  - ]:      54157 :             if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : nullptr)) {
         [ +  - ][ +  + ]
    1915 [ +  - ][ +  - ]:          4 :                 if (state.GetReason() == ValidationInvalidReason::TX_NOT_STANDARD) {
    1916                 :            :                     // CheckInputs may return NOT_STANDARD for extra flags we passed,
    1917                 :            :                     // but we can't return that, as it's not defined for a block, so
    1918                 :            :                     // we reset the reason flag to CONSENSUS here.
    1919                 :            :                     // In the event of a future soft-fork, we may need to
    1920                 :            :                     // consider whether rewriting to CONSENSUS or
    1921                 :            :                     // RECENT_CONSENSUS_CHANGE would be more appropriate.
    1922         [ +  - ]:          2 :                     state.Invalid(ValidationInvalidReason::CONSENSUS, false,
    1923 [ +  - ][ +  - ]:          6 :                               state.GetRejectCode(), state.GetRejectReason(), state.GetDebugMessage());
         [ +  - ][ +  - ]
         [ -  + ][ #  # ]
                 [ #  # ]
    1924                 :            :                 }
    1925         [ +  - ]:          2 :                 return error("ConnectBlock(): CheckInputs on %s failed with %s",
    1926 [ +  - ][ +  - ]:          8 :                     tx.GetHash().ToString(), FormatStateMessage(state));
         [ +  - ][ +  - ]
         [ +  - ][ #  # ]
                 [ #  # ]
    1927                 :            :             }
    1928         [ +  + ]:     108281 :             control.Add(vChecks);
    1929                 :            :         }
    1930                 :            : 
    1931         [ +  + ]:     202904 :         CTxUndo undoDummy;
    1932         [ +  + ]:     101452 :         if (i > 0) {
    1933 [ +  - ][ +  - ]:     108286 :             blockundo.vtxundo.push_back(CTxUndo());
    1934                 :            :         }
    1935 [ +  + ][ +  - ]:     101452 :         UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
    1936                 :            :     }
    1937         [ +  - ]:      47262 :     int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
    1938 [ +  + ][ +  - ]:      47262 :     LogPrint(BCLog::BENCH, "      - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs (%.2fms/blk)]\n", (unsigned)block.vtx.size(), MILLI * (nTime3 - nTime2), MILLI * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : MILLI * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * MICRO, nTimeConnect * MILLI / nBlocksTotal);
                 [ +  - ]
    1939                 :            : 
    1940         [ +  - ]:      47262 :     CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
    1941 [ +  - ][ +  - ]:     141786 :     if (block.vtx[0]->GetValueOut() > blockReward)
         [ +  - ][ +  + ]
    1942 [ +  - ][ +  - ]:         20 :         return state.Invalid(ValidationInvalidReason::CONSENSUS,
         [ +  - ][ +  - ]
         [ +  - ][ -  + ]
         [ -  + ][ -  + ]
         [ #  # ][ #  # ]
                 [ #  # ]
    1943                 :          5 :                          error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
    1944 [ +  - ][ +  - ]:         15 :                                block.vtx[0]->GetValueOut(), blockReward),
         [ +  - ][ +  - ]
    1945                 :            :                                REJECT_INVALID, "bad-cb-amount");
    1946                 :            : 
    1947 [ +  + ][ +  + ]:      89212 :     if (!control.Wait())
    1948 [ +  - ][ +  - ]:        605 :         return state.Invalid(ValidationInvalidReason::CONSENSUS, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ +  - ][ -  + ]
         [ -  + ][ #  # ]
         [ #  # ][ #  # ]
    1949         [ +  - ]:      47136 :     int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
    1950 [ +  + ][ +  - ]:      47136 :     LogPrint(BCLog::BENCH, "    - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n", nInputs - 1, MILLI * (nTime4 - nTime2), nInputs <= 1 ? 0 : MILLI * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * MICRO, nTimeVerify * MILLI / nBlocksTotal);
    1951                 :            : 
    1952         [ +  + ]:      47136 :     if (fJustCheck)
    1953                 :            :         return true;
    1954                 :            : 
    1955 [ +  - ][ +  - ]:      32964 :     if (!WriteUndoDataForBlock(blockundo, state, pindex, chainparams))
    1956                 :            :         return false;
    1957                 :            : 
    1958 [ +  - ][ +  + ]:      32964 :     if (!pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
    1959                 :      31411 :         pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
    1960         [ +  - ]:      31411 :         setDirtyBlockIndex.insert(pindex);
    1961                 :            :     }
    1962                 :            : 
    1963         [ -  + ]:      32964 :     assert(pindex->phashBlock);
    1964                 :            :     // add this block to the view's block chain
    1965 [ +  - ][ +  - ]:      65928 :     view.SetBestBlock(pindex->GetBlockHash());
    1966                 :            : 
    1967         [ +  - ]:      32964 :     int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
    1968         [ +  - ]:      32964 :     LogPrint(BCLog::BENCH, "    - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime5 - nTime4), nTimeIndex * MICRO, nTimeIndex * MILLI / nBlocksTotal);
    1969                 :            : 
    1970         [ +  - ]:      32964 :     int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
    1971         [ +  - ]:      32964 :     LogPrint(BCLog::BENCH, "    - Callbacks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime6 - nTime5), nTimeCallbacks * MICRO, nTimeCallbacks * MILLI / nBlocksTotal);
    1972                 :            : 
    1973                 :            :     return true;
    1974                 :            : }
    1975                 :            : 
    1976                 :     117073 : bool CChainState::FlushStateToDisk(
    1977                 :            :     const CChainParams& chainparams,
    1978                 :            :     CValidationState &state,
    1979                 :            :     FlushStateMode mode,
    1980                 :            :     int nManualPruneHeight)
    1981                 :            : {
    1982                 :     117073 :     int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
    1983         [ #  # ]:     234146 :     LOCK(cs_main);
    1984                 :     117073 :     static int64_t nLastWrite = 0;
    1985                 :     117073 :     static int64_t nLastFlush = 0;
    1986 [ +  - ][ +  - ]:     234146 :     std::set<int> setFilesToPrune;
    1987                 :     117073 :     bool full_flush_completed = false;
    1988                 :     117073 :     try {
    1989                 :     117073 :     {
    1990                 :     117073 :         bool fFlushForPrune = false;
    1991                 :     117073 :         bool fDoFullFlush = false;
    1992 [ +  - ][ #  # ]:     234146 :         LOCK(cs_LastBlockFile);
                 [ +  - ]
    1993 [ +  + ][ +  + ]:     117073 :         if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
         [ -  + ][ +  - ]
                 [ +  - ]
    1994         [ -  + ]:          6 :             if (nManualPruneHeight > 0) {
    1995         [ #  # ]:          0 :                 FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
    1996                 :            :             } else {
    1997 [ +  - ][ +  - ]:         12 :                 FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
    1998                 :          6 :                 fCheckForPruning = false;
    1999                 :            :             }
    2000 [ -  + ][ -  + ]:         12 :             if (!setFilesToPrune.empty()) {
    2001                 :          0 :                 fFlushForPrune = true;
    2002         [ #  # ]:          0 :                 if (!fHavePruned) {
    2003 [ #  # ][ #  # ]:          0 :                     pblocktree->WriteFlag("prunedblockfiles", true);
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
    2004                 :          0 :                     fHavePruned = true;
    2005                 :            :                 }
    2006                 :            :             }
    2007                 :            :         }
    2008         [ +  - ]:     117073 :         int64_t nNow = GetTimeMicros();
    2009                 :            :         // Avoid writing/flushing immediately after startup.
    2010         [ +  + ]:     117073 :         if (nLastWrite == 0) {
    2011                 :        390 :             nLastWrite = nNow;
    2012                 :            :         }
    2013         [ +  + ]:     117073 :         if (nLastFlush == 0) {
    2014                 :        390 :             nLastFlush = nNow;
    2015                 :            :         }
    2016 [ +  - ][ +  - ]:     234146 :         int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
         [ +  - ][ -  + ]
         [ +  - ][ #  # ]
    2017 [ +  - ][ +  - ]:     234146 :         int64_t cacheSize = pcoinsTip->DynamicMemoryUsage();
    2018         [ -  + ]:     117073 :         int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
    2019                 :            :         // The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing).
    2020 [ +  + ][ +  - ]:     165089 :         bool fCacheLarge = mode == FlushStateMode::PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024);
                 [ +  - ]
    2021                 :            :         // The cache is over the limit, we have to write now.
    2022                 :     117073 :         bool fCacheCritical = mode == FlushStateMode::IF_NEEDED && cacheSize > nTotalSpace;
    2023                 :            :         // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
    2024 [ +  + ][ +  - ]:     117073 :         bool fPeriodicWrite = mode == FlushStateMode::PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
    2025                 :            :         // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
    2026 [ +  + ][ +  - ]:     117073 :         bool fPeriodicFlush = mode == FlushStateMode::PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
    2027                 :            :         // Combine all conditions that result in a full cache flush.
    2028 [ +  + ][ +  - ]:     117073 :         fDoFullFlush = (mode == FlushStateMode::ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
                 [ +  - ]
    2029                 :            :         // Write blocks and block index to disk.
    2030         [ +  + ]:     117073 :         if (fDoFullFlush || fPeriodicWrite) {
    2031                 :            :             // Depend on nMinDiskSpace to ensure we can write block index
    2032 [ +  - ][ +  - ]:       1000 :             if (!CheckDiskSpace(GetBlocksDir())) {
                 [ -  + ]
    2033 [ #  # ][ #  # ]:          0 :                 return AbortNode(state, "Disk space is too low!", _("Error: Disk space is too low!").translated, CClientUIInterface::MSG_NOPREFIX);
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
    2034                 :            :             }
    2035                 :            :             // First make sure all block and undo data is flushed to disk.
    2036         [ +  - ]:       1000 :             FlushBlockFile();
    2037                 :            :             // Then update all block file information (which may refer to block and undo files).
    2038                 :       1000 :             {
    2039 [ +  - ][ #  # ]:       1000 :                 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
    2040 [ +  - ][ +  - ]:       2000 :                 vFiles.reserve(setDirtyFileInfo.size());
    2041 [ +  + ][ +  + ]:       2861 :                 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
                 [ +  + ]
    2042 [ +  - ][ +  - ]:       1722 :                     vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
    2043                 :        574 :                     setDirtyFileInfo.erase(it++);
    2044                 :            :                 }
    2045 [ +  - ][ +  + ]:       2284 :                 std::vector<const CBlockIndex*> vBlocks;
         [ +  + ][ #  # ]
    2046 [ +  - ][ +  - ]:       2000 :                 vBlocks.reserve(setDirtyBlockIndex.size());
    2047 [ +  + ][ +  + ]:      99287 :                 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
                 [ +  + ]
    2048 [ +  - ][ +  - ]:      64858 :                     vBlocks.push_back(*it);
    2049                 :      64858 :                     setDirtyBlockIndex.erase(it++);
    2050                 :            :                 }
    2051 [ +  - ][ +  - ]:       2000 :                 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
                 [ -  + ]
    2052 [ #  # ][ #  # ]:          0 :                     return AbortNode(state, "Failed to write to block index database");
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
                 [ #  # ]
    2053                 :            :                 }
    2054                 :            :             }
    2055                 :            :             // Finally remove any pruned files
    2056         [ -  + ]:       1000 :             if (fFlushForPrune)
    2057         [ #  # ]:          0 :                 UnlinkPrunedFiles(setFilesToPrune);
    2058                 :       1000 :             nLastWrite = nNow;
    2059                 :            :         }
    2060                 :            :         // Flush best chain related state. This can only be done if the blocks / block index write was also done.
    2061 [ +  + ][ +  - ]:     118073 :         if (fDoFullFlush && !pcoinsTip->GetBestBlock().IsNull()) {
         [ +  - ][ +  - ]
    2062                 :            :             // Typical Coin structures on disk are around 48 bytes in size.
    2063                 :            :             // Pushing a new one to the database can cause it to be written
    2064                 :            :             // twice (once in the log, and once in the tables). This is already
    2065                 :            :             // an overestimation, as most will delete an existing entry or
    2066                 :            :             // overwrite one. Still, use a conservative safety factor of 2.
    2067 [ +  - ][ +  - ]:       2000 :             if (!CheckDiskSpace(GetDataDir(), 48 * 2 * 2 * pcoinsTip->GetCacheSize())) {
         [ +  - ][ +  - ]
                 [ -  + ]
    2068 [ #  # ][ #  # ]:          0 :                 return AbortNode(state, "Disk space is too low!", _("Error: Disk space is too low!").translated, CClientUIInterface::MSG_NOPREFIX);
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
    2069                 :            :             }
    2070                 :            :             // Flush the chainstate (which may refer to block index entries).
    2071 [ +  - ][ +  - ]:       2000 :             if (!pcoinsTip->Flush())
                 [ -  + ]
    2072 [ #  # ][ #  # ]:          0 :                 return AbortNode(state, "Failed to write to coin database");
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
                 [ #  # ]
    2073                 :       1000 :             nLastFlush = nNow;
    2074                 :       1000 :             full_flush_completed = true;
    2075                 :            :         }
    2076                 :            :     }
    2077         [ +  + ]:     117073 :     if (full_flush_completed) {
    2078                 :            :         // Update best block in wallet (so we can detect restored wallets).
    2079 [ +  - ][ +  - ]:       1000 :         GetMainSignals().ChainStateFlushed(m_chain.GetLocator());
         [ +  - ][ +  - ]
                 [ #  # ]
    2080                 :            :     }
    2081                 :          0 :     } catch (const std::runtime_error& e) {
    2082   [ #  #  #  # ]:          0 :         return AbortNode(state, std::string("System error while flushing: ") + e.what());
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
           [ #  #  #  # ]
    2083                 :            :     }
    2084                 :            :     return true;
    2085                 :            : }
    2086                 :            : 
    2087                 :        782 : void CChainState::ForceFlushStateToDisk() {
    2088         [ +  - ]:       1564 :     CValidationState state;
    2089         [ +  - ]:        782 :     const CChainParams& chainparams = Params();
    2090 [ +  - ][ -  + ]:        782 :     if (!this->FlushStateToDisk(chainparams, state, FlushStateMode::ALWAYS)) {
    2091 [ #  # ][ #  # ]:          0 :         LogPrintf("%s: failed to flush state (%s)\n", __func__, FormatStateMessage(state));
         [ #  # ][ #  # ]
    2092                 :            :     }
    2093                 :        782 : }
    2094                 :            : 
    2095                 :          5 : void CChainState::PruneAndFlush() {
    2096         [ +  - ]:         10 :     CValidationState state;
    2097                 :          5 :     fCheckForPruning = true;
    2098         [ +  - ]:          5 :     const CChainParams& chainparams = Params();
    2099                 :            : 
    2100 [ +  - ][ -  + ]:          5 :     if (!this->FlushStateToDisk(chainparams, state, FlushStateMode::NONE)) {
    2101 [ #  # ][ #  # ]:          0 :         LogPrintf("%s: failed to flush state (%s)\n", __func__, FormatStateMessage(state));
         [ #  # ][ #  # ]
    2102                 :            :     }
    2103                 :          5 : }
    2104                 :            : 
    2105                 :        152 : static void DoWarning(const std::string& strWarning)
    2106                 :            : {
    2107                 :        152 :     static bool fWarned = false;
    2108                 :        152 :     SetMiscWarning(strWarning);
    2109         [ +  + ]:        152 :     if (!fWarned) {
    2110                 :          3 :         AlertNotify(strWarning);
    2111                 :          3 :         fWarned = true;
    2112                 :            :     }
    2113                 :        152 : }
    2114                 :            : 
    2115                 :            : /** Private helper function that concatenates warning messages. */
    2116                 :       2323 : static void AppendWarning(std::string& res, const std::string& warn)
    2117                 :            : {
    2118 [ +  + ][ +  + ]:       4646 :     if (!res.empty()) res += ", ";
    2119                 :       2323 :     res += warn;
    2120                 :       2323 : }
    2121                 :            : 
    2122                 :            : /** Check warning conditions and do some notifications on new chain tip set. */
    2123                 :      36248 : void static UpdateTip(const CBlockIndex *pindexNew, const CChainParams& chainParams) {
    2124                 :            :     // New best block
    2125                 :      36248 :     mempool.AddTransactionsUpdated(1);
    2126                 :            : 
    2127                 :      36248 :     {
    2128                 :      36248 :         LOCK(g_best_block_mutex);
    2129                 :      36248 :         g_best_block = pindexNew->GetBlockHash();
    2130         [ +  - ]:      36248 :         g_best_block_cv.notify_all();
    2131                 :            :     }
    2132                 :            : 
    2133 [ +  - ][ +  + ]:      72496 :     std::string warningMessages;
                 [ #  # ]
    2134 [ +  - ][ +  + ]:      36248 :     if (!::ChainstateActive().IsInitialBlockDownload())
    2135                 :            :     {
    2136                 :      30944 :         int nUpgraded = 0;
    2137                 :      30944 :         const CBlockIndex* pindex = pindexNew;
    2138         [ +  + ]:     928320 :         for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
    2139                 :    1794752 :             WarningBitsConditionChecker checker(bit);
    2140 [ +  - ][ +  - ]:    1794752 :             ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
    2141         [ +  + ]:     897376 :             if (state == ThresholdState::ACTIVE || state == ThresholdState::LOCKED_IN) {
    2142 [ +  - ][ +  - ]:        880 :                 const std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)").translated, bit);
         [ +  - ][ #  # ]
    2143         [ +  + ]:        440 :                 if (state == ThresholdState::ACTIVE) {
    2144         [ +  - ]:        152 :                     DoWarning(strWarning);
    2145                 :            :                 } else {
    2146         [ +  - ]:        288 :                     AppendWarning(warningMessages, strWarning);
    2147                 :            :                 }
    2148                 :            :             }
    2149                 :            :         }
    2150                 :            :         // Check the version of the last 100 blocks to see if we need to upgrade:
    2151         [ +  + ]:    2610975 :         for (int i = 0; i < 100 && pindex != nullptr; i++)
    2152                 :            :         {
    2153 [ +  - ][ +  - ]:    5160062 :             int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
    2154 [ +  + ][ +  + ]:    2580031 :             if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
    2155                 :      65086 :                 ++nUpgraded;
    2156                 :    2580031 :             pindex = pindex->pprev;
    2157                 :            :         }
    2158         [ +  + ]:      30944 :         if (nUpgraded > 0)
    2159 [ +  - ][ +  - ]:       4070 :             AppendWarning(warningMessages, strprintf(_("%d of last 100 blocks have unexpected version").translated, nUpgraded));
         [ +  - ][ +  - ]
                 [ #  # ]
    2160                 :            :     }
    2161         [ +  - ]:      36248 :     LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__, /* Continued */
    2162 [ +  - ][ +  - ]:      72496 :       pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, pindexNew->nVersion,
                 [ #  # ]
    2163 [ +  - ][ +  - ]:      36248 :       log(pindexNew->nChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx,
    2164 [ +  - ][ #  # ]:      72496 :       FormatISO8601DateTime(pindexNew->GetBlockTime()),
                 [ +  - ]
    2165 [ +  - ][ +  - ]:      72496 :       GuessVerificationProgress(chainParams.TxData(), pindexNew), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
         [ +  - ][ +  - ]
                 [ +  - ]
    2166 [ +  + ][ +  + ]:      72496 :     if (!warningMessages.empty())
    2167         [ +  - ]:       2114 :         LogPrintf(" warning='%s'", warningMessages); /* Continued */
    2168         [ +  - ]:      36248 :     LogPrintf("\n");
    2169                 :            : 
    2170                 :      36248 : }
    2171                 :            : 
    2172                 :            : /** Disconnect m_chain's tip.
    2173                 :            :   * After calling, the mempool will be in an inconsistent state, with
    2174                 :            :   * transactions from disconnected blocks being added to disconnectpool.  You
    2175                 :            :   * should make the mempool consistent again by calling UpdateMempoolForReorg.
    2176                 :            :   * with cs_main held.
    2177                 :            :   *
    2178                 :            :   * If disconnectpool is nullptr, then no disconnected transactions are added to
    2179                 :            :   * disconnectpool (note that the caller is responsible for mempool consistency
    2180                 :            :   * in any case).
    2181                 :            :   */
    2182                 :       3270 : bool CChainState::DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool)
    2183                 :            : {
    2184         [ +  - ]:       3270 :     CBlockIndex *pindexDelete = m_chain.Tip();
    2185         [ -  + ]:       3270 :     assert(pindexDelete);
    2186                 :            :     // Read block from disk.
    2187 [ +  - ][ #  # ]:       9810 :     std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
    2188         [ +  - ]:       3270 :     CBlock& block = *pblock;
    2189         [ -  + ]:       6540 :     if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
           [ +  -  +  - ]
    2190         [ #  # ]:          0 :         return error("DisconnectTip(): Failed to read block");
    2191                 :            :     // Apply the block atomically to the chain state.
    2192         [ +  - ]:       3270 :     int64_t nStart = GetTimeMicros();
    2193                 :       3270 :     {
    2194 [ +  - ][ +  - ]:       9809 :         CCoinsViewCache view(pcoinsTip.get());
    2195 [ +  - ][ +  - ]:       6540 :         assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
         [ -  + ][ -  + ]
    2196 [ +  - ][ +  + ]:       3270 :         if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
    2197 [ +  - ][ +  - ]:          3 :             return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
         [ +  - ][ +  - ]
                 [ #  # ]
    2198         [ +  - ]:       3269 :         bool flushed = view.Flush();
    2199         [ -  + ]:       3269 :         assert(flushed);
    2200                 :            :     }
    2201 [ +  - ][ +  - ]:       3269 :     LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI);
    2202                 :            :     // Write the chain state to disk, if necessary.
    2203 [ +  - ][ +  - ]:       3269 :     if (!FlushStateToDisk(chainparams, state, FlushStateMode::IF_NEEDED))
    2204                 :            :         return false;
    2205                 :            : 
    2206         [ +  + ]:       3269 :     if (disconnectpool) {
    2207                 :            :         // Save transactions to re-add to mempool at end of reorg
    2208 [ +  + ][ +  + ]:      12325 :         for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
                 [ +  + ]
    2209 [ +  - ][ +  - ]:      18406 :             disconnectpool->addTransaction(*it);
    2210                 :            :         }
    2211 [ +  + ][ +  + ]:      12654 :         while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
    2212                 :            :             // Drop the earliest entry, and remove its children from the mempool.
    2213 [ +  - ][ +  - ]:       6410 :             auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
    2214 [ +  - ][ +  - ]:       9615 :             mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
                 [ +  - ]
    2215                 :       3205 :             disconnectpool->removeEntry(it);
    2216                 :            :         }
    2217                 :            :     }
    2218                 :            : 
    2219         [ +  - ]:       3269 :     m_chain.SetTip(pindexDelete->pprev);
    2220                 :            : 
    2221         [ +  - ]:       3269 :     UpdateTip(pindexDelete->pprev, chainparams);
    2222                 :            :     // Let wallets know transactions went from 1-confirmed to
    2223                 :            :     // 0-confirmed or conflicted:
    2224 [ +  - ][ +  - ]:       3269 :     GetMainSignals().BlockDisconnected(pblock);
         [ +  - ][ #  # ]
    2225                 :       3269 :     return true;
    2226                 :            : }
    2227                 :            : 
    2228                 :            : static int64_t nTimeReadFromDisk = 0;
    2229                 :            : static int64_t nTimeConnectTotal = 0;
    2230                 :            : static int64_t nTimeFlush = 0;
    2231                 :            : static int64_t nTimeChainState = 0;
    2232                 :            : static int64_t nTimePostConnect = 0;
    2233                 :            : 
    2234                 :     104952 : struct PerBlockConnectTrace {
    2235                 :            :     CBlockIndex* pindex = nullptr;
    2236                 :            :     std::shared_ptr<const CBlock> pblock;
    2237                 :            :     std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs;
    2238 [ +  - ][ +  - ]:     162836 :     PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {}
                 [ #  # ]
    2239                 :            : };
    2240                 :            : /**
    2241                 :            :  * Used to track blocks whose transactions were applied to the UTXO state as a
    2242                 :            :  * part of a single ActivateBestChainStep call.
    2243                 :            :  *
    2244                 :            :  * This class also tracks transactions that are removed from the mempool as
    2245                 :            :  * conflicts (per block) and can be used to pass all those transactions
    2246                 :            :  * through SyncTransaction.
    2247                 :            :  *
    2248                 :            :  * This class assumes (and asserts) that the conflicted transactions for a given
    2249                 :            :  * block are added via mempool callbacks prior to the BlockConnected() associated
    2250                 :            :  * with those transactions. If any transactions are marked conflicted, it is
    2251                 :            :  * assumed that an associated block will always be added.
    2252                 :            :  *
    2253                 :            :  * This class is single-use, once you call GetBlocksConnected() you have to throw
    2254                 :            :  * it away and make a new one.
    2255                 :            :  */
    2256                 :      48439 : class ConnectTrace {
    2257                 :            : private:
    2258                 :            :     std::vector<PerBlockConnectTrace> blocksConnected;
    2259                 :            :     CTxMemPool &pool;
    2260                 :            :     boost::signals2::scoped_connection m_connNotifyEntryRemoved;
    2261                 :            : 
    2262                 :            : public:
    2263   [ +  -  +  - ]:      96878 :     explicit ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
    2264 [ +  - ][ +  - ]:     145317 :         m_connNotifyEntryRemoved = pool.NotifyEntryRemoved.connect(std::bind(&ConnectTrace::NotifyEntryRemoved, this, std::placeholders::_1, std::placeholders::_2));
         [ -  + ][ #  # ]
           [ +  -  +  - ]
    2265                 :      48439 :     }
    2266                 :            : 
    2267                 :      32979 :     void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
    2268 [ -  + ][ -  + ]:      65958 :         assert(!blocksConnected.back().pindex);
    2269         [ -  + ]:      32979 :         assert(pindex);
    2270 [ -  + ][ -  + ]:      65958 :         assert(pblock);
    2271         [ -  + ]:      32979 :         blocksConnected.back().pindex = pindex;
    2272 [ -  + ][ -  + ]:      65958 :         blocksConnected.back().pblock = std::move(pblock);
    2273                 :      32979 :         blocksConnected.emplace_back();
    2274                 :      32979 :     }
    2275                 :            : 
    2276                 :      30445 :     std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
    2277                 :            :         // We always keep one extra block at the end of our list because
    2278                 :            :         // blocks are added after all the conflicted transactions have
    2279                 :            :         // been filled in. Thus, the last entry should always be an empty
    2280                 :            :         // one waiting for the transactions from the next block. We pop
    2281                 :            :         // the last entry here to make sure the list we return is sane.
    2282 [ -  + ][ -  + ]:      60890 :         assert(!blocksConnected.back().pindex);
    2283 [ -  + ][ -  + ]:     121780 :         assert(blocksConnected.back().conflictedTxs->empty());
         [ -  + ][ -  + ]
    2284                 :      30445 :         blocksConnected.pop_back();
    2285                 :      30445 :         return blocksConnected;
    2286                 :            :     }
    2287                 :            : 
    2288                 :      15667 :     void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason) {
    2289 [ -  + ][ -  + ]:      31334 :         assert(!blocksConnected.back().pindex);
    2290         [ +  + ]:      15667 :         if (reason == MemPoolRemovalReason::CONFLICT) {
    2291                 :        141 :             blocksConnected.back().conflictedTxs->emplace_back(std::move(txRemoved));
    2292                 :            :         }
    2293                 :      15667 :     }
    2294                 :            : };
    2295                 :            : 
    2296                 :            : /**
    2297                 :            :  * Connect a new block to m_chain. pblock is either nullptr or a pointer to a CBlock
    2298                 :            :  * corresponding to pindexNew, to bypass loading it again from disk.
    2299                 :            :  *
    2300                 :            :  * The block is added to connectTrace if connection succeeds.
    2301                 :            :  */
    2302                 :      33149 : bool CChainState::ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool)
    2303                 :            : {
    2304 [ +  + ][ -  + ]:      66076 :     assert(pindexNew->pprev == m_chain.Tip());
    2305                 :            :     // Read block from disk.
    2306                 :      33149 :     int64_t nTime1 = GetTimeMicros();
    2307 [ +  + ][ #  # ]:      33319 :     std::shared_ptr<const CBlock> pthisBlock;
    2308   [ +  +  +  + ]:      66298 :     if (!pblock) {
    2309 [ +  - ][ #  # ]:       6631 :         std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
    2310 [ +  - ][ +  - ]:      19893 :         if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
         [ +  - ][ -  + ]
    2311 [ #  # ][ #  # ]:          0 :             return AbortNode(state, "Failed to read block");
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
                 [ #  # ]
    2312         [ +  - ]:       6631 :         pthisBlock = pblockNew;
    2313                 :            :     } else {
    2314                 :      26518 :         pthisBlock = pblock;
    2315                 :            :     }
    2316         [ +  - ]:      33149 :     const CBlock& blockConnecting = *pthisBlock;
    2317                 :            :     // Apply the block atomically to the chain state.
    2318         [ +  - ]:      33149 :     int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
    2319                 :      33149 :     int64_t nTime3;
    2320         [ +  - ]:      33149 :     LogPrint(BCLog::BENCH, "  - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * MILLI, nTimeReadFromDisk * MICRO);
    2321                 :      33149 :     {
    2322 [ +  - ][ +  - ]:      99277 :         CCoinsViewCache view(pcoinsTip.get());
    2323         [ +  - ]:      33149 :         bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
    2324 [ +  - ][ +  - ]:      33149 :         GetMainSignals().BlockChecked(blockConnecting, state);
    2325         [ +  + ]:      33149 :         if (!rv) {
    2326 [ +  - ][ +  - ]:        340 :             if (state.IsInvalid())
    2327         [ +  - ]:        170 :                 InvalidBlockFound(pindexNew, state);
    2328 [ +  - ][ +  - ]:        510 :             return error("%s: ConnectBlock %s failed, %s", __func__, pindexNew->GetBlockHash().ToString(), FormatStateMessage(state));
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
    2329                 :            :         }
    2330         [ +  - ]:      32979 :         nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
    2331         [ +  - ]:      32979 :         LogPrint(BCLog::BENCH, "  - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime3 - nTime2) * MILLI, nTimeConnectTotal * MICRO, nTimeConnectTotal * MILLI / nBlocksTotal);
    2332         [ +  - ]:      32979 :         bool flushed = view.Flush();
    2333         [ -  + ]:      32979 :         assert(flushed);
    2334                 :            :     }
    2335         [ +  - ]:      32979 :     int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
    2336         [ +  - ]:      32979 :     LogPrint(BCLog::BENCH, "  - Flush: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime4 - nTime3) * MILLI, nTimeFlush * MICRO, nTimeFlush * MILLI / nBlocksTotal);
    2337                 :            :     // Write the chain state to disk, if necessary.
    2338 [ +  - ][ +  - ]:      32979 :     if (!FlushStateToDisk(chainparams, state, FlushStateMode::IF_NEEDED))
    2339                 :            :         return false;
    2340         [ +  - ]:      32979 :     int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
    2341         [ +  - ]:      32979 :     LogPrint(BCLog::BENCH, "  - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime5 - nTime4) * MILLI, nTimeChainState * MICRO, nTimeChainState * MILLI / nBlocksTotal);
    2342                 :            :     // Remove conflicting transactions from the mempool.;
    2343         [ +  - ]:      32979 :     mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
    2344         [ +  - ]:      32979 :     disconnectpool.removeForBlock(blockConnecting.vtx);
    2345                 :            :     // Update m_chain & related variables.
    2346         [ +  - ]:      32979 :     m_chain.SetTip(pindexNew);
    2347         [ +  - ]:      32979 :     UpdateTip(pindexNew, chainparams);
    2348                 :            : 
    2349         [ +  - ]:      32979 :     int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
    2350         [ +  - ]:      32979 :     LogPrint(BCLog::BENCH, "  - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime5) * MILLI, nTimePostConnect * MICRO, nTimePostConnect * MILLI / nBlocksTotal);
    2351         [ +  - ]:      32979 :     LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime1) * MILLI, nTimeTotal * MICRO, nTimeTotal * MILLI / nBlocksTotal);
    2352                 :            : 
    2353 [ +  - ][ +  - ]:      65958 :     connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
         [ -  + ][ #  # ]
    2354                 :      32979 :     return true;
    2355                 :            : }
    2356                 :            : 
    2357                 :            : /**
    2358                 :            :  * Return the tip of the chain with the most work in it, that isn't
    2359                 :            :  * known to be invalid (it's however far from certain to be valid).
    2360                 :            :  */
    2361                 :      45297 : CBlockIndex* CChainState::FindMostWorkChain() {
    2362                 :      45301 :     do {
    2363                 :      45301 :         CBlockIndex *pindexNew = nullptr;
    2364                 :            : 
    2365                 :            :         // Find the best candidate header.
    2366                 :      45301 :         {
    2367         [ +  - ]:      45301 :             std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
    2368 [ +  - ][ +  - ]:     135903 :             if (it == setBlockIndexCandidates.rend())
                 [ +  - ]
    2369                 :            :                 return nullptr;
    2370                 :      45301 :             pindexNew = *it;
    2371                 :            :         }
    2372                 :            : 
    2373                 :            :         // Check whether all blocks on the path between the currently active chain and the candidate are valid.
    2374                 :            :         // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
    2375                 :      45301 :         CBlockIndex *pindexTest = pindexNew;
    2376                 :      45301 :         bool fInvalidAncestor = false;
    2377 [ +  + ][ +  - ]:     156700 :         while (pindexTest && !m_chain.Contains(pindexTest)) {
                 [ +  + ]
    2378 [ -  + ][ -  + ]:      66328 :             assert(pindexTest->HaveTxsDownloaded() || pindexTest->nHeight == 0);
                 [ #  # ]
    2379                 :            : 
    2380                 :            :             // Pruned nodes may have entries in setBlockIndexCandidates for
    2381                 :            :             // which block files have been deleted.  Remove those as candidates
    2382                 :            :             // for the most work chain if we come across them; we can't switch
    2383                 :            :             // to a chain unless we have all the non-active-chain parent blocks.
    2384                 :      33164 :             bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
    2385                 :      33164 :             bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
    2386         [ +  + ]:      33164 :             if (fFailedChain || fMissingData) {
    2387                 :            :                 // Candidate chain is not usable (either invalid or missing data)
    2388 [ +  - ][ +  - ]:          4 :                 if (fFailedChain && (pindexBestInvalid == nullptr || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
                 [ -  + ]
    2389                 :          0 :                     pindexBestInvalid = pindexNew;
    2390                 :          4 :                 CBlockIndex *pindexFailed = pindexNew;
    2391                 :            :                 // Remove the entire chain from the set.
    2392         [ +  + ]:          8 :                 while (pindexTest != pindexFailed) {
    2393         [ +  - ]:          4 :                     if (fFailedChain) {
    2394                 :          4 :                         pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
    2395         [ #  # ]:          0 :                     } else if (fMissingData) {
    2396                 :            :                         // If we're missing data, then add back to m_blocks_unlinked,
    2397                 :            :                         // so that if the block arrives in the future we can try adding
    2398                 :            :                         // to setBlockIndexCandidates again.
    2399                 :          0 :                         m_blockman.m_blocks_unlinked.insert(
    2400                 :          0 :                             std::make_pair(pindexFailed->pprev, pindexFailed));
    2401                 :            :                     }
    2402                 :          4 :                     setBlockIndexCandidates.erase(pindexFailed);
    2403                 :          4 :                     pindexFailed = pindexFailed->pprev;
    2404                 :            :                 }
    2405                 :          4 :                 setBlockIndexCandidates.erase(pindexTest);
    2406                 :          4 :                 fInvalidAncestor = true;
    2407                 :          4 :                 break;
    2408                 :            :             }
    2409                 :      33160 :             pindexTest = pindexTest->pprev;
    2410                 :            :         }
    2411                 :          4 :         if (!fInvalidAncestor)
    2412                 :            :             return pindexNew;
    2413                 :            :     } while(true);
    2414                 :            : }
    2415                 :            : 
    2416                 :            : /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
    2417                 :      33423 : void CChainState::PruneBlockIndexCandidates() {
    2418                 :            :     // Note that we can't delete the current block itself, as we may need to return to it later in case a
    2419                 :            :     // reorganization to a better block fails.
    2420                 :      66846 :     std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
    2421 [ +  - ][ +  - ]:     498275 :     while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, m_chain.Tip())) {
         [ +  - ][ +  - ]
         [ +  - ][ +  + ]
    2422                 :     132464 :         setBlockIndexCandidates.erase(it++);
    2423                 :            :     }
    2424                 :            :     // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
    2425 [ -  + ][ -  + ]:      66846 :     assert(!setBlockIndexCandidates.empty());
    2426                 :      33423 : }
    2427                 :            : 
    2428                 :            : /**
    2429                 :            :  * Try to make some progress towards making pindexMostWork the active block.
    2430                 :            :  * pblock is either nullptr or a pointer to a CBlock corresponding to pindexMostWork.
    2431                 :            :  */
    2432                 :      30446 : bool CChainState::ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
    2433                 :            : {
    2434                 :      30446 :     AssertLockHeld(cs_main);
    2435                 :            : 
    2436         [ +  + ]:      30446 :     const CBlockIndex *pindexOldTip = m_chain.Tip();
    2437                 :      30446 :     const CBlockIndex *pindexFork = m_chain.FindFork(pindexMostWork);
    2438                 :            : 
    2439                 :            :     // Disconnect active blocks which are no longer in the best chain.
    2440                 :      30446 :     bool fBlocksDisconnected = false;
    2441                 :      60892 :     DisconnectedBlockTransactions disconnectpool;
    2442 [ +  + ][ +  - ]:      33164 :     while (m_chain.Tip() && m_chain.Tip() != pindexFork) {
         [ +  + ][ +  + ]
    2443 [ +  - ][ +  + ]:       2719 :         if (!DisconnectTip(state, chainparams, &disconnectpool)) {
    2444                 :            :             // This is likely a fatal error, but keep the mempool consistent,
    2445                 :            :             // just in case. Only remove from the mempool in this case.
    2446         [ +  - ]:          1 :             UpdateMempoolForReorg(disconnectpool, false);
    2447                 :            : 
    2448                 :            :             // If we're unable to disconnect a block during normal operation,
    2449                 :            :             // then that is a failure of our local system -- we should abort
    2450                 :            :             // rather than stay on a less work chain.
    2451 [ +  - ][ +  - ]:          4 :             AbortNode(state, "Failed to disconnect block; see debug.log for details");
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ -  + ][ -  + ]
         [ #  # ][ #  # ]
                 [ #  # ]
    2452                 :          1 :             return false;
    2453                 :            :         }
    2454                 :            :         fBlocksDisconnected = true;
    2455                 :            :     }
    2456                 :            : 
    2457                 :            :     // Build list of new blocks to connect.
    2458 [ +  + ][ +  - ]:      60890 :     std::vector<CBlockIndex*> vpindexToConnect;
                 [ #  # ]
    2459                 :      30445 :     bool fContinue = true;
    2460         [ +  + ]:      30445 :     int nHeight = pindexFork ? pindexFork->nHeight : -1;
    2461 [ +  + ][ +  + ]:      60967 :     while (fContinue && nHeight != pindexMostWork->nHeight) {
    2462                 :            :         // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
    2463                 :            :         // a few blocks along the way.
    2464         [ +  + ]:      30522 :         int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
    2465         [ +  + ]:      30522 :         vpindexToConnect.clear();
    2466         [ +  - ]:      30522 :         vpindexToConnect.reserve(nTargetHeight - nHeight);
    2467         [ +  - ]:      30522 :         CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
    2468 [ +  + ][ +  + ]:     109378 :         while (pindexIter && pindexIter->nHeight != nHeight) {
    2469         [ +  - ]:      78856 :             vpindexToConnect.push_back(pindexIter);
    2470                 :      78856 :             pindexIter = pindexIter->pprev;
    2471                 :            :         }
    2472                 :      30522 :         nHeight = nTargetHeight;
    2473                 :            : 
    2474                 :            :         // Connect new blocks.
    2475 [ +  + ][ +  + ]:      33237 :         for (CBlockIndex *pindexConnect : reverse_iterate(vpindexToConnect)) {
                 [ +  + ]
    2476 [ +  + ][ +  - ]:      59667 :             if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
         [ +  + ][ +  + ]
                 [ #  # ]
    2477 [ +  - ][ +  - ]:        340 :                 if (state.IsInvalid()) {
    2478                 :            :                     // The block violates a consensus rule.
    2479 [ +  - ][ +  - ]:        340 :                     if (state.GetReason() != ValidationInvalidReason::BLOCK_MUTATED) {
    2480 [ +  - ][ +  - ]:        340 :                         InvalidChainFound(vpindexToConnect.front());
    2481                 :            :                     }
    2482                 :        340 :                     state = CValidationState();
    2483                 :        170 :                     fInvalidFound = true;
    2484                 :        170 :                     fContinue = false;
    2485                 :        170 :                     break;
    2486                 :            :                 } else {
    2487                 :            :                     // A system error occurred (disk space, database error, ...).
    2488                 :            :                     // Make the mempool consistent with the current tip, just in case
    2489                 :            :                     // any observers try to use it before shutdown.
    2490         [ #  # ]:          0 :                     UpdateMempoolForReorg(disconnectpool, false);
    2491                 :            :                     return false;
    2492                 :            :                 }
    2493                 :            :             } else {
    2494         [ +  - ]:      32979 :                 PruneBlockIndexCandidates();
    2495 [ +  + ][ +  - ]:      65736 :                 if (!pindexOldTip || m_chain.Tip()->nChainWork > pindexOldTip->nChainWork) {
         [ +  - ][ +  + ]
    2496                 :            :                     // We're in a better position than we were. Return temporarily to release the lock.
    2497                 :            :                     fContinue = false;
    2498                 :            :                     break;
    2499                 :            :                 }
    2500                 :            :             }
    2501                 :            :         }
    2502                 :            :     }
    2503                 :            : 
    2504         [ +  + ]:      30445 :     if (fBlocksDisconnected) {
    2505                 :            :         // If any blocks were disconnected, disconnectpool may be non empty.  Add
    2506                 :            :         // any disconnected transactions back to the mempool.
    2507         [ +  - ]:         66 :         UpdateMempoolForReorg(disconnectpool, true);
    2508                 :            :     }
    2509 [ +  - ][ +  - ]:      60890 :     mempool.check(pcoinsTip.get());
    2510                 :            : 
    2511                 :            :     // Callbacks/notifications for a new best chain.
    2512         [ +  + ]:      30445 :     if (fInvalidFound)
    2513 [ +  - ][ +  - ]:        340 :         CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
    2514                 :            :     else
    2515         [ +  - ]:      30275 :         CheckForkWarningConditions();
    2516                 :            : 
    2517                 :            :     return true;
    2518                 :            : }
    2519                 :            : 
    2520                 :      57543 : static void NotifyHeaderTip() LOCKS_EXCLUDED(cs_main) {
    2521                 :      57543 :     bool fNotify = false;
    2522                 :      57543 :     bool fInitialBlockDownload = false;
    2523                 :      57543 :     static CBlockIndex* pindexHeaderOld = nullptr;
    2524                 :      57543 :     CBlockIndex* pindexHeader = nullptr;
    2525                 :      57543 :     {
    2526 [ +  - ][ #  # ]:     115086 :         LOCK(cs_main);
    2527                 :      57543 :         pindexHeader = pindexBestHeader;
    2528                 :            : 
    2529         [ +  + ]:      57543 :         if (pindexHeader != pindexHeaderOld) {
    2530                 :      20217 :             fNotify = true;
    2531         [ +  - ]:      20217 :             fInitialBlockDownload = ::ChainstateActive().IsInitialBlockDownload();
    2532                 :      20217 :             pindexHeaderOld = pindexHeader;
    2533                 :            :         }
    2534                 :            :     }
    2535                 :            :     // Send block tip changed notifications without cs_main
    2536         [ +  + ]:      57543 :     if (fNotify) {
    2537                 :      20217 :         uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
    2538                 :            :     }
    2539                 :      57543 : }
    2540                 :            : 
    2541                 :      49033 : static void LimitValidationInterfaceQueue() LOCKS_EXCLUDED(cs_main) {
    2542                 :      49033 :     AssertLockNotHeld(cs_main);
    2543                 :            : 
    2544         [ +  + ]:      49033 :     if (GetMainSignals().CallbacksPending() > 10) {
    2545                 :        503 :         SyncWithValidationInterfaceQueue();
    2546                 :            :     }
    2547                 :      49033 : }
    2548                 :            : 
    2549                 :            : /**
    2550                 :            :  * Make the best chain active, in multiple steps. The result is either failure
    2551                 :            :  * or an activated best chain. pblock is either nullptr or a pointer to a block
    2552                 :            :  * that is already loaded (to avoid loading it again from disk).
    2553                 :            :  *
    2554                 :            :  * ActivateBestChain is split into steps (see ActivateBestChainStep) so that
    2555                 :            :  * we avoid holding cs_main for an extended period of time; the length of this
    2556                 :            :  * call may be quite long during reindexing or a substantial reorg.
    2557                 :            :  */
    2558                 :      45127 : bool CChainState::ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
    2559                 :            :     // Note that while we're often called here from ProcessNewBlock, this is
    2560                 :            :     // far from a guarantee. Things in the P2P/RPC will often end up calling
    2561                 :            :     // us in the middle of ProcessNewBlock - do not assume pblock is set
    2562                 :            :     // sanely for performance or correctness!
    2563                 :      45127 :     AssertLockNotHeld(cs_main);
    2564                 :            : 
    2565                 :            :     // ABC maintains a fair degree of expensive-to-calculate internal state
    2566                 :            :     // because this function periodically releases cs_main so that it does not lock up other threads for too long
    2567                 :            :     // during large connects - and to allow for e.g. the callback queue to drain
    2568                 :            :     // we use m_cs_chainstate to enforce mutual exclusion so that only one caller may execute this function at a time
    2569 [ +  - ][ #  # ]:     135381 :     LOCK(m_cs_chainstate);
    2570                 :            : 
    2571                 :      45127 :     CBlockIndex *pindexMostWork = nullptr;
    2572                 :      45127 :     CBlockIndex *pindexNewTip = nullptr;
    2573 [ +  - ][ -  + ]:      90254 :     int nStopAtHeight = gArgs.GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
                 [ #  # ]
           [ +  -  +  - ]
    2574                 :      48433 :     do {
    2575         [ +  - ]:      48433 :         boost::this_thread::interruption_point();
    2576                 :            : 
    2577                 :            :         // Block until the validation queue drains. This should largely
    2578                 :            :         // never happen in normal operation, however may happen during
    2579                 :            :         // reindex, causing memory blowup if we run too far ahead.
    2580                 :            :         // Note that if a validationinterface callback ends up calling
    2581                 :            :         // ActivateBestChain this may lead to a deadlock! We should
    2582                 :            :         // probably have a DEBUG_LOCKORDER test for this in the future.
    2583         [ +  - ]:      48433 :         LimitValidationInterfaceQueue();
    2584                 :            : 
    2585                 :      48433 :         {
    2586 [ +  - ][ +  - ]:     109311 :             LOCK2(cs_main, ::mempool.cs); // Lock transaction pool for at least as long as it takes for connectTrace to be consumed
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
    2587         [ +  + ]:      48433 :             CBlockIndex* starting_tip = m_chain.Tip();
    2588                 :      48433 :             bool blocks_connected = false;
    2589                 :      48439 :             do {
    2590                 :            :                 // We absolutely may not unlock cs_main until we've made forward progress
    2591                 :            :                 // (with the exception of shutdown due to hardware issues, low disk space, etc).
    2592         [ +  - ]:      48439 :                 ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked
    2593                 :            : 
    2594         [ +  + ]:      48439 :                 if (pindexMostWork == nullptr) {
    2595         [ +  - ]:      45297 :                     pindexMostWork = FindMostWorkChain();
    2596                 :            :                 }
    2597                 :            : 
    2598                 :            :                 // Whether we have anything to do at all.
    2599 [ +  - ][ +  + ]:      96656 :                 if (pindexMostWork == nullptr || pindexMostWork == m_chain.Tip()) {
                 [ +  + ]
    2600                 :            :                     break;
    2601                 :            :                 }
    2602                 :            : 
    2603                 :      30446 :                 bool fInvalidFound = false;
    2604 [ -  + ][ #  # ]:      30445 :                 std::shared_ptr<const CBlock> nullBlockPtr;
    2605 [ +  + ][ +  + ]:      63694 :                 if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
         [ +  - ][ +  - ]
         [ +  - ][ +  + ]
         [ +  + ][ +  - ]
                 [ +  + ]
    2606         [ -  + ]:          1 :                     return false;
    2607                 :      30445 :                 blocks_connected = true;
    2608                 :            : 
    2609         [ +  + ]:      30445 :                 if (fInvalidFound) {
    2610                 :            :                     // Wipe cache, we may need another branch now.
    2611                 :        170 :                     pindexMostWork = nullptr;
    2612                 :            :                 }
    2613         [ +  - ]:      30445 :                 pindexNewTip = m_chain.Tip();
    2614                 :            : 
    2615 [ +  + ][ +  + ]:      96403 :                 for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
    2616 [ +  - ][ +  - ]:      65958 :                     assert(trace.pblock && trace.pindex);
                 [ -  + ]
    2617 [ +  - ][ +  - ]:      65958 :                     GetMainSignals().BlockConnected(trace.pblock, trace.pindex, trace.conflictedTxs);
         [ +  - ][ #  # ]
    2618                 :            :                 }
    2619 [ -  + ][ +  + ]:      30445 :             } while (!m_chain.Tip() || (starting_tip && CBlockIndexWorkComparator()(m_chain.Tip(), starting_tip)));
         [ +  - ][ +  - ]
         [ +  + ][ -  + ]
    2620         [ +  + ]:      48432 :             if (!blocks_connected) return true;
    2621                 :            : 
    2622         [ +  - ]:      30439 :             const CBlockIndex* pindexFork = m_chain.FindFork(starting_tip);
    2623         [ +  - ]:      30439 :             bool fInitialDownload = IsInitialBlockDownload();
    2624                 :            : 
    2625                 :            :             // Notify external listeners about the new tip.
    2626                 :            :             // Enqueue while holding cs_main to ensure that UpdatedBlockTip is called in the order in which blocks are connected
    2627         [ +  + ]:      30439 :             if (pindexFork != pindexNewTip) {
    2628                 :            :                 // Notify ValidationInterface subscribers
    2629 [ +  - ][ +  - ]:      30269 :                 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
    2630                 :            : 
    2631                 :            :                 // Always notify the UI if a new block tip was connected
    2632         [ +  - ]:      30269 :                 uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
    2633                 :            :             }
    2634                 :            :         }
    2635                 :            :         // When we reach this point, we switched to a new tip (stored in pindexNewTip).
    2636                 :            : 
    2637 [ +  + ][ +  + ]:      30439 :         if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
                 [ +  - ]
    2638                 :            : 
    2639                 :            :         // We check shutdown only after giving ActivateBestChainStep a chance to run once so that we
    2640                 :            :         // never shutdown before connecting the genesis block during LoadChainTip(). Previously this
    2641                 :            :         // caused an assert() failure during shutdown in such cases as the UTXO DB flushing checks
    2642                 :            :         // that the best block hash is non-null.
    2643 [ +  - ][ +  + ]:      30439 :         if (ShutdownRequested())
    2644                 :            :             break;
    2645         [ +  + ]:      30427 :     } while (pindexNewTip != pindexMostWork);
    2646 [ +  - ][ +  - ]:      54266 :     CheckBlockIndex(chainparams.GetConsensus());
    2647                 :            : 
    2648                 :            :     // Write changes periodically to disk, after relay.
    2649 [ +  - ][ -  + ]:      27133 :     if (!FlushStateToDisk(chainparams, state, FlushStateMode::PERIODIC)) {
    2650                 :          0 :         return false;
    2651                 :            :     }
    2652                 :            : 
    2653                 :            :     return true;
    2654                 :            : }
    2655                 :            : 
    2656                 :        501 : bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
    2657 [ +  - ][ +  - ]:       1005 :     return ::ChainstateActive().ActivateBestChain(state, chainparams, std::move(pblock));
         [ +  + ][ #  # ]
    2658                 :            : }
    2659                 :            : 
    2660                 :          9 : bool CChainState::PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
    2661                 :            : {
    2662                 :          9 :     {
    2663 [ +  - ][ #  # ]:         17 :         LOCK(cs_main);
    2664 [ +  - ][ +  + ]:         18 :         if (pindex->nChainWork < m_chain.Tip()->nChainWork) {
                 [ +  - ]
    2665                 :            :             // Nothing to do, this block is not at the tip.
    2666         [ +  - ]:          1 :             return true;
    2667                 :            :         }
    2668 [ +  - ][ +  - ]:         16 :         if (m_chain.Tip()->nChainWork > nLastPreciousChainwork) {
                 [ +  + ]
    2669                 :            :             // The chain has been extended since the last call, reset the counter.
    2670                 :          4 :             nBlockReverseSequenceId = -1;
    2671                 :            :         }
    2672         [ +  - ]:         16 :         nLastPreciousChainwork = m_chain.Tip()->nChainWork;
    2673         [ +  - ]:          8 :         setBlockIndexCandidates.erase(pindex);
    2674                 :          8 :         pindex->nSequenceId = nBlockReverseSequenceId;
    2675         [ +  - ]:          8 :         if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
    2676                 :            :             // We can't keep reducing the counter if somebody really wants to
    2677                 :            :             // call preciousblock 2**31-1 times on the same set of tips...
    2678                 :          8 :             nBlockReverseSequenceId--;
    2679                 :            :         }
    2680 [ +  - ][ +  - ]:          8 :         if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->HaveTxsDownloaded()) {
         [ +  - ][ +  - ]
    2681         [ +  - ]:          8 :             setBlockIndexCandidates.insert(pindex);
    2682         [ +  - ]:          8 :             PruneBlockIndexCandidates();
    2683                 :            :         }
    2684                 :            :     }
    2685                 :            : 
    2686 [ +  - ][ +  - ]:         16 :     return ActivateBestChain(state, params, std::shared_ptr<const CBlock>());
         [ -  + ][ #  # ]
    2687                 :            : }
    2688                 :          9 : bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex) {
    2689                 :          9 :     return ::ChainstateActive().PreciousBlock(state, params, pindex);
    2690                 :            : }
    2691                 :            : 
    2692                 :         49 : bool CChainState::InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
    2693                 :            : {
    2694                 :         49 :     CBlockIndex* to_mark_failed = pindex;
    2695                 :         49 :     bool pindex_was_in_chain = false;
    2696                 :         49 :     int disconnected = 0;
    2697                 :            : 
    2698                 :            :     // Disconnect (descendants of) pindex, and mark them invalid.
    2699                 :        453 :     while (true) {
    2700         [ +  - ]:        453 :         if (ShutdownRequested()) break;
    2701                 :            : 
    2702                 :            :         // Make sure the queue of validation callbacks doesn't grow unboundedly.
    2703                 :        453 :         LimitValidationInterfaceQueue();
    2704                 :            : 
    2705         [ #  # ]:        453 :         LOCK(cs_main);
    2706 [ +  - ][ #  # ]:        857 :         LOCK(::mempool.cs); // Lock for as long as disconnectpool is in scope to make sure UpdateMempoolForReorg is called after DisconnectTip without unlocking in between
                 [ +  - ]
    2707 [ +  - ][ +  + ]:        906 :         if (!m_chain.Contains(pindex)) break;
    2708                 :        404 :         pindex_was_in_chain = true;
    2709         [ +  - ]:        404 :         CBlockIndex *invalid_walk_tip = m_chain.Tip();
    2710                 :            : 
    2711                 :            :         // ActivateBestChain considers blocks already in m_chain
    2712                 :            :         // unconditionally valid already, so force disconnect away from it.
    2713   [ +  -  +  - ]:        808 :         DisconnectedBlockTransactions disconnectpool;
    2714         [ +  - ]:        404 :         bool ret = DisconnectTip(state, chainparams, &disconnectpool);
    2715                 :            :         // DisconnectTip will add transactions to disconnectpool.
    2716                 :            :         // Adjust the mempool to be consistent with the new tip, adding
    2717                 :            :         // transactions back to the mempool if disconnecting was successful,
    2718                 :            :         // and we're not doing a very deep invalidation (in which case
    2719                 :            :         // keeping the mempool up to date is probably futile anyway).
    2720 [ +  + ][ -  + ]:        687 :         UpdateMempoolForReorg(disconnectpool, /* fAddToMempool = */ (++disconnected <= 10) && ret);
                 [ +  - ]
    2721 [ -  + ][ #  # ]:        404 :         if (!ret) return false;
    2722 [ +  - ][ -  + ]:        808 :         assert(invalid_walk_tip->pprev == m_chain.Tip());
    2723                 :            : 
    2724                 :            :         // We immediately mark the disconnected blocks as invalid.
    2725                 :            :         // This prevents a case where pruned nodes may fail to invalidateblock
    2726                 :            :         // and be left unable to start as they have no tip candidates (as there
    2727                 :            :         // are no blocks that meet the "have data and are not invalid per
    2728                 :            :         // nStatus" criteria for inclusion in setBlockIndexCandidates).
    2729                 :        404 :         invalid_walk_tip->nStatus |= BLOCK_FAILED_VALID;
    2730         [ +  - ]:        404 :         setDirtyBlockIndex.insert(invalid_walk_tip);
    2731         [ +  - ]:        404 :         setBlockIndexCandidates.erase(invalid_walk_tip);
    2732         [ +  - ]:        404 :         setBlockIndexCandidates.insert(invalid_walk_tip->pprev);
    2733 [ +  + ][ -  + ]:        404 :         if (invalid_walk_tip->pprev == to_mark_failed && (to_mark_failed->nStatus & BLOCK_FAILED_VALID)) {
    2734                 :            :             // We only want to mark the last disconnected block as BLOCK_FAILED_VALID; its children
    2735                 :            :             // need to be BLOCK_FAILED_CHILD instead.
    2736                 :          0 :             to_mark_failed->nStatus = (to_mark_failed->nStatus ^ BLOCK_FAILED_VALID) | BLOCK_FAILED_CHILD;
    2737         [ #  # ]:          0 :             setDirtyBlockIndex.insert(to_mark_failed);
    2738                 :            :         }
    2739                 :            : 
    2740                 :            :         // Track the last disconnected block, so we can correct its BLOCK_FAILED_CHILD status in future
    2741                 :            :         // iterations, or, if it's the last one, call InvalidChainFound on it.
    2742                 :        404 :         to_mark_failed = invalid_walk_tip;
    2743                 :            :     }
    2744                 :            : 
    2745                 :         49 :     {
    2746 [ +  - ][ #  # ]:         98 :         LOCK(cs_main);
    2747 [ -  + ][ +  - ]:         98 :         if (m_chain.Contains(to_mark_failed)) {
    2748                 :            :             // If the to-be-marked invalid block is in the active chain, something is interfering and we can't proceed.
    2749         [ #  # ]:          0 :             return false;
    2750                 :            :         }
    2751                 :            : 
    2752                 :            :         // Mark pindex (or the last disconnected block) as invalid, even when it never was in the main chain
    2753                 :         49 :         to_mark_failed->nStatus |= BLOCK_FAILED_VALID;
    2754         [ +  - ]:         49 :         setDirtyBlockIndex.insert(to_mark_failed);
    2755         [ +  - ]:         49 :         setBlockIndexCandidates.erase(to_mark_failed);
    2756         [ +  - ]:         49 :         m_blockman.m_failed_blocks.insert(to_mark_failed);
    2757                 :            : 
    2758                 :            :         // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
    2759                 :            :         // add it again.
    2760                 :         98 :         BlockMap::iterator it = m_blockman.m_block_index.begin();
    2761 [ +  + ][ +  + ]:      45378 :         while (it != m_blockman.m_block_index.end()) {
                 [ +  + ]
    2762 [ +  + ][ +  + ]:      58548 :             if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->HaveTxsDownloaded() && !setBlockIndexCandidates.value_comp()(it->second, m_chain.Tip())) {
         [ +  + ][ +  - ]
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
                 [ +  + ]
    2763 [ +  - ][ +  - ]:        108 :                 setBlockIndexCandidates.insert(it->second);
    2764                 :            :             }
    2765                 :      15077 :             it++;
    2766                 :            :         }
    2767                 :            : 
    2768         [ +  - ]:         49 :         InvalidChainFound(to_mark_failed);
    2769                 :            :     }
    2770                 :            : 
    2771                 :            :     // Only notify about a new block tip if the active chain was modified.
    2772         [ +  + ]:         49 :     if (pindex_was_in_chain) {
    2773                 :         48 :         uiInterface.NotifyBlockTip(IsInitialBlockDownload(), to_mark_failed->pprev);
    2774                 :            :     }
    2775                 :            :     return true;
    2776                 :            : }
    2777                 :            : 
    2778                 :         49 : bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex) {
    2779                 :         49 :     return ::ChainstateActive().InvalidateBlock(state, chainparams, pindex);
    2780                 :            : }
    2781                 :            : 
    2782                 :          7 : void CChainState::ResetBlockFailureFlags(CBlockIndex *pindex) {
    2783                 :          7 :     AssertLockHeld(cs_main);
    2784                 :            : 
    2785                 :          7 :     int nHeight = pindex->nHeight;
    2786                 :            : 
    2787                 :            :     // Remove the invalidity flag from this block and all its descendants.
    2788                 :         14 :     BlockMap::iterator it = m_blockman.m_block_index.begin();
    2789 [ +  + ][ +  + ]:       2946 :     while (it != m_blockman.m_block_index.end()) {
                 [ +  + ]
    2790 [ +  + ][ +  + ]:       1950 :         if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
         [ +  + ][ +  + ]
    2791                 :        210 :             it->second->nStatus &= ~BLOCK_FAILED_MASK;
    2792                 :        420 :             setDirtyBlockIndex.insert(it->second);
    2793 [ +  - ][ +  - ]:        630 :             if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->HaveTxsDownloaded() && setBlockIndexCandidates.value_comp()(m_chain.Tip(), it->second)) {
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
           [ +  -  +  - ]
    2794                 :        420 :                 setBlockIndexCandidates.insert(it->second);
    2795                 :            :             }
    2796 [ +  + ][ +  + ]:        420 :             if (it->second == pindexBestInvalid) {
    2797                 :            :                 // Reset invalid block marker if it was pointing to one of those.
    2798                 :          6 :                 pindexBestInvalid = nullptr;
    2799                 :            :             }
    2800                 :        420 :             m_blockman.m_failed_blocks.erase(it->second);
    2801                 :            :         }
    2802                 :        975 :         it++;
    2803                 :            :     }
    2804                 :            : 
    2805                 :            :     // Remove the invalidity flag from all ancestors too.
    2806         [ +  + ]:        764 :     while (pindex != nullptr) {
    2807         [ +  + ]:        757 :         if (pindex->nStatus & BLOCK_FAILED_MASK) {
    2808                 :          1 :             pindex->nStatus &= ~BLOCK_FAILED_MASK;
    2809                 :          1 :             setDirtyBlockIndex.insert(pindex);
    2810                 :          1 :             m_blockman.m_failed_blocks.erase(pindex);
    2811                 :            :         }
    2812                 :        757 :         pindex = pindex->pprev;
    2813                 :            :     }
    2814                 :          7 : }
    2815                 :            : 
    2816                 :          7 : void ResetBlockFailureFlags(CBlockIndex *pindex) {
    2817                 :          7 :     return ::ChainstateActive().ResetBlockFailureFlags(pindex);
    2818                 :            : }
    2819                 :            : 
    2820                 :      34150 : CBlockIndex* BlockManager::AddToBlockIndex(const CBlockHeader& block)
    2821                 :            : {
    2822                 :      34150 :     AssertLockHeld(cs_main);
    2823                 :            : 
    2824                 :            :     // Check for duplicate
    2825                 :      34150 :     uint256 hash = block.GetHash();
    2826                 :      34150 :     BlockMap::iterator it = m_block_index.find(hash);
    2827   [ +  +  +  +  :     102450 :     if (it != m_block_index.end())
                   +  + ]
    2828                 :          6 :         return it->second;
    2829                 :            : 
    2830                 :            :     // Construct new block index object
    2831                 :      34147 :     CBlockIndex* pindexNew = new CBlockIndex(block);
    2832                 :            :     // We assign the sequence id to blocks only when the full data is available,
    2833                 :            :     // to avoid miners withholding blocks but broadcasting headers, to get a
    2834                 :            :     // competitive advantage.
    2835                 :      34147 :     pindexNew->nSequenceId = 0;
    2836                 :      68294 :     BlockMap::iterator mi = m_block_index.insert(std::make_pair(hash, pindexNew)).first;
    2837                 :      34147 :     pindexNew->phashBlock = &((*mi).first);
    2838                 :      34147 :     BlockMap::iterator miPrev = m_block_index.find(block.hashPrevBlock);
    2839   [ +  +  +  +  :     102441 :     if (miPrev != m_block_index.end())
                   +  + ]
    2840                 :            :     {
    2841                 :      33927 :         pindexNew->pprev = (*miPrev).second;
    2842                 :      33927 :         pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
    2843                 :      33927 :         pindexNew->BuildSkip();
    2844                 :            :     }
    2845 [ +  + ][ +  + ]:      49032 :     pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
    2846         [ +  + ]:     136588 :     pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
    2847                 :      34147 :     pindexNew->RaiseValidity(BLOCK_VALID_TREE);
    2848 [ +  + ][ +  + ]:      34147 :     if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork)
    2849                 :      32028 :         pindexBestHeader = pindexNew;
    2850                 :            : 
    2851                 :      34147 :     setDirtyBlockIndex.insert(pindexNew);
    2852                 :            : 
    2853                 :      34147 :     return pindexNew;
    2854                 :            : }
    2855                 :            : 
    2856                 :            : /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
    2857                 :      32019 : void CChainState::ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos, const Consensus::Params& consensusParams)
    2858                 :            : {
    2859                 :      32019 :     pindexNew->nTx = block.vtx.size();
    2860                 :      32019 :     pindexNew->nChainTx = 0;
    2861                 :      32019 :     pindexNew->nFile = pos.nFile;
    2862                 :      32019 :     pindexNew->nDataPos = pos.nPos;
    2863                 :      32019 :     pindexNew->nUndoPos = 0;
    2864                 :      32019 :     pindexNew->nStatus |= BLOCK_HAVE_DATA;
    2865         [ +  + ]:      32019 :     if (IsWitnessEnabled(pindexNew->pprev, consensusParams)) {
    2866                 :      27456 :         pindexNew->nStatus |= BLOCK_OPT_WITNESS;
    2867                 :            :     }
    2868                 :      32019 :     pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
    2869                 :      32019 :     setDirtyBlockIndex.insert(pindexNew);
    2870                 :            : 
    2871 [ +  + ][ +  + ]:      32019 :     if (pindexNew->pprev == nullptr || pindexNew->pprev->HaveTxsDownloaded()) {
                 [ +  + ]
    2872                 :            :         // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
    2873                 :      59096 :         std::deque<CBlockIndex*> queue;
    2874         [ +  - ]:      29548 :         queue.push_back(pindexNew);
    2875                 :            : 
    2876                 :            :         // Recursively process any descendant blocks that now may be eligible to be connected.
    2877 [ +  + ][ +  + ]:     123128 :         while (!queue.empty()) {
    2878         [ +  + ]:      32016 :             CBlockIndex *pindex = queue.front();
    2879         [ +  + ]:      32016 :             queue.pop_front();
    2880         [ +  + ]:      32016 :             pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
    2881                 :      32016 :             {
    2882         [ +  - ]:      32016 :                 LOCK(cs_nBlockSequenceId);
    2883         [ +  - ]:      32016 :                 pindex->nSequenceId = nBlockSequenceId++;
    2884                 :            :             }
    2885 [ +  + ][ +  - ]:      32016 :             if (m_chain.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, m_chain.Tip())) {
         [ +  - ][ +  - ]
         [ +  - ][ +  + ]
    2886         [ +  - ]:      30349 :                 setBlockIndexCandidates.insert(pindex);
    2887                 :            :             }
    2888                 :      32016 :             std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = m_blockman.m_blocks_unlinked.equal_range(pindex);
    2889 [ +  + ][ +  + ]:      68968 :             while (range.first != range.second) {
    2890                 :       2468 :                 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
    2891 [ +  - ][ +  - ]:       4936 :                 queue.push_back(it->second);
    2892                 :       2468 :                 range.first++;
    2893                 :       2468 :                 m_blockman.m_blocks_unlinked.erase(it);
    2894                 :            :             }
    2895                 :            :         }
    2896                 :            :     } else {
    2897 [ +  - ][ +  - ]:       2471 :         if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
    2898                 :       4942 :             m_blockman.m_blocks_unlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
    2899                 :            :         }
    2900                 :            :     }
    2901                 :      32019 : }
    2902                 :            : 
    2903                 :      32019 : static bool FindBlockPos(FlatFilePos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
    2904                 :            : {
    2905 [ +  - ][ #  # ]:      96057 :     LOCK(cs_LastBlockFile);
    2906                 :            : 
    2907         [ +  + ]:      32019 :     unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
    2908 [ +  + ][ +  + ]:      64038 :     if (vinfoBlockFile.size() <= nFile) {
    2909         [ +  - ]:         73 :         vinfoBlockFile.resize(nFile + 1);
    2910                 :            :     }
    2911                 :            : 
    2912         [ +  + ]:      32019 :     if (!fKnown) {
    2913 [ +  + ][ +  + ]:      62728 :         while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
    2914                 :         10 :             nFile++;
    2915 [ -  + ][ -  + ]:         20 :             if (vinfoBlockFile.size() <= nFile) {
    2916         [ +  - ]:         10 :                 vinfoBlockFile.resize(nFile + 1);
    2917                 :            :             }
    2918                 :            :         }
    2919                 :      31354 :         pos.nFile = nFile;
    2920                 :      62708 :         pos.nPos = vinfoBlockFile[nFile].nSize;
    2921                 :            :     }
    2922                 :            : 
    2923         [ +  + ]:      32019 :     if ((int)nFile != nLastBlockFile) {
    2924         [ +  - ]:         10 :         if (!fKnown) {
    2925 [ +  - ][ +  - ]:         20 :             LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
         [ +  - ][ +  - ]
                 [ #  # ]
    2926                 :            :         }
    2927         [ +  - ]:         10 :         FlushBlockFile(!fKnown);
    2928                 :         10 :         nLastBlockFile = nFile;
    2929                 :            :     }
    2930                 :            : 
    2931 [ +  + ][ +  + ]:      64038 :     vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
    2932         [ +  + ]:      32019 :     if (fKnown)
    2933 [ +  + ][ +  + ]:       1400 :         vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
    2934                 :            :     else
    2935                 :      62708 :         vinfoBlockFile[nFile].nSize += nAddSize;
    2936                 :            : 
    2937         [ +  + ]:      32019 :     if (!fKnown) {
    2938                 :      31354 :         bool out_of_space;
    2939 [ +  - ][ +  - ]:      31354 :         size_t bytes_allocated = BlockFileSeq().Allocate(pos, nAddSize, out_of_space);
         [ +  - ][ #  # ]
    2940         [ -  + ]:      31354 :         if (out_of_space) {
    2941 [ #  # ][ #  # ]:          0 :             return AbortNode("Disk space is too low!", _("Error: Disk space is too low!").translated, CClientUIInterface::MSG_NOPREFIX);
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
    2942                 :            :         }
    2943 [ +  + ][ +  + ]:      31354 :         if (bytes_allocated != 0 && fPruneMode) {
    2944                 :          1 :             fCheckForPruning = true;
    2945                 :            :         }
    2946                 :            :     }
    2947                 :            : 
    2948         [ +  - ]:      32019 :     setDirtyFileInfo.insert(nFile);
    2949                 :      32019 :     return true;
    2950                 :            : }
    2951                 :            : 
    2952                 :      31411 : static bool FindUndoPos(CValidationState &state, int nFile, FlatFilePos &pos, unsigned int nAddSize)
    2953                 :            : {
    2954                 :      31411 :     pos.nFile = nFile;
    2955                 :            : 
    2956 [ +  - ][ #  # ]:      94233 :     LOCK(cs_LastBlockFile);
    2957                 :            : 
    2958         [ +  - ]:      31411 :     pos.nPos = vinfoBlockFile[nFile].nUndoSize;
    2959         [ +  - ]:      31411 :     vinfoBlockFile[nFile].nUndoSize += nAddSize;
    2960         [ +  - ]:      31411 :     setDirtyFileInfo.insert(nFile);
    2961                 :            : 
    2962                 :      31411 :     bool out_of_space;
    2963 [ +  - ][ +  - ]:      31411 :     size_t bytes_allocated = UndoFileSeq().Allocate(pos, nAddSize, out_of_space);
         [ +  - ][ #  # ]
    2964         [ -  + ]:      31411 :     if (out_of_space) {
    2965 [ #  # ][ #  # ]:          0 :         return AbortNode(state, "Disk space is too low!", _("Error: Disk space is too low!").translated, CClientUIInterface::MSG_NOPREFIX);
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
    2966                 :            :     }
    2967 [ +  + ][ +  + ]:      31411 :     if (bytes_allocated != 0 && fPruneMode) {
    2968                 :          1 :         fCheckForPruning = true;
    2969                 :            :     }
    2970                 :            : 
    2971                 :            :     return true;
    2972                 :            : }
    2973                 :            : 
    2974                 :     104096 : static bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
    2975                 :            : {
    2976                 :            :     // Check proof of work matches claimed amount
    2977 [ +  + ][ +  + ]:     104096 :     if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
    2978   [ +  -  +  - ]:          3 :         return state.Invalid(ValidationInvalidReason::BLOCK_INVALID_HEADER, false, REJECT_INVALID, "high-hash", "proof of work failed");
         [ +  - ][ -  + ]
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
                 [ #  # ]
    2979                 :            : 
    2980                 :            :     return true;
    2981                 :            : }
    2982                 :            : 
    2983                 :     143588 : bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
    2984                 :            : {
    2985                 :            :     // These are checks that are independent of context.
    2986                 :            : 
    2987         [ +  + ]:     143588 :     if (block.fChecked)
    2988                 :            :         return true;
    2989                 :            : 
    2990                 :            :     // Check that the header is valid (particularly PoW).  This is mostly
    2991                 :            :     // redundant with the call in AcceptBlockHeader.
    2992         [ +  + ]:      70132 :     if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
    2993                 :            :         return false;
    2994                 :            : 
    2995                 :            :     // Check the merkle root.
    2996         [ +  + ]:      70131 :     if (fCheckMerkleRoot) {
    2997                 :      41779 :         bool mutated;
    2998                 :      41779 :         uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
    2999   [ +  +  +  + ]:      83558 :         if (block.hashMerkleRoot != hashMerkleRoot2)
    3000   [ +  -  +  - ]:         33 :             return state.Invalid(ValidationInvalidReason::BLOCK_MUTATED, false, REJECT_INVALID, "bad-txnmrklroot", "hashMerkleRoot mismatch");
         [ +  - ][ -  + ]
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
                 [ #  # ]
    3001                 :            : 
    3002                 :            :         // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
    3003                 :            :         // of transactions in a block without affecting the merkle root of a block,
    3004                 :            :         // while still invalidating it.
    3005         [ +  + ]:      41768 :         if (mutated)
    3006   [ +  -  +  - ]:        775 :             return state.Invalid(ValidationInvalidReason::BLOCK_MUTATED, false, REJECT_INVALID, "bad-txns-duplicate", "duplicate transaction");
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
                 [ #  # ]
    3007                 :            :     }
    3008                 :            : 
    3009                 :            :     // All potential-corruption validation must be done before we do any
    3010                 :            :     // transaction validation, as otherwise we may mark the header as invalid
    3011                 :            :     // because we receive the wrong transactions for it.
    3012                 :            :     // Note that witness malleability is checked in ContextualCheckBlock, so no
    3013                 :            :     // checks that use witness data may be performed here.
    3014                 :            : 
    3015                 :            :     // Size limits
    3016 [ +  + ][ +  + ]:     139930 :     if (block.vtx.empty() || block.vtx.size() * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT || ::GetSerializeSize(block, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT)
         [ +  - ][ +  - ]
                 [ +  + ]
    3017   [ +  -  +  - ]:          6 :         return state.Invalid(ValidationInvalidReason::CONSENSUS, false, REJECT_INVALID, "bad-blk-length", "size limits failed");
         [ +  - ][ -  + ]
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
                 [ #  # ]
    3018                 :            : 
    3019                 :            :     // First transaction must be coinbase, the rest must not be
    3020 [ +  - ][ +  - ]:     139926 :     if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
         [ +  - ][ +  - ]
    3021   [ +  -  +  - ]:          6 :         return state.Invalid(ValidationInvalidReason::CONSENSUS, false, REJECT_INVALID, "bad-cb-missing", "first tx is not coinbase");
         [ +  - ][ -  + ]
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
                 [ #  # ]
    3022 [ +  + ][ +  + ]:     204395 :     for (unsigned int i = 1; i < block.vtx.size(); i++)
    3023 [ +  + ][ +  + ]:     193425 :         if (block.vtx[i]->IsCoinBase())
                 [ +  + ]
    3024   [ +  -  +  - ]:          6 :             return state.Invalid(ValidationInvalidReason::CONSENSUS, false, REJECT_INVALID, "bad-cb-multiple", "more than one coinbase");
         [ +  - ][ -  + ]
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
                 [ #  # ]
    3025                 :            : 
    3026                 :            :     // Check transactions
    3027 [ +  + ][ +  + ]:     344191 :     for (const auto& tx : block.vtx)
    3028         [ +  + ]:     268860 :         if (!CheckTransaction(*tx, state, true))
    3029 [ +  - ][ +  - ]:        232 :             return state.Invalid(state.GetReason(), false, state.GetRejectCode(), state.GetRejectReason(),
         [ +  - ][ +  - ]
         [ +  + ][ #  # ]
    3030   [ +  -  +  -  :        464 :                                  strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
           +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ -  + ][ #  # ]
         [ #  # ][ #  # ]
    3031                 :            : 
    3032                 :      69843 :     unsigned int nSigOps = 0;
    3033 [ +  + ][ +  + ]:     477709 :     for (const auto& tx : block.vtx)
    3034                 :            :     {
    3035                 :     268180 :         nSigOps += GetLegacySigOpCount(*tx);
    3036                 :            :     }
    3037         [ +  + ]:      69843 :     if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
    3038   [ +  -  +  - ]:         24 :         return state.Invalid(ValidationInvalidReason::CONSENSUS, false, REJECT_INVALID, "bad-blk-sigops", "out-of-bounds SigOpCount");
         [ +  - ][ -  + ]
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
                 [ #  # ]
    3039                 :            : 
    3040         [ +  + ]:      69835 :     if (fCheckPOW && fCheckMerkleRoot)
    3041                 :      41482 :         block.fChecked = true;
    3042                 :            : 
    3043                 :            :     return true;
    3044                 :            : }
    3045                 :            : 
    3046                 :     167908 : bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
    3047                 :            : {
    3048         [ #  # ]:     167908 :     LOCK(cs_main);
    3049 [ +  - ][ +  - ]:     335816 :     return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == ThresholdState::ACTIVE);
    3050                 :            : }
    3051                 :            : 
    3052                 :      63733 : bool IsNullDummyEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
    3053                 :            : {
    3054         [ #  # ]:      63733 :     LOCK(cs_main);
    3055 [ +  - ][ +  - ]:     127466 :     return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == ThresholdState::ACTIVE);
    3056                 :            : }
    3057                 :            : 
    3058                 :            : // Compute at which vout of the block's coinbase transaction the witness
    3059                 :            : // commitment occurs, or -1 if not found.
    3060                 :      69760 : static int GetWitnessCommitmentIndex(const CBlock& block)
    3061                 :            : {
    3062                 :      69760 :     int commitpos = -1;
    3063 [ +  - ][ +  - ]:     139520 :     if (!block.vtx.empty()) {
    3064 [ +  + ][ +  + ]:     330269 :         for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
                 [ +  + ]
    3065 [ +  + ][ +  + ]:     707429 :             if (block.vtx[0]->vout[o].scriptPubKey.size() >= 38 && block.vtx[0]->vout[o].scriptPubKey[0] == OP_RETURN && block.vtx[0]->vout[o].scriptPubKey[1] == 0x24 && block.vtx[0]->vout[o].scriptPubKey[2] == 0xaa && block.vtx[0]->vout[o].scriptPubKey[3] == 0x21 && block.vtx[0]->vout[o].scriptPubKey[4] == 0xa9 && block.vtx[0]->vout[o].scriptPubKey[5] == 0xed) {
         [ +  + ][ +  + ]
         [ -  + ][ -  + ]
         [ +  + ][ -  + ]
         [ -  + ][ +  - ]
         [ -  + ][ -  + ]
         [ +  - ][ -  + ]
         [ -  + ][ +  - ]
         [ -  + ][ -  + ]
         [ +  - ][ -  + ]
         [ -  + ][ +  - ]
    3066                 :      47954 :                 commitpos = o;
    3067                 :            :             }
    3068                 :            :         }
    3069                 :            :     }
    3070                 :      69760 :     return commitpos;
    3071                 :            : }
    3072                 :            : 
    3073                 :      15506 : void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
    3074                 :            : {
    3075                 :      15506 :     int commitpos = GetWitnessCommitmentIndex(block);
    3076 [ +  - ][ +  - ]:      15506 :     static const std::vector<unsigned char> nonce(32, 0x00);
         [ +  - ][ +  + ]
    3077 [ +  + ][ +  + ]:      28446 :     if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
                 [ +  + ]
    3078                 :      25538 :         CMutableTransaction tx(*block.vtx[0]);
    3079   [ +  -  +  - ]:      25538 :         tx.vin[0].scriptWitness.stack.resize(1);
    3080 [ +  - ][ +  - ]:      38307 :         tx.vin[0].scriptWitness.stack[0] = nonce;
                 [ +  - ]
    3081 [ +  - ][ +  - ]:      25538 :         block.vtx[0] = MakeTransactionRef(std::move(tx));
         [ +  - ][ -  + ]
    3082                 :            :     }
    3083                 :      15506 : }
    3084                 :            : 
    3085                 :      15312 : std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
    3086                 :            : {
    3087                 :      15312 :     std::vector<unsigned char> commitment;
    3088                 :      15312 :     int commitpos = GetWitnessCommitmentIndex(block);
    3089         [ #  # ]:      30624 :     std::vector<unsigned char> ret(32, 0x00);
           [ +  -  +  - ]
    3090         [ +  + ]:      15312 :     if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
    3091         [ +  - ]:      15311 :         if (commitpos == -1) {
    3092         [ +  - ]:      15311 :             uint256 witnessroot = BlockWitnessMerkleRoot(block, nullptr);
    3093 [ +  - ][ +  - ]:      15311 :             CHash256().Write(witnessroot.begin(), 32).Write(ret.data(), 32).Finalize(witnessroot.begin());
         [ +  - ][ +  - ]
                 [ +  - ]
    3094         [ #  # ]:      15311 :             CTxOut out;
    3095                 :      15311 :             out.nValue = 0;
    3096                 :      15311 :             out.scriptPubKey.resize(38);
    3097         [ +  - ]:      15311 :             out.scriptPubKey[0] = OP_RETURN;
    3098         [ +  - ]:      15311 :             out.scriptPubKey[1] = 0x24;
    3099         [ +  - ]:      15311 :             out.scriptPubKey[2] = 0xaa;
    3100         [ +  - ]:      15311 :             out.scriptPubKey[3] = 0x21;
    3101         [ +  - ]:      15311 :             out.scriptPubKey[4] = 0xa9;
    3102         [ +  - ]:      15311 :             out.scriptPubKey[5] = 0xed;
    3103 [ +  - ][ +  - ]:      30622 :             memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
    3104 [ +  - ][ +  - ]:      61244 :             commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
         [ +  - ][ +  - ]
         [ -  + ][ +  - ]
    3105 [ +  - ][ +  - ]:      61244 :             CMutableTransaction tx(*block.vtx[0]);
           [ +  -  +  - ]
    3106         [ +  - ]:      15311 :             tx.vout.push_back(out);
    3107 [ +  - ][ +  - ]:      30622 :             block.vtx[0] = MakeTransactionRef(std::move(tx));
         [ +  - ][ -  + ]
    3108                 :            :         }
    3109                 :            :     }
    3110         [ +  - ]:      15312 :     UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
    3111         [ +  - ]:      30624 :     return commitment;
    3112                 :            : }
    3113                 :            : 
    3114                 :            : //! Returns last CBlockIndex* that is a checkpoint
    3115                 :      47994 : static CBlockIndex* GetLastCheckpoint(const CCheckpointData& data) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
    3116                 :            : {
    3117                 :      47994 :     const MapCheckpoints& checkpoints = data.mapCheckpoints;
    3118                 :            : 
    3119 [ +  - ][ +  - ]:      47994 :     for (const MapCheckpoints::value_type& i : reverse_iterate(checkpoints))
    3120                 :            :     {
    3121                 :      47994 :         const uint256& hash = i.second;
    3122                 :      47994 :         CBlockIndex* pindex = LookupBlockIndex(hash);
    3123         [ -  + ]:      47994 :         if (pindex) {
    3124                 :            :             return pindex;
    3125                 :            :         }
    3126                 :            :     }
    3127                 :            :     return nullptr;
    3128                 :            : }
    3129                 :            : 
    3130                 :            : /** Context-dependent validity checks.
    3131                 :            :  *  By "context", we mean only the previous block headers, but not the UTXO
    3132                 :            :  *  set; UTXO-related validity checks are done in ConnectBlock().
    3133                 :            :  *  NOTE: This function is not currently invoked by ConnectBlock(), so we
    3134                 :            :  *  should consider upgrade issues if we change which consensus rules are
    3135                 :            :  *  enforced in this function (eg by adding a new consensus rule). See comment
    3136                 :            :  *  in ConnectBlock().
    3137                 :            :  *  Note that -reindex-chainstate skips the validation that happens here!
    3138                 :            :  */
    3139                 :      48125 : static bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
    3140                 :            : {
    3141         [ -  + ]:      48125 :     assert(pindexPrev != nullptr);
    3142                 :      48125 :     const int nHeight = pindexPrev->nHeight + 1;
    3143                 :            : 
    3144                 :            :     // Check proof of work
    3145                 :      48125 :     const Consensus::Params& consensusParams = params.GetConsensus();
    3146         [ +  + ]:      48125 :     if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
    3147   [ +  -  +  - ]:          6 :         return state.Invalid(ValidationInvalidReason::BLOCK_INVALID_HEADER, false, REJECT_INVALID, "bad-diffbits", "incorrect proof of work");
         [ +  - ][ -  + ]
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
                 [ #  # ]
    3148                 :            : 
    3149                 :            :     // Check against checkpoints
    3150         [ +  + ]:      48123 :     if (fCheckpointsEnabled) {
    3151                 :            :         // Don't accept any forks from the main chain prior to last checkpoint.
    3152                 :            :         // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
    3153                 :            :         // g_blockman.m_block_index.
    3154                 :      95988 :         CBlockIndex* pcheckpoint = GetLastCheckpoint(params.Checkpoints());
    3155 [ -  + ][ +  - ]:      47994 :         if (pcheckpoint && nHeight < pcheckpoint->nHeight)
    3156   [ #  #  #  # ]:          0 :             return state.Invalid(ValidationInvalidReason::BLOCK_CHECKPOINT, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), REJECT_CHECKPOINT, "bad-fork-prior-to-checkpoint");
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
    3157                 :            :     }
    3158                 :            : 
    3159                 :            :     // Check timestamp against prev
    3160         [ +  + ]:      96246 :     if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
    3161   [ +  -  +  - ]:         18 :         return state.Invalid(ValidationInvalidReason::BLOCK_INVALID_HEADER, false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
         [ +  - ][ -  + ]
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
                 [ #  # ]
    3162                 :            : 
    3163                 :            :     // Check timestamp
    3164 [ +  + ][ +  + ]:      96234 :     if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
    3165   [ +  -  +  - ]:         12 :         return state.Invalid(ValidationInvalidReason::BLOCK_TIME_FUTURE, false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
         [ +  - ][ -  + ]
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
                 [ #  # ]
    3166                 :            : 
    3167                 :            :     // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
    3168                 :            :     // check for version 2, 3 and 4 upgrades
    3169 [ +  + ][ +  + ]:      48113 :     if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
                 [ +  + ]
    3170 [ +  + ][ +  + ]:      48112 :        (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
    3171         [ +  + ]:       1571 :        (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
    3172 [ +  - ][ +  - ]:          6 :             return state.Invalid(ValidationInvalidReason::BLOCK_INVALID_HEADER, false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
         [ #  # ][ +  - ]
    3173 [ +  - ][ #  # ]:          6 :                                  strprintf("rejected nVersion=0x%08x block", block.nVersion));
    3174                 :            : 
    3175                 :            :     return true;
    3176                 :            : }
    3177                 :            : 
    3178                 :            : /** NOTE: This function is not currently invoked by ConnectBlock(), so we
    3179                 :            :  *  should consider upgrade issues if we change which consensus rules are
    3180                 :            :  *  enforced in this function (eg by adding a new consensus rule). See comment
    3181                 :            :  *  in ConnectBlock().
    3182                 :            :  *  Note that -reindex-chainstate skips the validation that happens here!
    3183                 :            :  */
    3184                 :      46000 : static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
    3185                 :            : {
    3186         [ +  + ]:      46000 :     const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
    3187                 :            : 
    3188                 :            :     // Start enforcing BIP113 (Median Time Past) using versionbits logic.
    3189                 :      46000 :     int nLockTimeFlags = 0;
    3190         [ +  + ]:      46000 :     if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == ThresholdState::ACTIVE) {
    3191         [ -  + ]:       4475 :         assert(pindexPrev != nullptr);
    3192                 :            :         nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
    3193                 :            :     }
    3194                 :            : 
    3195                 :      46000 :     int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
    3196         [ +  + ]:      46000 :                               ? pindexPrev->GetMedianTimePast()
    3197                 :      83050 :                               : block.GetBlockTime();
    3198                 :            : 
    3199                 :            :     // Check that all transactions are finalized
    3200 [ +  + ][ +  + ]:     235994 :     for (const auto& tx : block.vtx) {
    3201         [ +  + ]:     196002 :         if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
    3202   [ +  -  +  - ]:         35 :             return state.Invalid(ValidationInvalidReason::CONSENSUS, false, REJECT_INVALID, "bad-txns-nonfinal", "non-final transaction");
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
                 [ #  # ]
    3203                 :            :         }
    3204                 :            :     }
    3205                 :            : 
    3206                 :            :     // Enforce rule that the coinbase starts with serialized block height
    3207         [ +  + ]:      45993 :     if (nHeight >= consensusParams.BIP34Height)
    3208                 :            :     {
    3209 [ +  - ][ +  - ]:      21368 :         CScript expect = CScript() << nHeight;
         [ -  + ][ -  + ]
    3210 [ -  + ][ -  + ]:      35614 :         if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
         [ -  + ][ -  + ]
                 [ -  + ]
           [ +  +  -  + ]
    3211 [ +  - ][ +  - ]:      28488 :             !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
         [ +  - ][ -  + ]
    3212 [ +  - ][ +  - ]:          5 :             return state.Invalid(ValidationInvalidReason::CONSENSUS, false, REJECT_INVALID, "bad-cb-height", "block height mismatch in coinbase");
         [ +  - ][ +  - ]
         [ +  - ][ -  + ]
         [ +  - ][ +  - ]
         [ -  + ][ -  + ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
                 [ #  # ]
    3213                 :            :         }
    3214                 :            :     }
    3215                 :            : 
    3216                 :            :     // Validation for witness commitments.
    3217                 :            :     // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
    3218                 :            :     //   coinbase (where 0x0000....0000 is used instead).
    3219                 :            :     // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness reserved value (unconstrained).
    3220                 :            :     // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
    3221                 :            :     // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
    3222                 :            :     //   {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness reserved value). In case there are
    3223                 :            :     //   multiple, the last one is used.
    3224                 :      45992 :     bool fHaveWitness = false;
    3225         [ +  + ]:      45992 :     if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == ThresholdState::ACTIVE) {
    3226                 :      38942 :         int commitpos = GetWitnessCommitmentIndex(block);
    3227         [ +  + ]:      38942 :         if (commitpos != -1) {
    3228                 :      32385 :             bool malleated = false;
    3229                 :      32385 :             uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
    3230                 :            :             // The malleation check is ignored; as the transaction tree itself
    3231                 :            :             // already does not permit it, it is impossible to trigger in the
    3232                 :            :             // witness tree.
    3233 [ +  - ][ +  - ]:     161925 :             if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
         [ +  - ][ +  +  
          +  +  +  +  +  
                +  +  + ]
    3234   [ +  -  +  - ]:          8 :                 return state.Invalid(ValidationInvalidReason::BLOCK_MUTATED, false, REJECT_INVALID, "bad-witness-nonce-size", strprintf("%s : invalid witness reserved value size", __func__));
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
                 [ #  # ]
    3235                 :            :             }
    3236                 :      32383 :             CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
    3237 [ +  + ][ -  +  :     161915 :             if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
          -  +  -  +  -  
                      + ]
    3238   [ +  -  +  - ]:         12 :                 return state.Invalid(ValidationInvalidReason::BLOCK_MUTATED, false, REJECT_INVALID, "bad-witness-merkle-match", strprintf("%s : witness merkle commitment mismatch", __func__));
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
                 [ #  # ]
    3239                 :            :             }
    3240                 :            :             fHaveWitness = true;
    3241                 :            :         }
    3242                 :            :     }
    3243                 :            : 
    3244                 :            :     // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
    3245                 :            :     if (!fHaveWitness) {
    3246 [ +  + ][ +  + ]:      76530 :       for (const auto& tx : block.vtx) {
    3247         [ +  + ]:     107145 :             if (tx->HasWitness()) {
    3248   [ +  -  +  - ]:         24 :                 return state.Invalid(ValidationInvalidReason::BLOCK_MUTATED, false, REJECT_INVALID, "unexpected-witness", strprintf("%s : unexpected witness data found", __func__));
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
                 [ #  # ]
    3249                 :            :             }
    3250                 :            :         }
    3251                 :            :     }
    3252                 :            : 
    3253                 :            :     // After the coinbase witness reserved value and commitment are verified,
    3254                 :            :     // we can check if the block weight passes (before we've checked the
    3255                 :            :     // coinbase witness, it would be possible for the weight to be too
    3256                 :            :     // large by filling up the coinbase witness, which doesn't change
    3257                 :            :     // the block hash, so we couldn't mark the block as permanently
    3258                 :            :     // failed).
    3259         [ +  + ]:      45981 :     if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
    3260   [ +  -  +  - ]:          2 :         return state.Invalid(ValidationInvalidReason::CONSENSUS, false, REJECT_INVALID, "bad-blk-weight", strprintf("%s : weight limit failed", __func__));
         [ +  - ][ -  + ]
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
                 [ #  # ]
    3261                 :            :     }
    3262                 :            : 
    3263                 :            :     return true;
    3264                 :            : }
    3265                 :            : 
    3266                 :      77165 : bool BlockManager::AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
    3267                 :            : {
    3268                 :      77165 :     AssertLockHeld(cs_main);
    3269                 :            :     // Check for duplicate
    3270                 :      77165 :     uint256 hash = block.GetHash();
    3271                 :      77165 :     BlockMap::iterator miSelf = m_block_index.find(hash);
    3272                 :      77165 :     CBlockIndex *pindex = nullptr;
    3273   [ +  +  +  +  :     231495 :     if (hash != chainparams.GetConsensus().hashGenesisBlock) {
                   +  + ]
    3274 [ +  + ][ +  + ]:     231471 :         if (miSelf != m_block_index.end()) {
                 [ +  + ]
    3275                 :            :             // Block header is already known.
    3276         [ +  - ]:      43193 :             pindex = miSelf->second;
    3277         [ +  - ]:      43193 :             if (ppindex)
    3278                 :      43193 :                 *ppindex = pindex;
    3279         [ +  + ]:      43193 :             if (pindex->nStatus & BLOCK_FAILED_MASK)
    3280   [ +  -  +  - ]:        396 :                 return state.Invalid(ValidationInvalidReason::CACHED_INVALID, error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
         [ +  - ][ +  - ]
         [ +  - ][ +  - ]
         [ -  + ][ -  + ]
         [ -  + ][ #  # ]
         [ #  # ][ #  # ]
                 [ #  # ]
    3281                 :            :             return true;
    3282                 :            :         }
    3283                 :            : 
    3284         [ -  + ]:      67928 :         if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
    3285 [ #  # ][ #  # ]:          0 :             return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
    3286                 :            : 
    3287                 :            :         // Get prev block index
    3288                 :      33964 :         CBlockIndex* pindexPrev = nullptr;
    3289                 :      33964 :         BlockMap::iterator mi = m_block_index.find(block.hashPrevBlock);
    3290   [ +  +  +  +  :     101892 :         if (mi == m_block_index.end())
                   +  + ]
    3291   [ +  -  +  - ]:         15 :             return state.Invalid(ValidationInvalidReason::BLOCK_MISSING_PREV, error("%s: prev block not found", __func__), 0, "prev-blk-not-found");
         [ +  - ][ +  - ]
         [ +  - ][ -  + ]
         [ -  + ][ #  # ]
         [ #  # ][ #  # ]
    3292         [ +  + ]:      33961 :         pindexPrev = (*mi).second;
    3293         [ +  + ]:      33961 :         if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
    3294   [ +  -  +  - ]:         63 :             return state.Invalid(ValidationInvalidReason::BLOCK_INVALID_PREV, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
         [ +  - ][ +  - ]
         [ -  + ][ -  + ]
         [ -  + ][ #  # ]
         [ #  # ][ #  # ]
    3295         [ +  + ]:      33940 :         if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
    3296 [ +  - ][ +  - ]:         24 :             return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
    3297                 :            : 
    3298                 :            :         /* Determine if this block descends from any block which has been found
    3299                 :            :          * invalid (m_failed_blocks), then mark pindexPrev and any blocks between
    3300                 :            :          * them as failed. For example:
    3301                 :            :          *
    3302                 :            :          *                D3
    3303                 :            :          *              /
    3304                 :            :          *      B2 - C2
    3305                 :            :          *    /         \
    3306                 :            :          *  A             D2 - E2 - F2
    3307                 :            :          *    \
    3308                 :            :          *      B1 - C1 - D1 - E1
    3309                 :            :          *
    3310                 :            :          * In the case that we attempted to reorg from E1 to F2, only to find
    3311                 :            :          * C2 to be invalid, we would mark D2, E2, and F2 as BLOCK_FAILED_CHILD
    3312                 :            :          * but NOT D3 (it was not in any of our candidate sets at the time).
    3313                 :            :          *
    3314                 :            :          * In any case D3 will also be marked as BLOCK_FAILED_CHILD at restart
    3315                 :            :          * in LoadBlockIndex.
    3316                 :            :          */
    3317 [ +  - ][ +  + ]:      33928 :         if (!pindexPrev->IsValid(BLOCK_VALID_SCRIPTS)) {
    3318                 :            :             // The above does not mean "invalid": it checks if the previous block
    3319                 :            :             // hasn't been validated up to BLOCK_VALID_SCRIPTS. This is a performance
    3320                 :            :             // optimization, in the common case of adding a new block to the tip,
    3321                 :            :             // we don't need to iterate over the failed blocks list.
    3322 [ +  + ][ +  + ]:      96234 :             for (const CBlockIndex* failedit : m_failed_blocks) {
    3323         [ +  + ]:      48184 :                 if (pindexPrev->GetAncestor(failedit->nHeight) == failedit) {
    3324         [ -  + ]:          1 :                     assert(failedit->nStatus & BLOCK_FAILED_VALID);
    3325                 :          1 :                     CBlockIndex* invalid_walk = pindexPrev;
    3326         [ +  + ]:          2 :                     while (invalid_walk != failedit) {
    3327                 :          1 :                         invalid_walk->nStatus |= BLOCK_FAILED_CHILD;
    3328                 :          1 :                         setDirtyBlockIndex.insert(invalid_walk);
    3329                 :          1 :                         invalid_walk = invalid_walk->pprev;
    3330                 :            :                     }
    3331   [ +  -  +  - ]:          3 :                     return state.Invalid(ValidationInvalidReason::BLOCK_INVALID_PREV, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
         [ +  - ][ +  - ]
         [ -  + ][ -  + ]
         [ -  + ][ #  # ]
         [ #  # ][ #  # ]
    3332                 :            :                 }
    3333                 :            :             }
    3334                 :            :         }
    3335                 :            :     }
    3336                 :      33935 :     if (pindex == nullptr)
    3337                 :      33935 :         pindex = AddToBlockIndex(block);
    3338                 :            : 
    3339         [ +  - ]:      33935 :     if (ppindex)
    3340                 :      33935 :         *ppindex = pindex;
    3341                 :            : 
    3342                 :            :     return true;
    3343                 :            : }
    3344                 :            : 
    3345                 :            : // Exposed wrapper for AcceptBlockHeader
    3346                 :      12293 : bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex, CBlockHeader *first_invalid)
    3347                 :            : {
    3348         [ +  + ]:      12293 :     if (first_invalid != nullptr) first_invalid->SetNull();
    3349                 :      12293 :     {
    3350 [ +  - ][ #  # ]:      24553 :         LOCK(cs_main);
    3351 [ +  + ][ +  + ]:      68606 :         for (const CBlockHeader& header : headers) {
    3352                 :      31760 :             CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
    3353         [ +  - ]:      31760 :             bool accepted = g_blockman.AcceptBlockHeader(header, state, chainparams, &pindex);
    3354 [ +  - ][ +  - ]:      63520 :             ::ChainstateActive().CheckBlockIndex(chainparams.GetConsensus());
    3355                 :            : 
    3356         [ +  + ]:      31760 :             if (!accepted) {
    3357         [ +  + ]:         33 :                 if (first_invalid) *first_invalid = header;
    3358         [ +  - ]:         33 :                 return false;
    3359                 :            :             }
    3360         [ +  + ]:      31727 :             if (ppindex) {
    3361                 :      31456 :                 *ppindex = pindex;
    3362                 :            :             }
    3363                 :            :         }
    3364                 :            :     }
    3365                 :      12260 :     NotifyHeaderTip();
    3366                 :      12260 :     return true;
    3367                 :            : }
    3368                 :            : 
    3369                 :            : /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
    3370                 :      32019 : static FlatFilePos SaveBlockToDisk(const CBlock& block, int nHeight, const CChainParams& chainparams, const FlatFilePos* dbp) {
    3371                 :      32019 :     unsigned int nBlockSize = ::GetSerializeSize(block, CLIENT_VERSION);
    3372         [ +  + ]:      32019 :     FlatFilePos blockPos;
    3373         [ +  + ]:      32019 :     if (dbp != nullptr)
    3374                 :        665 :         blockPos = *dbp;
    3375         [ -  + ]:      64038 :     if (!FindBlockPos(blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != nullptr)) {
    3376                 :          0 :         error("%s: FindBlockPos failed", __func__);
    3377                 :          0 :         return FlatFilePos();
    3378                 :            :     }
    3379         [ +  + ]:      32019 :     if (dbp == nullptr) {
    3380         [ -  + ]:      62708 :         if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) {
    3381   [ #  #  #  # ]:          0 :             AbortNode("Failed to write block");
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
                 [ #  # ]
    3382                 :          0 :             return FlatFilePos();
    3383                 :            :         }
    3384                 :            :     }
    3385                 :      32019 :     return blockPos;
    3386                 :            : }
    3387                 :            : 
    3388                 :            : /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
    3389                 :      45405 : bool CChainState::AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const FlatFilePos* dbp, bool* fNewBlock)
    3390                 :            : {
    3391         [ +  + ]:      45405 :     const CBlock& block = *pblock;
    3392                 :            : 
    3393         [ +  + ]:      45405 :     if (fNewBlock) *fNewBlock = false;
    3394                 :      45405 :     AssertLockHeld(cs_main);
    3395                 :            : 
    3396                 :      45405 :     CBlockIndex *pindexDummy = nullptr;
    3397         [ +  + ]:      45405 :     CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
    3398                 :            : 
    3399                 :      45405 :     bool accepted_header = m_blockman.AcceptBlockHeader(block, state, chainparams, &pindex);
    3400                 :      90810 :     CheckBlockIndex(chainparams.GetConsensus());
    3401                 :            : 
    3402         [ +  + ]:      45405 :     if (!accepted_header)
    3403                 :            :         return false;
    3404                 :            : 
    3405                 :            :     // Try to process all requested blocks that we don't have, but only
    3406                 :            :     // process an unrequested block if it's new and has enough work to
    3407                 :            :     // advance our tip, and isn't too many blocks ahead.
    3408                 :      45302 :     bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
    3409 [ +  + ][ +  - ]:      45302 :     bool fHasMoreOrSameWork = (m_chain.Tip() ? pindex->nChainWork >= m_chain.Tip()->nChainWork : true);
                 [ +  + ]
    3410                 :            :     // Blocks that are too out-of-order needlessly limit the effectiveness of
    3411                 :            :     // pruning, because pruning will not delete block files that contain any
    3412                 :            :     // blocks which are too close in height to the tip.  Apply this test
    3413                 :            :     // regardless of whether pruning is enabled; it should generally be safe to
    3414                 :            :     // not process unrequested blocks.
    3415         [ +  + ]:      45302 :     bool fTooFarAhead = (pindex->nHeight > int(m_chain.Height() + MIN_BLOCKS_TO_KEEP));
    3416                 :            : 
    3417                 :            :     // TODO: Decouple this function from the block download logic by removing fRequested
    3418                 :            :     // This requires some new chain data structure to efficiently look up if a
    3419                 :            :     // block is in a chain leading to a candidate for best tip, despite not
    3420                 :            :     // being such a candidate itself.
    3421                 :            : 
    3422                 :            :     // TODO: deal better with return value and error conditions for duplicate
    3423                 :            :     // and unrequested blocks.
    3424         [ +  + ]:      45302 :     if (fAlreadyHave) return true;
    3425         [ +  + ]:      32917 :     if (!fRequested) {  // If we didn't ask for it:
    3426         [ +  - ]:       1701 :         if (pindex->nTx != 0) return true;    // This is a previously-processed block that was pruned
    3427         [ +  + ]:       1701 :         if (!fHasMoreOrSameWork) return true; // Don't process less-work chains
    3428         [ +  + ]:        609 :         if (fTooFarAhead) return true;        // Block height is too high
    3429                 :            : 
    3430                 :            :         // Protect against DoS attacks from low-work chains.
    3431                 :            :         // If our tip is behind, a peer could try to send us
    3432                 :            :         // low-work blocks on a fake chain that we would never
    3433                 :            :         // request; don't process these.
    3434         [ +  + ]:        608 :         if (pindex->nChainWork < nMinimumChainWork) return true;
    3435                 :            :     }
    3436                 :            : 
    3437   [ +  -  +  + ]:      95469 :     if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
    3438                 :      63646 :         !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
    3439 [ -  + ][ -  + ]:         57 :         assert(IsBlockReason(state.GetReason()));
                 [ -  + ]
    3440 [ +  - ][ +  - ]:         38 :         if (state.IsInvalid() && state.GetReason() != ValidationInvalidReason::BLOCK_MUTATED) {
         [ +  + ][ +  + ]
    3441                 :          8 :             pindex->nStatus |= BLOCK_FAILED_VALID;
    3442                 :          8 :             setDirtyBlockIndex.insert(pindex);
    3443                 :            :         }
    3444 [ +  - ][ +  - ]:         19 :         return error("%s: %s", __func__, FormatStateMessage(state));
                 [ #  # ]
    3445                 :            :     }
    3446                 :            : 
    3447                 :            :     // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
    3448                 :            :     // (but if it does not build on our best tip, let the SendMessages loop relay it)
    3449 [ +  + ][ +  - ]:      58996 :     if (!IsInitialBlockDownload() && m_chain.Tip() == pindex->pprev)
                 [ +  + ]
    3450                 :      23689 :         GetMainSignals().NewPoWValidBlock(pindex, pblock);
    3451                 :            : 
    3452                 :            :     // Write block to history file
    3453         [ +  + ]:      31804 :     if (fNewBlock) *fNewBlock = true;
    3454                 :      31804 :     try {
    3455         [ +  - ]:      31804 :         FlatFilePos blockPos = SaveBlockToDisk(block, pindex->nHeight, chainparams, dbp);
    3456 [ -  + ][ -  + ]:      63608 :         if (blockPos.IsNull()) {
    3457 [ #  # ][ #  # ]:          0 :             state.Error(strprintf("%s: Failed to find position to write new block to disk", __func__));
         [ #  # ][ #  # ]
    3458                 :          0 :             return false;
    3459                 :            :         }
    3460 [ +  - ][ +  - ]:      63608 :         ReceivedBlockTransactions(block, pindex, blockPos, chainparams.GetConsensus());
    3461                 :          0 :     } catch (const std::runtime_error& e) {
    3462   [ #  #  #  # ]:          0 :         return AbortNode(state, std::string("System error: ") + e.what());
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
           [ #  #  #  # ]
    3463                 :            :     }
    3464                 :            : 
    3465                 :      31804 :     FlushStateToDisk(chainparams, state, FlushStateMode::NONE);
    3466                 :            : 
    3467                 :      31804 :     CheckBlockIndex(chainparams.GetConsensus());
    3468                 :            : 
    3469                 :      31804 :     return true;
    3470                 :            : }
    3471                 :            : 
    3472                 :      45029 : bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
    3473                 :            : {
    3474                 :      45029 :     AssertLockNotHeld(cs_main);
    3475                 :            : 
    3476                 :      45029 :     {
    3477                 :      45029 :         CBlockIndex *pindex = nullptr;
    3478         [ +  + ]:      45029 :         if (fNewBlock) *fNewBlock = false;
    3479         [ +  - ]:      45029 :         CValidationState state;
    3480                 :            : 
    3481                 :            :         // CheckBlock() does not support multi-threaded block validation because CBlock::fChecked can cause data race.
    3482                 :            :         // Therefore, the following critical section must include the CheckBlock() call as well.
    3483 [ +  - ][ +  - ]:     134265 :         LOCK(cs_main);
                 [ #  # ]
    3484                 :            : 
    3485                 :            :         // Ensure that CheckBlock() passes before calling AcceptBlock, as
    3486                 :            :         // belt-and-suspenders.
    3487 [ +  - ][ +  - ]:     135087 :         bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
                 [ +  - ]
    3488         [ +  + ]:      45029 :         if (ret) {
    3489                 :            :             // Store to disk
    3490         [ +  - ]:      44740 :             ret = ::ChainstateActive().AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, nullptr, fNewBlock);
    3491                 :            :         }
    3492         [ +  + ]:      45029 :         if (!ret) {
    3493 [ +  - ][ +  - ]:        411 :             GetMainSignals().BlockChecked(*pblock, state);
                 [ +  - ]
    3494 [ +  - ][ +  - ]:        822 :             return error("%s: AcceptBlock FAILED (%s)", __func__, FormatStateMessage(state));
         [ +  - ][ +  - ]
                 [ #  # ]
    3495                 :            :         }
    3496                 :            :     }
    3497                 :            : 
    3498                 :      44618 :     NotifyHeaderTip();
    3499                 :            : 
    3500                 :      89236 :     CValidationState state; // Only used to report errors, not invalidity - ignore it
    3501 [ +  - ][ +  + ]:      89236 :     if (!::ChainstateActive().ActivateBestChain(state, chainparams, pblock))
         [ #  # ][ +  - ]
    3502 [ +  - ][ +  - ]:          1 :         return error("%s: ActivateBestChain failed (%s)", __func__, FormatStateMessage(state));
         [ +  - ][ #  # ]
    3503                 :            : 
    3504                 :            :     return true;
    3505                 :            : }
    3506                 :            : 
    3507                 :      14185 : bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
    3508                 :            : {
    3509                 :      14185 :     AssertLockHeld(cs_main);
    3510 [ +  - ][ +  - ]:      28370 :     assert(pindexPrev && pindexPrev == ::ChainActive().Tip());
                 [ -  + ]
    3511                 :      42555 :     CCoinsViewCache viewNew(pcoinsTip.get());
    3512         [ +  - ]:      14185 :     uint256 block_hash(block.GetHash());
    3513                 :      14185 :     CBlockIndex indexDummy(block);
    3514                 :      14185 :     indexDummy.pprev = pindexPrev;
    3515                 :      14185 :     indexDummy.nHeight = pindexPrev->nHeight + 1;
    3516                 :      14185 :     indexDummy.phashBlock = &block_hash;
    3517                 :            : 
    3518                 :            :     // NOTE: CheckBlockHeader is called by CheckBlock
    3519 [ +  - ][ +  + ]:      14185 :     if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
                 [ +  - ]
    3520 [ +  - ][ +  - ]:          3 :         return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
         [ +  - ][ #  # ]
    3521 [ +  - ][ +  - ]:      28364 :     if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
                 [ +  + ]
    3522 [ +  - ][ +  - ]:          5 :         return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
         [ +  - ][ #  # ]
    3523 [ +  - ][ +  - ]:      28354 :     if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
                 [ +  + ]
    3524 [ +  - ][ +  - ]:          1 :         return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
         [ +  - ][ #  # ]
    3525 [ +  - ][ +  + ]:      14176 :     if (!::ChainstateActive().ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
    3526                 :            :         return false;
    3527 [ -  + ][ -  + ]:      28344 :     assert(state.IsValid());
    3528                 :            : 
    3529                 :            :     return true;
    3530                 :            : }
    3531                 :            : 
    3532                 :            : /**
    3533                 :            :  * BLOCK PRUNING CODE
    3534                 :            :  */
    3535                 :            : 
    3536                 :            : /* Calculate the amount of disk space the block & undo files currently use */
    3537                 :        283 : uint64_t CalculateCurrentUsage()
    3538                 :            : {
    3539                 :        283 :     LOCK(cs_LastBlockFile);
    3540                 :            : 
    3541                 :        283 :     uint64_t retval = 0;
    3542 [ +  + ][ +  + ]:       1415 :     for (const CBlockFileInfo &file : vinfoBlockFile) {
    3543                 :        283 :         retval += file.nSize + file.nUndoSize;
    3544                 :            :     }
    3545         [ +  - ]:        283 :     return retval;
    3546                 :            : }
    3547                 :            : 
    3548                 :            : /* Prune a block file (modify associated database entries)*/
    3549                 :          3 : void PruneOneBlockFile(const int fileNumber)
    3550                 :            : {
    3551         [ #  # ]:          3 :     LOCK(cs_LastBlockFile);
    3552                 :            : 
    3553 [ +  + ][ +  + ]:        315 :     for (const auto& entry : g_blockman.m_block_index) {
                 [ +  + ]
    3554                 :        306 :         CBlockIndex* pindex = entry.second;
    3555         [ +  + ]:        306 :         if (pindex->nFile == fileNumber) {
    3556                 :        203 :             pindex->nStatus &= ~BLOCK_HAVE_DATA;
    3557                 :        203 :             pindex->nStatus &= ~BLOCK_HAVE_UNDO;
    3558                 :        203 :             pindex->nFile = 0;
    3559                 :        203 :             pindex->nDataPos = 0;
    3560                 :        203 :             pindex->nUndoPos = 0;
    3561         [ +  - ]:        203 :             setDirtyBlockIndex.insert(pindex);
    3562                 :            : 
    3563                 :            :             // Prune from m_blocks_unlinked -- any block we prune would have
    3564                 :            :             // to be downloaded again in order to consider its chain, at which
    3565                 :            :             // point it would be considered as a candidate for
    3566                 :            :             // m_blocks_unlinked or setBlockIndexCandidates.
    3567                 :        203 :             auto range = g_blockman.m_blocks_unlinked.equal_range(pindex->pprev);
    3568 [ -  + ][ -  + ]:        406 :             while (range.first != range.second) {
    3569                 :          0 :                 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
    3570         [ #  # ]:          0 :                 range.first++;
    3571 [ #  # ][ #  # ]:          0 :                 if (_it->second == pindex) {
    3572                 :          0 :                     g_blockman.m_blocks_unlinked.erase(_it);
    3573                 :            :                 }
    3574                 :            :             }
    3575                 :            :         }
    3576                 :            :     }
    3577                 :            : 
    3578 [ +  - ][ +  - ]:          6 :     vinfoBlockFile[fileNumber].SetNull();
    3579 [ +  - ][ +  - ]:          3 :     setDirtyFileInfo.insert(fileNumber);
    3580                 :          3 : }
    3581                 :            : 
    3582                 :            : 
    3583                 :          3 : void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
    3584                 :            : {
    3585 [ +  + ][ +  + ]:         15 :     for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
                 [ +  + ]
    3586                 :          6 :         FlatFilePos pos(*it, 0);
    3587 [ +  - ][ +  - ]:          6 :         fs::remove(BlockFileSeq().FileName(pos));
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
    3588 [ +  - ][ +  - ]:          6 :         fs::remove(UndoFileSeq().FileName(pos));
         [ +  - ][ +  - ]
         [ #  # ][ #  # ]
    3589                 :          6 :         LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
    3590                 :            :     }
    3591                 :          3 : }
    3592                 :            : 
    3593                 :            : /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
    3594                 :          0 : static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
    3595                 :            : {
    3596 [ #  # ][ #  # ]:          0 :     assert(fPruneMode && nManualPruneHeight > 0);
    3597                 :            : 
    3598 [ #  # ][ #  # ]:          0 :     LOCK2(cs_main, cs_LastBlockFile);
         [ #  # ][ #  # ]
                 [ #  # ]
    3599 [ #  # ][ #  # ]:          0 :     if (::ChainActive().Tip() == nullptr)
    3600 [ #  # ][ #  # ]:          0 :         return;
    3601                 :            : 
    3602                 :            :     // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
    3603 [ #  # ][ #  # ]:          0 :     unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, ::ChainActive().Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
    3604                 :          0 :     int count=0;
    3605         [ #  # ]:          0 :     for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
    3606 [ #  # ][ #  # ]:          0 :         if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
                 [ #  # ]
    3607                 :            :             continue;
    3608         [ #  # ]:          0 :         PruneOneBlockFile(fileNumber);
    3609         [ #  # ]:          0 :         setFilesToPrune.insert(fileNumber);
    3610                 :          0 :         count++;
    3611                 :            :     }
    3612         [ #  # ]:          0 :     LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
    3613                 :            : }
    3614                 :            : 
    3615                 :            : /* This function is called from the RPC code for pruneblockchain */
    3616                 :          0 : void PruneBlockFilesManual(int nManualPruneHeight)
    3617                 :            : {
    3618         [ #  # ]:          0 :     CValidationState state;
    3619         [ #  # ]:          0 :     const CChainParams& chainparams = Params();
    3620 [ #  # ][ #  # ]:          0 :     if (!::ChainstateActive().FlushStateToDisk(
    3621                 :            :             chainparams, state, FlushStateMode::NONE, nManualPruneHeight)) {
    3622 [ #  # ][ #  # ]:          0 :         LogPrintf("%s: failed to flush state (%s)\n", __func__, FormatStateMessage(state));
         [ #  # ][ #  # ]
    3623                 :            :     }
    3624                 :          0 : }
    3625                 :            : 
    3626                 :            : /**
    3627                 :            :  * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
    3628                 :            :  * The user sets the target (in MB) on the command line or in config file.  This will be run on startup and whenever new
    3629                 :            :  * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
    3630                 :            :  * (which in this case means the blockchain must be re-downloaded.)
    3631                 :            :  *
    3632                 :            :  * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
    3633                 :            :  * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
    3634                 :            :  * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 1000 on regtest).
    3635                 :            :  * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
    3636                 :            :  * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
    3637                 :            :  * A db flag records the fact that at least some block files have been pruned.
    3638                 :            :  *
    3639                 :            :  * @param[out]   setFilesToPrune   The set of file indices that can be unlinked will be returned
    3640                 :            :  */
    3641                 :          6 : static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
    3642                 :            : {
    3643 [ +  - ][ #  # ]:          6 :     LOCK2(cs_main, cs_LastBlockFile);
         [ #  # ][ #  # ]
                 [ #  # ]
    3644 [ +  + ][ +  - ]:          6 :     if (::ChainActive().Tip() == nullptr || nPruneTarget == 0) {
                 [ +  - ]
    3645 [ +  - ][ +  - ]:         12 :         return;
    3646                 :            :     }
    3647 [ -  + ][ -  + ]:         10 :     if ((uint64_t)::ChainActive().Tip()->nHeight <= nPruneAfterHeight) {
    3648                 :            :         return;
    3649                 :            :     }
    3650                 :            : 
    3651         [ #  # ]:          0 :     unsigned int nLastBlockWeCanPrune = ::ChainActive().Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
    3652         [ #  # ]:          0 :     uint64_t nCurrentUsage = CalculateCurrentUsage();
    3653                 :            :     // We don't check to prune until after we've allocated new space for files
    3654                 :            :     // So we should leave a buffer under our target to account for another allocation
    3655                 :            :     // before the next pruning.
    3656                 :          0 :     uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
    3657                 :          0 :     uint64_t nBytesToPrune;
    3658                 :          0 :     int count=0;
    3659                 :            : 
    3660         [ #  # ]:          0 :     if (nCurrentUsage + nBuffer >= nPruneTarget) {
    3661                 :            :         // On a prune event, the chainstate DB is flushed.
    3662                 :            :         // To avoid excessive prune events negating the benefit of high dbcache
    3663                 :            :         // values, we should not prune too rapidly.
    3664                 :            :         // So when pruning in IBD, increase the buffer a bit to avoid a re-prune too soon.
    3665 [ #  # ][ #  # ]:          0 :         if (::ChainstateActive().IsInitialBlockDownload()) {
    3666                 :            :             // Since this is only relevant during IBD, we use a fixed 10%
    3667                 :          0 :             nBuffer += nPruneTarget / 10;
    3668                 :            :         }
    3669                 :            : 
    3670         [ #  # ]:          0 :         for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
    3671         [ #  # ]:          0 :             nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
    3672                 :            : 
    3673         [ #  # ]:          0 :             if (vinfoBlockFile[fileNumber].nSize == 0)
    3674                 :            :                 continue;
    3675                 :            : 
    3676         [ #  # ]:          0 :             if (nCurrentUsage + nBuffer < nPruneTarget)  // are we below our target?
    3677                 :            :                 break;
    3678                 :            : 
    3679                 :            :             // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
    3680         [ #  # ]:          0 :             if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
    3681                 :            :                 continue;
    3682                 :            : 
    3683         [ #  # ]:          0 :             PruneOneBlockFile(fileNumber);
    3684                 :            :             // Queue up the files for removal
    3685         [ #  # ]:          0 :             setFilesToPrune.insert(fileNumber);
    3686                 :          0 :             nCurrentUsage -= nBytesToPrune;
    3687                 :          0 :             count++;
    3688                 :            :         }
    3689                 :            :     }
    3690                 :            : 
    3691                 :          0 :     LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
    3692                 :          0 :            nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
    3693         [ #  # ]:          0 :            ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
    3694                 :            :            nLastBlockWeCanPrune, count);
    3695                 :            : }
    3696                 :            : 
    3697                 :     137794 : static FlatFileSeq BlockFileSeq()
    3698                 :            : {
    3699 [ +  - ][ -  + ]:     137794 :     return FlatFileSeq(GetBlocksDir(), "blk", BLOCKFILE_CHUNK_SIZE);
                 [ #  # ]
    3700                 :            : }
    3701                 :            : 
    3702                 :      70009 : static FlatFileSeq UndoFileSeq()
    3703                 :            : {
    3704 [ +  - ][ -  + ]:      70009 :     return FlatFileSeq(GetBlocksDir(), "rev", UNDOFILE_CHUNK_SIZE);
                 [ #  # ]
    3705                 :            : }
    3706                 :            : 
    3707                 :     105417 : FILE* OpenBlockFile(const FlatFilePos &pos, bool fReadOnly) {
    3708 [ +  - ][ +  - ]:     210834 :     return BlockFileSeq().Open(pos, fReadOnly);
                 [ #  # ]
    3709                 :            : }
    3710                 :            : 
    3711                 :            : /** Open an undo file (rev?????.dat) */
    3712                 :      37585 : static FILE* OpenUndoFile(const FlatFilePos &pos, bool fReadOnly) {
    3713 [ +  - ][ +  - ]:      75170 :     return UndoFileSeq().Open(pos, fReadOnly);
                 [ #  # ]
    3714                 :            : }
    3715                 :            : 
    3716                 :         10 : fs::path GetBlockPosFilename(const FlatFilePos &pos)
    3717                 :            : {
    3718 [ +  - ][ +  - ]:         20 :     return BlockFileSeq().FileName(pos);
                 [ #  # ]
    3719                 :            : }
    3720                 :            : 
    3721                 :      72554 : CBlockIndex * BlockManager::InsertBlockIndex(const uint256& hash)
    3722                 :            : {
    3723                 :      72554 :     AssertLockHeld(cs_main);
    3724                 :            : 
    3725         [ +  + ]:     145108 :     if (hash.IsNull())
    3726                 :            :         return nullptr;
    3727                 :            : 
    3728                 :            :     // Return existing
    3729                 :      72334 :     BlockMap::iterator mi = m_block_index.find(hash);
    3730   [ +  +  +  +  :     217002 :     if (mi != m_block_index.end())
                   +  + ]
    3731                 :      72114 :         return (*mi).second;
    3732                 :            : 
    3733                 :            :     // Create new
    3734                 :      36277 :     CBlockIndex* pindexNew = new CBlockIndex();
    3735                 :      72554 :     mi = m_block_index.insert(std::make_pair(hash, pindexNew)).first;
    3736                 :      36277 :     pindexNew->phashBlock = &((*mi).first);
    3737                 :            : 
    3738                 :      36277 :     return pindexNew;
    3739                 :            : }
    3740                 :            : 
    3741                 :        367 : bool BlockManager::LoadBlockIndex(
    3742                 :            :     const Consensus::Params& consensus_params,
    3743                 :            :     CBlockTreeDB& blocktree,
    3744                 :            :     std::set<CBlockIndex*, CBlockIndexWorkComparator>& block_index_candidates)
    3745                 :            : {
    3746 [ +  - ][ +  - ]:      73288 :     if (!blocktree.LoadBlockIndexGuts(consensus_params, [this](const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return this->InsertBlockIndex(hash); }))
         [ +  - ][ #  # ]
    3747                 :            :         return false;
    3748                 :            : 
    3749                 :            :     // Calculate nChainWork
    3750 [ +  - ][ +  + ]:        734 :     std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
                 [ #  # ]
    3751 [ +  - ][ +  - ]:        734 :     vSortedByHeight.reserve(m_block_index.size());
    3752 [ +  + ][ +  + ]:      73655 :     for (const std::pair<const uint256, CBlockIndex*>& item : m_block_index)
                 [ +  - ]
    3753                 :            :     {
    3754                 :      36277 :         CBlockIndex* pindex = item.second;
    3755 [ +  - ][ +  - ]:      72554 :         vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
    3756                 :            :     }
    3757                 :       1101 :     sort(vSortedByHeight.begin(), vSortedByHeight.end());
    3758 [ +  + ][ +  + ]:      37378 :     for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
    3759                 :            :     {
    3760 [ +  - ][ +  - ]:      36277 :         if (ShutdownRequested()) return false;
    3761                 :      36277 :         CBlockIndex* pindex = item.second;
    3762 [ +  - ][ +  + ]:     145108 :         pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
    3763 [ +  + ][ +  + ]:      43701 :         pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
    3764                 :            :         // We can link the chain of blocks for which we've received transactions at some point.
    3765                 :            :         // Pruned nodes may have deleted the block.
    3766         [ +  - ]:      36277 :         if (pindex->nTx > 0) {
    3767         [ +  + ]:      36277 :             if (pindex->pprev) {
    3768 [ +  - ][ +  - ]:      72114 :                 if (pindex->pprev->HaveTxsDownloaded()) {
    3769                 :      36057 :                     pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
    3770                 :            :                 } else {
    3771                 :          0 :                     pindex->nChainTx = 0;
    3772 [ #  # ][ #  # ]:          0 :                     m_blocks_unlinked.insert(std::make_pair(pindex->pprev, pindex));
    3773                 :            :                 }
    3774                 :            :             } else {
    3775                 :        220 :                 pindex->nChainTx = pindex->nTx;
    3776                 :            :             }
    3777                 :            :         }
    3778 [ +  + ][ +  + ]:      36277 :         if (!(pindex->nStatus & BLOCK_FAILED_MASK) && pindex->pprev && (pindex->pprev->nStatus & BLOCK_FAILED_MASK)) {
                 [ -  + ]
    3779                 :          0 :             pindex->nStatus |= BLOCK_FAILED_CHILD;
    3780         [ #  # ]:          0 :             setDirtyBlockIndex.insert(pindex);
    3781                 :            :         }
    3782 [ +  + ][ +  - ]:      36277 :         if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->HaveTxsDownloaded() || pindex->pprev == nullptr)) {
         [ -  + ][ -  + ]
                 [ #  # ]
    3783         [ +  - ]:      36274 :             block_index_candidates.insert(pindex);
    3784                 :            :         }
    3785 [ +  + ][ -  + ]:      36277 :         if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
         [ #  # ][ #  # ]
    3786                 :          3 :             pindexBestInvalid = pindex;
    3787         [ +  + ]:      36277 :         if (pindex->pprev)
    3788         [ +  - ]:      36057 :             pindex->BuildSkip();
    3789 [ +  + ][ +  - ]:      36277 :         if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
         [ +  + ][ +  - ]
                 [ +  + ]
    3790                 :      36271 :             pindexBestHeader = pindex;
    3791                 :            :     }
    3792                 :            : 
    3793                 :            :     return true;
    3794                 :            : }
    3795                 :            : 
    3796                 :        440 : void BlockManager::Unload() {
    3797                 :        440 :     m_failed_blocks.clear();
    3798                 :        440 :     m_blocks_unlinked.clear();
    3799                 :            : 
    3800 [ +  + ][ +  + ]:       6156 :     for (const BlockMap::value_type& entry : m_block_index) {
    3801                 :       2418 :         delete entry.second;
    3802                 :            :     }
    3803                 :            : 
    3804                 :        440 :     m_block_index.clear();
    3805                 :        440 : }
    3806                 :            : 
    3807                 :        367 : bool static LoadBlockIndexDB(const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
    3808                 :            : {
    3809         [ +  - ]:        367 :     if (!g_blockman.LoadBlockIndex(
    3810                 :        734 :             chainparams.GetConsensus(), *pblocktree, ::ChainstateActive().setBlockIndexCandidates))
    3811                 :            :         return false;
    3812                 :            : 
    3813                 :            :     // Load block file info
    3814                 :        734 :     pblocktree->ReadLastBlockFile(nLastBlockFile);
    3815                 :        367 :     vinfoBlockFile.resize(nLastBlockFile + 1);
    3816                 :        367 :     LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
    3817         [ +  + ]:        734 :     for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
    3818                 :       1101 :         pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
    3819                 :            :     }
    3820 [ +  - ][ +  - ]:        734 :     LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
                 [ #  # ]
    3821                 :        367 :     for (int nFile = nLastBlockFile + 1; true; nFile++) {
    3822                 :        367 :         CBlockFileInfo info;
    3823         [ -  + ]:        734 :         if (pblocktree->ReadBlockFileInfo(nFile, info)) {
    3824                 :          0 :             vinfoBlockFile.push_back(info);
    3825                 :            :         } else {
    3826                 :            :             break;
    3827                 :            :         }
    3828                 :          0 :     }
    3829                 :            : 
    3830                 :            :     // Check presence of blk files
    3831                 :        367 :     LogPrintf("Checking all blk files are present...\n");
    3832                 :        734 :     std::set<int> setBlkDataFiles;
    3833 [ +  + ][ +  + ]:      37378 :     for (const std::pair<const uint256, CBlockIndex*>& item : g_blockman.m_block_index)
                 [ +  - ]
    3834                 :            :     {
    3835                 :      36277 :         CBlockIndex* pindex = item.second;
    3836         [ +  - ]:      36277 :         if (pindex->nStatus & BLOCK_HAVE_DATA) {
    3837         [ +  - ]:      36277 :             setBlkDataFiles.insert(pindex->nFile);
    3838                 :            :         }
    3839                 :            :     }
    3840 [ +  + ][ +  + ]:        954 :     for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
                 [ +  + ]
    3841                 :            :     {
    3842 [ +  - ][ +  - ]:        440 :         FlatFilePos pos(*it, 0);
    3843 [ +  - ][ +  - ]:        440 :         if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
         [ +  - ][ +  - ]
                 [ +  - ]
    3844                 :            :             return false;
    3845                 :            :         }
    3846                 :            :     }
    3847                 :            : 
    3848                 :            :     // Check whether we have ever pruned block & undo files
    3849 [ +  - ][ +  - ]:       1468 :     pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
         [ +  - ][ +  - ]
         [ +  - ][ -  + ]
                 [ #  # ]
    3850         [ -  + ]:        367 :     if (fHavePruned)
    3851         [ #  # ]:          0 :         LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
    3852                 :            : 
    3853                 :            :     // Check whether we need to continue reindexing
    3854                 :        367 :     bool fReindexing = false;
    3855 [ +  - ][ +  - ]:        734 :     pblocktree->ReadReindexing(fReindexing);
    3856         [ -  + ]:        367 :     if(fReindexing) fReindex = true;
    3857                 :            : 
    3858                 :            :     return true;
    3859                 :            : }
    3860                 :            : 
    3861                 :        218 : bool LoadChainTip(const CChainParams& chainparams)
    3862                 :            : {
    3863                 :        218 :     AssertLockHeld(cs_main);
    3864         [ -  + ]:        654 :     assert(!pcoinsTip->GetBestBlock().IsNull()); // Never called when the coins view is empty
    3865                 :            : 
    3866 [ -  + ][ #  # ]:        218 :     if (::ChainActive().Tip() && ::ChainActive().Tip()->GetBlockHash() == pcoinsTip->GetBestBlock()) return true;
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
    3867                 :            : 
    3868                 :            :     // Load pointer to end of best chain
    3869                 :        436 :     CBlockIndex* pindex = LookupBlockIndex(pcoinsTip->GetBestBlock());
    3870         [ +  - ]:        218 :     if (!pindex) {
    3871                 :            :         return false;
    3872                 :            :     }
    3873                 :        218 :     ::ChainActive().SetTip(pindex);
    3874                 :            : 
    3875                 :        218 :     ::ChainstateActive().PruneBlockIndexCandidates();
    3876                 :            : 
    3877         [ +  - ]:        218 :     LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
    3878 [ +  - ][ +  - ]:       1090 :         ::ChainActive().Tip()->GetBlockHash().ToString(), ::ChainActive().Height(),
         [ +  - ][ #  # ]
           [ +  -  +  - ]
    3879 [ +  - ][ #  # ]:        654 :         FormatISO8601DateTime(::ChainActive().Tip()->GetBlockTime()),
    3880 [ +  - ][ +  - ]:        654 :         GuessVerificationProgress(chainparams.TxData(), ::ChainActive().Tip()));
    3881                 :        218 :     return true;
    3882                 :            : }
    3883                 :            : 
    3884                 :        219 : CVerifyDB::CVerifyDB()
    3885                 :            : {
    3886         [ +  - ]:        219 :     uiInterface.ShowProgress(_("Verifying blocks...").translated, 0, false);
    3887                 :        219 : }
    3888                 :            : 
    3889                 :        219 : CVerifyDB::~CVerifyDB()
    3890                 :            : {
    3891         [ -  + ]:        438 :     uiInterface.ShowProgress("", 100, false);
    3892                 :        219 : }
    3893                 :            : 
    3894                 :        219 : bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
    3895                 :            : {
    3896 [ +  - ][ #  # ]:        657 :     LOCK(cs_main);
    3897 [ +  - ][ +  + ]:        219 :     if (::ChainActive().Tip() == nullptr || ::ChainActive().Tip()->pprev == nullptr)
         [ +  + ][ +  - ]
    3898                 :            :         return true;
    3899                 :            : 
    3900                 :            :     // Verify blocks in the best chain
    3901 [ +  + ][ +  + ]:        190 :     if (nCheckDepth <= 0 || nCheckDepth > ::ChainActive().Height())
                 [ +  + ]
    3902                 :         22 :         nCheckDepth = ::ChainActive().Height();
    3903 [ +  + ][ +  - ]:        379 :     nCheckLevel = std::max(0, std::min(4, nCheckLevel));
    3904         [ +  - ]:        190 :     LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
    3905         [ +  - ]:        190 :     CCoinsViewCache coins(coinsview);
    3906                 :        190 :     CBlockIndex* pindex;
    3907                 :        190 :     CBlockIndex* pindexFailure = nullptr;
    3908                 :        190 :     int nGoodTransactions = 0;
    3909         [ +  - ]:        380 :     CValidationState state;
    3910                 :        190 :     int reportDone = 0;
    3911         [ +  - ]:        190 :     LogPrintf("[0%%]..."); /* Continued */
    3912 [ +  - ][ +  - ]:       1670 :     for (pindex = ::ChainActive().Tip(); pindex && pindex->pprev; pindex = pindex->pprev) {
                 [ +  + ]
    3913         [ +  - ]:       1470 :         boost::this_thread::interruption_point();
    3914 [ +  + ][ +  + ]:       5494 :         const int percentageDone = std::max(1, std::min(99, (int)(((double)(::ChainActive().Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
         [ +  + ][ +  + ]
    3915         [ +  + ]:       1470 :         if (reportDone < percentageDone/10) {
    3916                 :            :             // report every 10% step
    3917         [ +  - ]:       1078 :             LogPrintf("[%d%%]...", percentageDone); /* Continued */
    3918                 :       1078 :             reportDone = percentageDone/10;
    3919                 :            :         }
    3920 [ +  - ][ +  - ]:       1470 :         uiInterface.ShowProgress(_("Verifying blocks...").translated, percentageDone, false);
    3921   [ +  +  +  + ]:       2940 :         if (pindex->nHeight <= ::ChainActive().Height()-nCheckDepth)
    3922                 :            :             break;
    3923 [ +  + ][ -  + ]:       1291 :         if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
    3924                 :            :             // If pruning, only go back as far as we have data.
    3925         [ #  # ]:          0 :             LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
    3926                 :            :             break;
    3927                 :            :         }
    3928                 :       2581 :         CBlock block;
    3929                 :            :         // check level 0: read from disk
    3930         [ -  + ]:       2582 :         if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
           [ +  -  +  - ]
    3931 [ #  # ][ #  # ]:          0 :             return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
         [ #  # ][ #  # ]
                 [ #  # ]
    3932                 :            :         // check level 1: verify block validity
    3933 [ +  - ][ +  - ]:       1291 :         if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
         [ +  - ][ +  - ]
    3934                 :          0 :             return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
    3935 [ #  # ][ #  # ]:          0 :                          pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
    3936                 :            :         // check level 2: verify undo validity
    3937         [ +  - ]:       1291 :         if (nCheckLevel >= 2 && pindex) {
    3938         [ +  - ]:       2581 :             CBlockUndo undo;
    3939 [ +  - ][ +  - ]:       3873 :             if (!pindex->GetUndoPos().IsNull()) {
                 [ +  - ]
    3940 [ +  - ][ +  + ]:       1291 :                 if (!UndoReadFromDisk(undo, pindex)) {
    3941 [ +  - ][ +  - ]:          3 :                     return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
         [ +  - ][ +  - ]
                 [ #  # ]
    3942                 :            :                 }
    3943                 :            :             }
    3944                 :            :         }
    3945                 :            :         // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
    3946 [ +  - ][ +  - ]:       1290 :         if (nCheckLevel >= 3 && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
         [ +  - ][ +  - ]
                 [ +  - ]
    3947 [ +  - ][ +  - ]:       2580 :             assert(coins.GetBestBlock() == pindex->GetBlockHash());
         [ -  + ][ -  + ]
    3948         [ +  - ]:       1290 :             DisconnectResult res = ::ChainstateActive().DisconnectBlock(block, pindex, coins);
    3949         [ -  + ]:       1290 :             if (res == DISCONNECT_FAILED) {
    3950 [ #  # ][ #  # ]:          0 :                 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
         [ #  # ][ #  # ]
                 [ #  # ]
    3951                 :            :             }
    3952         [ -  + ]:       1290 :             if (res == DISCONNECT_UNCLEAN) {
    3953                 :          0 :                 nGoodTransactions = 0;
    3954                 :          0 :                 pindexFailure = pindex;
    3955                 :            :             } else {
    3956                 :       2580 :                 nGoodTransactions += block.vtx.size();
    3957                 :            :             }
    3958                 :            :         }
    3959 [ +  - ][ +  - ]:       1290 :         if (ShutdownRequested())
    3960                 :            :             return true;
    3961                 :            :     }
    3962         [ -  + ]:        189 :     if (pindexFailure)
    3963 [ #  # ][ #  # ]:          0 :         return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", ::ChainActive().Height() - pindexFailure->nHeight + 1, nGoodTransactions);
    3964                 :            : 
    3965                 :            :     // store block count as we move pindex at check level >= 4
    3966         [ +  + ]:        189 :     int block_count = ::ChainActive().Height() - pindex->nHeight;
    3967                 :            : 
    3968                 :            :     // check level 4: try reconnecting blocks
    3969         [ +  + ]:        189 :     if (nCheckLevel >= 4) {
    3970 [ +  - ][ +  + ]:        416 :         while (pindex != ::ChainActive().Tip()) {
    3971         [ +  - ]:        207 :             boost::this_thread::interruption_point();
    3972 [ +  + ][ +  + ]:        613 :             const int percentageDone = std::max(1, std::min(99, 100 - (int)(((double)(::ChainActive().Height() - pindex->nHeight)) / (double)nCheckDepth * 50)));
                 [ +  - ]
    3973         [ +  + ]:        207 :             if (reportDone < percentageDone/10) {
    3974                 :            :                 // report every 10% step
    3975         [ +  - ]:          5 :                 LogPrintf("[%d%%]...", percentageDone); /* Continued */
    3976                 :          5 :                 reportDone = percentageDone/10;
    3977                 :            :             }
    3978 [ +  - ][ +  - ]:        207 :             uiInterface.ShowProgress(_("Verifying blocks...").translated, percentageDone, false);
    3979                 :        207 :             pindex = ::ChainActive().Next(pindex);
    3980                 :        414 :             CBlock block;
    3981         [ -  + ]:        414 :             if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
           [ +  -  +  - ]
    3982 [ #  # ][ #  # ]:          0 :                 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
         [ #  # ][ #  # ]
                 [ #  # ]
    3983 [ +  - ][ -  + ]:        207 :             if (!::ChainstateActive().ConnectBlock(block, state, pindex, coins, chainparams))
    3984 [ #  # ][ #  # ]:          0 :                 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s (%s)", pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
    3985                 :            :         }
    3986                 :            :     }
    3987                 :            : 
    3988         [ +  - ]:        189 :     LogPrintf("[DONE].\n");
    3989         [ +  - ]:        189 :     LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", block_count, nGoodTransactions);
    3990                 :            : 
    3991                 :            :     return true;
    3992                 :            : }
    3993                 :            : 
    3994                 :            : /** Apply the effects of a block on the utxo cache, ignoring that it may already have been applied. */
    3995                 :          0 : bool CChainState::RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params)
    3996                 :            : {
    3997                 :            :     // TODO: merge with ConnectBlock
    3998                 :          0 :     CBlock block;
    3999         [ #  # ]:          0 :     if (!ReadBlockFromDisk(block, pindex, params.GetConsensus())) {
           [ #  #  #  # ]
    4000 [ #  # ][ #  # ]:          0 :         return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
         [ #  # ][ #  # ]
                 [ #  # ]
    4001                 :            :     }
    4002                 :            : 
    4003 [ #  # ][ #  # ]:          0 :     for (const CTransactionRef& tx : block.vtx) {
    4004 [ #  # ][ #  # ]:          0 :         if (!tx->IsCoinBase()) {
    4005 [ #  # ][ #  # ]:          0 :             for (const CTxIn &txin : tx->vin) {
    4006         [ #  # ]:          0 :                 inputs.SpendCoin(txin.prevout);
    4007                 :            :             }
    4008                 :            :         }
    4009                 :            :         // Pass check = true as every addition may be an overwrite.
    4010 [ #  # ][ #  # ]:          0 :         AddCoins(inputs, *tx, pindex->nHeight, true);
    4011                 :            :     }
    4012                 :            :     return true;
    4013                 :            : }
    4014                 :            : 
    4015                 :        372 : bool CChainState::ReplayBlocks(const CChainParams& params, CCoinsView* view)
    4016                 :            : {
    4017         [ #  # ]:        744 :     LOCK(cs_main);
    4018                 :            : 
    4019   [ +  -  +  - ]:        744 :     CCoinsViewCache cache(view);
    4020                 :            : 
    4021 [ +  - ][ -  + ]:        744 :     std::vector<uint256> hashHeads = view->GetHeadBlocks();
                 [ #  # ]
    4022 [ -  + ][ -  + ]:        744 :     if (hashHeads.empty()) return true; // We're already in a consistent state.
    4023 [ #  # ][ #  # ]:          0 :     if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
                 [ #  # ]
    4024                 :            : 
    4025 [ #  # ][ #  # ]:          0 :     uiInterface.ShowProgress(_("Replaying blocks...").translated, 0, false);
    4026         [ #  # ]:          0 :     LogPrintf("Replaying blocks\n");
    4027                 :            : 
    4028                 :          0 :     const CBlockIndex* pindexOld = nullptr;  // Old tip during the interrupted flush.
    4029                 :          0 :     const CBlockIndex* pindexNew;            // New tip during the interrupted flush.
    4030                 :          0 :     const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
    4031                 :            : 
    4032         [ #  # ]:          0 :     if (m_blockman.m_block_index.count(hashHeads[0]) == 0) {
    4033         [ #  # ]:          0 :         return error("ReplayBlocks(): reorganization to unknown block requested");
    4034                 :            :     }
    4035         [ #  # ]:          0 :     pindexNew = m_blockman.m_block_index[hashHeads[0]];
    4036                 :            : 
    4037         [ #  # ]:          0 :     if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
    4038         [ #  # ]:          0 :         if (m_blockman.m_block_index.count(hashHeads[1]) == 0) {
    4039         [ #  # ]:          0 :             return error("ReplayBlocks(): reorganization from unknown block requested");
    4040                 :            :         }
    4041         [ #  # ]:          0 :         pindexOld = m_blockman.m_block_index[hashHeads[1]];
    4042         [ #  # ]:          0 :         pindexFork = LastCommonAncestor(pindexOld, pindexNew);
    4043         [ #  # ]:          0 :         assert(pindexFork != nullptr);
    4044                 :            :     }
    4045                 :            : 
    4046                 :            :     // Rollback along the old branch.
    4047         [ #  # ]:          0 :     while (pindexOld != pindexFork) {
    4048         [ #  # ]:          0 :         if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
    4049                 :          0 :             CBlock block;
    4050         [ #  # ]:          0 :             if (!ReadBlockFromDisk(block, pindexOld, params.GetConsensus())) {
           [ #  #  #  # ]
    4051 [ #  # ][ #  # ]:          0 :                 return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
         [ #  # ][ #  # ]
                 [ #  # ]
    4052                 :            :             }
    4053 [ #  # ][ #  # ]:          0 :             LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
         [ #  # ][ #  # ]
                 [