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