LCOV - code coverage report
Current view: top level - src - validation.cpp (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 2294 2448 93.7 %
Date: 2020-12-03 10:38:13 Functions: 158 159 99.4 %
Branches: 2615 4406 59.4 %

           Branch data     Line data    Source code
       1                 :            : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2                 :            : // Copyright (c) 2009-2020 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 <logging.h>
      22                 :            : #include <logging/timer.h>
      23                 :            : #include <node/ui_interface.h>
      24                 :            : #include <optional.h>
      25                 :            : #include <policy/fees.h>
      26                 :            : #include <policy/policy.h>
      27                 :            : #include <policy/settings.h>
      28                 :            : #include <pow.h>
      29                 :            : #include <primitives/block.h>
      30                 :            : #include <primitives/transaction.h>
      31                 :            : #include <random.h>
      32                 :            : #include <reverse_iterator.h>
      33                 :            : #include <script/script.h>
      34                 :            : #include <script/sigcache.h>
      35                 :            : #include <shutdown.h>
      36                 :            : #include <signet.h>
      37                 :            : #include <timedata.h>
      38                 :            : #include <tinyformat.h>
      39                 :            : #include <txdb.h>
      40                 :            : #include <txmempool.h>
      41                 :            : #include <uint256.h>
      42                 :            : #include <undo.h>
      43                 :            : #include <util/check.h> // For NDEBUG compile time check
      44                 :            : #include <util/moneystr.h>
      45                 :            : #include <util/rbf.h>
      46                 :            : #include <util/strencodings.h>
      47                 :            : #include <util/system.h>
      48                 :            : #include <util/translation.h>
      49                 :            : #include <validationinterface.h>
      50                 :            : #include <warnings.h>
      51                 :            : 
      52                 :            : #include <string>
      53                 :            : 
      54                 :            : #include <boost/algorithm/string/replace.hpp>
      55                 :            : 
      56                 :            : #define MICRO 0.000001
      57                 :            : #define MILLI 0.001
      58                 :            : 
      59                 :            : /**
      60                 :            :  * An extra transaction can be added to a package, as long as it only has one
      61                 :            :  * ancestor and is no larger than this. Not really any reason to make this
      62                 :            :  * configurable as it doesn't materially change DoS parameters.
      63                 :            :  */
      64                 :            : static const unsigned int EXTRA_DESCENDANT_TX_SIZE_LIMIT = 10000;
      65                 :            : /** Maximum kilobytes for transactions to store for processing during reorg */
      66                 :            : static const unsigned int MAX_DISCONNECTED_TX_POOL_SIZE = 20000;
      67                 :            : /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
      68                 :            : static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
      69                 :            : /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
      70                 :            : static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
      71                 :            : /** Time to wait between writing blocks/block index to disk. */
      72                 :            : static constexpr std::chrono::hours DATABASE_WRITE_INTERVAL{1};
      73                 :            : /** Time to wait between flushing chainstate to disk. */
      74                 :            : static constexpr std::chrono::hours DATABASE_FLUSH_INTERVAL{24};
      75                 :            : /** Maximum age of our tip for us to be considered current for fee estimation */
      76                 :            : static constexpr std::chrono::hours MAX_FEE_ESTIMATION_TIP_AGE{3};
      77                 :            : const std::vector<std::string> CHECKLEVEL_DOC {
      78                 :            :     "level 0 reads the blocks from disk",
      79                 :            :     "level 1 verifies block validity",
      80                 :            :     "level 2 verifies undo data",
      81                 :            :     "level 3 checks disconnection of tip blocks",
      82                 :            :     "level 4 tries to reconnect the blocks",
      83                 :            :     "each level includes the checks of the previous levels",
      84                 :            : };
      85                 :            : 
      86                 :  475492096 : bool CBlockIndexWorkComparator::operator()(const CBlockIndex *pa, const CBlockIndex *pb) const {
      87                 :            :     // First sort by most total work, ...
      88         [ +  + ]:  475492096 :     if (pa->nChainWork > pb->nChainWork) return false;
      89         [ +  + ]:  311828896 :     if (pa->nChainWork < pb->nChainWork) return true;
      90                 :            : 
      91                 :            :     // ... then by earliest time received, ...
      92         [ +  + ]:    1680105 :     if (pa->nSequenceId < pb->nSequenceId) return false;
      93         [ +  + ]:    1639668 :     if (pa->nSequenceId > pb->nSequenceId) return true;
      94                 :            : 
      95                 :            :     // Use pointer address as tie breaker (should only happen with blocks
      96                 :            :     // loaded from disk, as those all have id 0).
      97         [ +  + ]:    1616218 :     if (pa < pb) return false;
      98         [ +  + ]:    1615893 :     if (pa > pb) return true;
      99                 :            : 
     100                 :            :     // Identical blocks.
     101                 :            :     return false;
     102                 :            : }
     103                 :            : 
     104                 :            : ChainstateManager g_chainman;
     105                 :            : 
     106                 :   13855302 : CChainState& ChainstateActive()
     107                 :            : {
     108                 :   13855302 :     LOCK(::cs_main);
     109         [ -  + ]:   13855302 :     assert(g_chainman.m_active_chainstate);
     110         [ +  - ]:   13855302 :     return *g_chainman.m_active_chainstate;
     111                 :            : }
     112                 :            : 
     113                 :   10066419 : CChain& ChainActive()
     114                 :            : {
     115                 :   10066419 :     LOCK(::cs_main);
     116   [ +  -  +  - ]:   20132838 :     return ::ChainstateActive().m_chain;
     117                 :            : }
     118                 :            : 
     119                 :            : /**
     120                 :            :  * Mutex to guard access to validation specific variables, such as reading
     121                 :            :  * or changing the chainstate.
     122                 :            :  *
     123                 :            :  * This may also need to be locked when updating the transaction pool, e.g. on
     124                 :            :  * AcceptToMemoryPool. See CTxMemPool::cs comment for details.
     125                 :            :  *
     126                 :            :  * The transaction pool has a separate lock to allow reading from it and the
     127                 :            :  * chainstate at the same time.
     128                 :            :  */
     129                 :            : RecursiveMutex cs_main;
     130                 :            : 
     131                 :            : CBlockIndex *pindexBestHeader = nullptr;
     132                 :            : Mutex g_best_block_mutex;
     133                 :            : std::condition_variable g_best_block_cv;
     134                 :            : uint256 g_best_block;
     135                 :            : bool g_parallel_script_checks{false};
     136                 :            : std::atomic_bool fImporting(false);
     137                 :            : std::atomic_bool fReindex(false);
     138                 :            : bool fHavePruned = false;
     139                 :            : bool fPruneMode = false;
     140                 :            : bool fRequireStandard = true;
     141                 :            : bool fCheckBlockIndex = false;
     142                 :            : bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
     143                 :            : uint64_t nPruneTarget = 0;
     144                 :            : int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
     145                 :            : 
     146                 :            : uint256 hashAssumeValid;
     147                 :            : arith_uint256 nMinimumChainWork;
     148                 :            : 
     149                 :            : CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
     150                 :            : 
     151                 :            : CBlockPolicyEstimator feeEstimator;
     152                 :            : 
     153                 :            : // Internal stuff
     154                 :            : namespace {
     155                 :            :     CBlockIndex* pindexBestInvalid = nullptr;
     156                 :            : 
     157                 :            :     RecursiveMutex cs_LastBlockFile;
     158                 :            :     std::vector<CBlockFileInfo> vinfoBlockFile;
     159                 :            :     int nLastBlockFile = 0;
     160                 :            :     /** Global flag to indicate we should check to see if there are
     161                 :            :      *  block/undo files that should be deleted.  Set on startup
     162                 :            :      *  or if we allocate more file space when we're in prune mode
     163                 :            :      */
     164                 :            :     bool fCheckForPruning = false;
     165                 :            : 
     166                 :            :     /** Dirty block index entries. */
     167                 :            :     std::set<CBlockIndex*> setDirtyBlockIndex;
     168                 :            : 
     169                 :            :     /** Dirty block file entries. */
     170                 :            :     std::set<int> setDirtyFileInfo;
     171                 :            : } // anon namespace
     172                 :            : 
     173                 :     918278 : CBlockIndex* LookupBlockIndex(const uint256& hash)
     174                 :            : {
     175                 :     918278 :     AssertLockHeld(cs_main);
     176         [ +  + ]:     918278 :     BlockMap::const_iterator it = g_chainman.BlockIndex().find(hash);
     177         [ +  + ]:     918278 :     return it == g_chainman.BlockIndex().end() ? nullptr : it->second;
     178                 :            : }
     179                 :            : 
     180                 :       1810 : CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
     181                 :            : {
     182                 :       1810 :     AssertLockHeld(cs_main);
     183                 :            : 
     184                 :            :     // Find the latest block common to locator and chain - we expect that
     185                 :            :     // locator.vHave is sorted descending by height.
     186         [ +  + ]:       7690 :     for (const uint256& hash : locator.vHave) {
     187                 :       7682 :         CBlockIndex* pindex = LookupBlockIndex(hash);
     188         [ +  + ]:       7682 :         if (pindex) {
     189         [ +  + ]:       7318 :             if (chain.Contains(pindex))
     190                 :            :                 return pindex;
     191   [ +  +  +  + ]:      11050 :             if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
     192                 :       1810 :                 return chain.Tip();
     193                 :            :             }
     194                 :            :         }
     195                 :            :     }
     196         [ -  + ]:          8 :     return chain.Genesis();
     197                 :            : }
     198                 :            : 
     199                 :            : std::unique_ptr<CBlockTreeDB> pblocktree;
     200                 :            : 
     201                 :            : bool CheckInputScripts(const CTransaction& tx, TxValidationState &state, const CCoinsViewCache &inputs, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks = nullptr);
     202                 :            : static FILE* OpenUndoFile(const FlatFilePos &pos, bool fReadOnly = false);
     203                 :            : static FlatFileSeq BlockFileSeq();
     204                 :            : static FlatFileSeq UndoFileSeq();
     205                 :            : 
     206                 :    5979590 : bool CheckFinalTx(const CTransaction &tx, int flags)
     207                 :            : {
     208         [ +  + ]:    5979590 :     AssertLockHeld(cs_main);
     209                 :            : 
     210                 :            :     // By convention a negative value for flags indicates that the
     211                 :            :     // current network-enforced consensus rules should be used. In
     212                 :            :     // a future soft-fork scenario that would mean checking which
     213                 :            :     // rules would be enforced for the next block and setting the
     214                 :            :     // appropriate flags. At the present time no soft-forks are
     215                 :            :     // scheduled, so no flags are set.
     216         [ +  + ]:    5979590 :     flags = std::max(flags, 0);
     217                 :            : 
     218                 :            :     // CheckFinalTx() uses ::ChainActive().Height()+1 to evaluate
     219                 :            :     // nLockTime because when IsFinalTx() is called within
     220                 :            :     // CBlock::AcceptBlock(), the height of the block *being*
     221                 :            :     // evaluated is what is used. Thus if we want to know if a
     222                 :            :     // transaction can be part of the *next* block, we need to call
     223                 :            :     // IsFinalTx() with one more than ::ChainActive().Height().
     224         [ +  + ]:    5979590 :     const int nBlockHeight = ::ChainActive().Height() + 1;
     225                 :            : 
     226                 :            :     // BIP113 requires that time-locked transactions have nLockTime set to
     227                 :            :     // less than the median time of the previous block they're contained in.
     228                 :            :     // When the next block is created its previous block will be the current
     229                 :            :     // chain tip, so we use that to calculate the median time passed to
     230                 :            :     // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
     231                 :    5979590 :     const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
     232   [ +  +  +  - ]:    6259902 :                              ? ::ChainActive().Tip()->GetMedianTimePast()
     233                 :    5699278 :                              : GetAdjustedTime();
     234                 :            : 
     235                 :    5979590 :     return IsFinalTx(tx, nBlockHeight, nBlockTime);
     236                 :            : }
     237                 :            : 
     238                 :      35687 : bool TestLockPointValidity(const LockPoints* lp)
     239                 :            : {
     240         [ -  + ]:      35687 :     AssertLockHeld(cs_main);
     241         [ -  + ]:      35687 :     assert(lp);
     242                 :            :     // If there are relative lock times then the maxInputBlock will be set
     243                 :            :     // If there are no relative lock times, the LockPoints don't depend on the chain
     244         [ +  - ]:      35687 :     if (lp->maxInputBlock) {
     245                 :            :         // Check whether ::ChainActive() is an extension of the block at which the LockPoints
     246                 :            :         // calculation was valid.  If not LockPoints are no longer valid
     247         [ +  + ]:      35687 :         if (!::ChainActive().Contains(lp->maxInputBlock)) {
     248                 :      11236 :             return false;
     249                 :            :         }
     250                 :            :     }
     251                 :            : 
     252                 :            :     // LockPoints still valid
     253                 :            :     return true;
     254                 :            : }
     255                 :            : 
     256                 :     276582 : bool CheckSequenceLocks(const CTxMemPool& pool, const CTransaction& tx, int flags, LockPoints* lp, bool useExistingLockPoints)
     257                 :            : {
     258                 :     276582 :     AssertLockHeld(cs_main);
     259                 :     276582 :     AssertLockHeld(pool.cs);
     260                 :            : 
     261         [ +  - ]:     276582 :     CBlockIndex* tip = ::ChainActive().Tip();
     262         [ -  + ]:     276582 :     assert(tip != nullptr);
     263                 :            : 
     264                 :     276582 :     CBlockIndex index;
     265                 :     276582 :     index.pprev = tip;
     266                 :            :     // CheckSequenceLocks() uses ::ChainActive().Height()+1 to evaluate
     267                 :            :     // height based locks because when SequenceLocks() is called within
     268                 :            :     // ConnectBlock(), the height of the block *being*
     269                 :            :     // evaluated is what is used.
     270                 :            :     // Thus if we want to know if a transaction can be part of the
     271                 :            :     // *next* block, we need to use one more than ::ChainActive().Height()
     272                 :     276582 :     index.nHeight = tip->nHeight + 1;
     273                 :            : 
     274                 :     276582 :     std::pair<int, int64_t> lockPair;
     275         [ +  + ]:     276582 :     if (useExistingLockPoints) {
     276         [ -  + ]:      24448 :         assert(lp);
     277                 :      24448 :         lockPair.first = lp->height;
     278                 :      24448 :         lockPair.second = lp->time;
     279                 :            :     }
     280                 :            :     else {
     281                 :            :         // CoinsTip() contains the UTXO set for ::ChainActive().Tip()
     282                 :     252134 :         CCoinsViewMemPool viewMemPool(&::ChainstateActive().CoinsTip(), pool);
     283         [ +  - ]:     504268 :         std::vector<int> prevheights;
     284         [ +  - ]:     252134 :         prevheights.resize(tx.vin.size());
     285         [ +  + ]:     758426 :         for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
     286                 :     506292 :             const CTxIn& txin = tx.vin[txinIndex];
     287                 :    1012584 :             Coin coin;
     288   [ +  -  -  + ]:     506292 :             if (!viewMemPool.GetCoin(txin.prevout, coin)) {
     289         [ #  # ]:          0 :                 return error("%s: Missing input", __func__);
     290                 :            :             }
     291         [ +  + ]:     506292 :             if (coin.nHeight == MEMPOOL_HEIGHT) {
     292                 :            :                 // Assume all mempool transaction confirm in the next block
     293                 :      21050 :                 prevheights[txinIndex] = tip->nHeight + 1;
     294                 :            :             } else {
     295                 :     485242 :                 prevheights[txinIndex] = coin.nHeight;
     296                 :            :             }
     297                 :            :         }
     298         [ +  - ]:     252134 :         lockPair = CalculateSequenceLocks(tx, flags, prevheights, index);
     299         [ +  + ]:     252134 :         if (lp) {
     300                 :     252126 :             lp->height = lockPair.first;
     301                 :     252126 :             lp->time = lockPair.second;
     302                 :            :             // Also store the hash of the block with the highest height of
     303                 :            :             // all the blocks which have sequence locked prevouts.
     304                 :            :             // This hash needs to still be on the chain
     305                 :            :             // for these LockPoint calculations to be valid
     306                 :            :             // Note: It is impossible to correctly calculate a maxInputBlock
     307                 :            :             // if any of the sequence locked inputs depend on unconfirmed txs,
     308                 :            :             // except in the special case where the relative lock time/height
     309                 :            :             // is 0, which is equivalent to no sequence lock. Since we assume
     310                 :            :             // input height of tip+1 for mempool txs and test the resulting
     311                 :            :             // lockPair from CalculateSequenceLocks against tip+1.  We know
     312                 :            :             // EvaluateSequenceLocks will fail if there was a non-zero sequence
     313                 :            :             // lock on a mempool input, so we can use the return value of
     314                 :            :             // CheckSequenceLocks to indicate the LockPoints validity
     315                 :     252126 :             int maxInputHeight = 0;
     316         [ +  + ]:     758410 :             for (const int height : prevheights) {
     317                 :            :                 // Can ignore mempool inputs since we'll fail if they had non-zero locks
     318         [ +  + ]:     506284 :                 if (height != tip->nHeight+1) {
     319         [ +  + ]:     811681 :                     maxInputHeight = std::max(maxInputHeight, height);
     320                 :            :                 }
     321                 :            :             }
     322         [ +  - ]:     252126 :             lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
     323                 :            :         }
     324                 :            :     }
     325                 :     276582 :     return EvaluateSequenceLocks(index, lockPair);
     326                 :            : }
     327                 :            : 
     328                 :            : // Returns the script flags which should be checked for a given block
     329                 :            : static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& chainparams);
     330                 :            : 
     331                 :     123147 : static void LimitMempoolSize(CTxMemPool& pool, size_t limit, std::chrono::seconds age)
     332                 :            :     EXCLUSIVE_LOCKS_REQUIRED(pool.cs, ::cs_main)
     333                 :            : {
     334                 :     123147 :     int expired = pool.Expire(GetTime<std::chrono::seconds>() - age);
     335         [ +  + ]:     123147 :     if (expired != 0) {
     336         [ +  - ]:          2 :         LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
     337                 :            :     }
     338                 :            : 
     339         [ +  - ]:     123147 :     std::vector<COutPoint> vNoSpendsRemaining;
     340         [ +  - ]:     123147 :     pool.TrimToSize(limit, &vNoSpendsRemaining);
     341         [ +  + ]:     123173 :     for (const COutPoint& removed : vNoSpendsRemaining)
     342   [ +  -  +  - ]:         26 :         ::ChainstateActive().CoinsTip().Uncache(removed);
     343                 :     123147 : }
     344                 :            : 
     345                 :     120176 : static bool IsCurrentForFeeEstimation() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
     346                 :            : {
     347                 :     120176 :     AssertLockHeld(cs_main);
     348         [ +  + ]:     120176 :     if (::ChainstateActive().IsInitialBlockDownload())
     349                 :            :         return false;
     350   [ +  -  +  + ]:     240214 :     if (::ChainActive().Tip()->GetBlockTime() < count_seconds(GetTime<std::chrono::seconds>() - MAX_FEE_ESTIMATION_TIP_AGE))
     351                 :            :         return false;
     352         [ -  + ]:     120002 :     if (::ChainActive().Height() < pindexBestHeader->nHeight - 1)
     353                 :          0 :         return false;
     354                 :            :     return true;
     355                 :            : }
     356                 :            : 
     357                 :            : /* Make mempool consistent after a reorg, by re-adding or recursively erasing
     358                 :            :  * disconnected block transactions from the mempool, and also removing any
     359                 :            :  * other transactions from the mempool that are no longer valid given the new
     360                 :            :  * tip/height.
     361                 :            :  *
     362                 :            :  * Note: we assume that disconnectpool only contains transactions that are NOT
     363                 :            :  * confirmed in the current chain nor already in the mempool (otherwise,
     364                 :            :  * in-mempool descendants of such transactions would be removed).
     365                 :            :  *
     366                 :            :  * Passing fAddToMempool=false will skip trying to add the transactions back,
     367                 :            :  * and instead just erase from the mempool as needed.
     368                 :            :  */
     369                 :            : 
     370                 :       2765 : static void UpdateMempoolForReorg(CTxMemPool& mempool, DisconnectedBlockTransactions& disconnectpool, bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, mempool.cs)
     371                 :            : {
     372                 :       2765 :     AssertLockHeld(cs_main);
     373                 :       2765 :     AssertLockHeld(mempool.cs);
     374                 :       2765 :     std::vector<uint256> vHashUpdate;
     375                 :            :     // disconnectpool's insertion_order index sorts the entries from
     376                 :            :     // oldest to newest, but the oldest entry will be the last tx from the
     377                 :            :     // latest mined block that was disconnected.
     378                 :            :     // Iterate disconnectpool in reverse, so that we add transactions
     379                 :            :     // back to the mempool starting with the earliest transaction that had
     380                 :            :     // been previously seen in a block.
     381                 :       2765 :     auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
     382         [ +  + ]:      24259 :     while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
     383                 :            :         // ignore validation errors in resurrected transactions
     384         [ +  + ]:      45753 :         TxValidationState stateDummy;
     385   [ +  +  +  +  :      58327 :         if (!fAddToMempool || (*it)->IsCoinBase() ||
                   +  + ]
     386         [ +  - ]:      16488 :             !AcceptToMemoryPool(mempool, stateDummy, *it,
     387                 :            :                                 nullptr /* plTxnReplaced */, true /* bypass_limits */)) {
     388                 :            :             // If the transaction doesn't make it in to the mempool, remove any
     389                 :            :             // transactions that depend on it (which would now be orphans).
     390         [ +  - ]:       8700 :             mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
     391   [ +  -  +  - ]:      12794 :         } else if (mempool.exists((*it)->GetHash())) {
     392         [ +  - ]:      12794 :             vHashUpdate.push_back((*it)->GetHash());
     393                 :            :         }
     394         [ +  - ]:      42988 :         ++it;
     395                 :            :     }
     396                 :       2765 :     disconnectpool.queuedTx.clear();
     397                 :            :     // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
     398                 :            :     // no in-mempool children, which is generally not true when adding
     399                 :            :     // previously-confirmed transactions back to the mempool.
     400                 :            :     // UpdateTransactionsFromBlock finds descendants of any transactions in
     401                 :            :     // the disconnectpool that were added back and cleans up the mempool state.
     402         [ +  - ]:       2765 :     mempool.UpdateTransactionsFromBlock(vHashUpdate);
     403                 :            : 
     404                 :            :     // We also need to remove any now-immature transactions
     405   [ +  -  +  -  :       5530 :     mempool.removeForReorg(&::ChainstateActive().CoinsTip(), ::ChainActive().Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
             +  -  +  - ]
     406                 :            :     // Re-limit mempool size, in case we added any transactions
     407   [ +  -  +  -  :       5530 :     LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, std::chrono::hours{gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)});
          +  -  +  -  +  
                      - ]
     408                 :       2765 : }
     409                 :            : 
     410                 :            : // Used to avoid mempool polluting consensus critical paths if CCoinsViewMempool
     411                 :            : // were somehow broken and returning the wrong scriptPubKeys
     412                 :     237903 : static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, TxValidationState& state, const CCoinsViewCache& view, const CTxMemPool& pool,
     413                 :            :                  unsigned int flags, PrecomputedTransactionData& txdata) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
     414                 :     237903 :     AssertLockHeld(cs_main);
     415                 :            : 
     416                 :            :     // pool.cs should be locked already, but go ahead and re-take the lock here
     417                 :            :     // to enforce that mempool doesn't change between when we check the view
     418                 :            :     // and when we actually call through to CheckInputScripts
     419                 :     475806 :     LOCK(pool.cs);
     420                 :            : 
     421         [ -  + ]:     237903 :     assert(!tx.IsCoinBase());
     422         [ +  + ]:     713683 :     for (const CTxIn& txin : tx.vin) {
     423         [ +  - ]:     475780 :         const Coin& coin = view.AccessCoin(txin.prevout);
     424                 :            : 
     425                 :            :         // AcceptToMemoryPoolWorker has already checked that the coins are
     426                 :            :         // available, so this shouldn't fail. If the inputs are not available
     427                 :            :         // here then return false.
     428         [ +  - ]:     475780 :         if (coin.IsSpent()) return false;
     429                 :            : 
     430                 :            :         // Check equivalence for available inputs.
     431         [ +  - ]:     951560 :         const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
     432         [ +  + ]:     475780 :         if (txFrom) {
     433         [ -  + ]:       4829 :             assert(txFrom->GetHash() == txin.prevout.hash);
     434         [ -  + ]:       4829 :             assert(txFrom->vout.size() > txin.prevout.n);
     435         [ -  + ]:       4829 :             assert(txFrom->vout[txin.prevout.n] == coin.out);
     436                 :            :         } else {
     437   [ +  -  +  - ]:     470951 :             const Coin& coinFromDisk = ::ChainstateActive().CoinsTip().AccessCoin(txin.prevout);
     438         [ -  + ]:     470951 :             assert(!coinFromDisk.IsSpent());
     439         [ -  + ]:     470951 :             assert(coinFromDisk.out == coin.out);
     440                 :            :         }
     441                 :            :     }
     442                 :            : 
     443                 :            :     // Call CheckInputScripts() to cache signature and script validity against current tip consensus rules.
     444         [ +  - ]:     237903 :     return CheckInputScripts(tx, state, view, flags, /* cacheSigStore = */ true, /* cacheFullSciptStore = */ true, txdata);
     445                 :            : }
     446                 :            : 
     447                 :            : namespace {
     448                 :            : 
     449                 :            : class MemPoolAccept
     450                 :            : {
     451                 :            : public:
     452                 :     246232 :     explicit MemPoolAccept(CTxMemPool& mempool) : m_pool(mempool), m_view(&m_dummy), m_viewmempool(&::ChainstateActive().CoinsTip(), m_pool),
     453   [ +  -  +  -  :     492464 :         m_limit_ancestors(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT)),
                   +  - ]
     454   [ +  -  +  -  :     492464 :         m_limit_ancestor_size(gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000),
                   +  - ]
     455   [ +  -  +  -  :     492464 :         m_limit_descendants(gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT)),
                   +  - ]
     456   [ +  -  +  -  :    1231160 :         m_limit_descendant_size(gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000) {}
          +  -  +  -  +  
                      - ]
     457                 :            : 
     458                 :            :     // We put the arguments we're handed into a struct, so we can pass them
     459                 :            :     // around easier.
     460                 :            :     struct ATMPArgs {
     461                 :            :         const CChainParams& m_chainparams;
     462                 :            :         TxValidationState &m_state;
     463                 :            :         const int64_t m_accept_time;
     464                 :            :         std::list<CTransactionRef>* m_replaced_transactions;
     465                 :            :         const bool m_bypass_limits;
     466                 :            :         /*
     467                 :            :          * Return any outpoints which were not previously present in the coins
     468                 :            :          * cache, but were added as a result of validating the tx for mempool
     469                 :            :          * acceptance. This allows the caller to optionally remove the cache
     470                 :            :          * additions if the associated transaction ends up being rejected by
     471                 :            :          * the mempool.
     472                 :            :          */
     473                 :            :         std::vector<COutPoint>& m_coins_to_uncache;
     474                 :            :         const bool m_test_accept;
     475                 :            :         CAmount* m_fee_out;
     476                 :            :     };
     477                 :            : 
     478                 :            :     // Single transaction acceptance
     479                 :            :     bool AcceptSingleTransaction(const CTransactionRef& ptx, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     480                 :            : 
     481                 :            : private:
     482                 :            :     // All the intermediate state that gets passed between the various levels
     483                 :            :     // of checking a given transaction.
     484                 :            :     struct Workspace {
     485                 :     246232 :         explicit Workspace(const CTransactionRef& ptx) : m_ptx(ptx), m_hash(ptx->GetHash()) {}
     486                 :            :         std::set<uint256> m_conflicts;
     487                 :            :         CTxMemPool::setEntries m_all_conflicting;
     488                 :            :         CTxMemPool::setEntries m_ancestors;
     489                 :            :         std::unique_ptr<CTxMemPoolEntry> m_entry;
     490                 :            : 
     491                 :            :         bool m_replacement_transaction;
     492                 :            :         CAmount m_modified_fees;
     493                 :            :         CAmount m_conflicting_fees;
     494                 :            :         size_t m_conflicting_size;
     495                 :            : 
     496                 :            :         const CTransactionRef& m_ptx;
     497                 :            :         const uint256& m_hash;
     498                 :            :     };
     499                 :            : 
     500                 :            :     // Run the policy checks on a given transaction, excluding any script checks.
     501                 :            :     // Looks up inputs, calculates feerate, considers replacement, evaluates
     502                 :            :     // package limits, etc. As this function can be invoked for "free" by a peer,
     503                 :            :     // only tests that are fast should be done here (to avoid CPU DoS).
     504                 :            :     bool PreChecks(ATMPArgs& args, Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
     505                 :            : 
     506                 :            :     // Run the script checks using our policy flags. As this can be slow, we should
     507                 :            :     // only invoke this on transactions that have otherwise passed policy checks.
     508                 :            :     bool PolicyScriptChecks(ATMPArgs& args, Workspace& ws, PrecomputedTransactionData& txdata) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     509                 :            : 
     510                 :            :     // Re-run the script checks, using consensus flags, and try to cache the
     511                 :            :     // result in the scriptcache. This should be done after
     512                 :            :     // PolicyScriptChecks(). This requires that all inputs either be in our
     513                 :            :     // utxo set or in the mempool.
     514                 :            :     bool ConsensusScriptChecks(ATMPArgs& args, Workspace& ws, PrecomputedTransactionData &txdata) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     515                 :            : 
     516                 :            :     // Try to add the transaction to the mempool, removing any conflicts first.
     517                 :            :     // Returns true if the transaction is in the mempool after any size
     518                 :            :     // limiting is performed, false otherwise.
     519                 :            :     bool Finalize(ATMPArgs& args, Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
     520                 :            : 
     521                 :            :     // Compare a package's feerate against minimum allowed.
     522                 :     227315 :     bool CheckFeeRate(size_t package_size, CAmount package_fee, TxValidationState& state)
     523                 :            :     {
     524   [ +  -  +  -  :     227315 :         CAmount mempoolRejectFee = m_pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(package_size);
             +  -  +  + ]
     525         [ +  + ]:         25 :         if (mempoolRejectFee > 0 && package_fee < mempoolRejectFee) {
     526   [ +  -  +  - ]:          1 :             return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool min fee not met", strprintf("%d < %d", package_fee, mempoolRejectFee));
     527                 :            :         }
     528                 :            : 
     529         [ +  + ]:     227314 :         if (package_fee < ::minRelayTxFee.GetFee(package_size)) {
     530   [ +  -  +  - ]:     227329 :             return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "min relay fee not met", strprintf("%d < %d", package_fee, ::minRelayTxFee.GetFee(package_size)));
     531                 :            :         }
     532                 :            :         return true;
     533                 :            :     }
     534                 :            : 
     535                 :            : private:
     536                 :            :     CTxMemPool& m_pool;
     537                 :            :     CCoinsViewCache m_view;
     538                 :            :     CCoinsViewMemPool m_viewmempool;
     539                 :            :     CCoinsView m_dummy;
     540                 :            : 
     541                 :            :     // The package limits in effect at the time of invocation.
     542                 :            :     const size_t m_limit_ancestors;
     543                 :            :     const size_t m_limit_ancestor_size;
     544                 :            :     // These may be modified while evaluating a transaction (eg to account for
     545                 :            :     // in-mempool conflicts; see below).
     546                 :            :     size_t m_limit_descendants;
     547                 :            :     size_t m_limit_descendant_size;
     548                 :            : };
     549                 :            : 
     550                 :     246232 : bool MemPoolAccept::PreChecks(ATMPArgs& args, Workspace& ws)
     551                 :            : {
     552                 :     246232 :     const CTransactionRef& ptx = ws.m_ptx;
     553                 :     246232 :     const CTransaction& tx = *ws.m_ptx;
     554                 :     246232 :     const uint256& hash = ws.m_hash;
     555                 :            : 
     556                 :            :     // Copy/alias what we need out of args
     557                 :     246232 :     TxValidationState &state = args.m_state;
     558                 :     246232 :     const int64_t nAcceptTime = args.m_accept_time;
     559                 :     246232 :     const bool bypass_limits = args.m_bypass_limits;
     560                 :     246232 :     std::vector<COutPoint>& coins_to_uncache = args.m_coins_to_uncache;
     561                 :            : 
     562                 :            :     // Alias what we need out of ws
     563                 :     246232 :     std::set<uint256>& setConflicts = ws.m_conflicts;
     564                 :     246232 :     CTxMemPool::setEntries& allConflicting = ws.m_all_conflicting;
     565                 :     246232 :     CTxMemPool::setEntries& setAncestors = ws.m_ancestors;
     566                 :     246232 :     std::unique_ptr<CTxMemPoolEntry>& entry = ws.m_entry;
     567                 :     246232 :     bool& fReplacementTransaction = ws.m_replacement_transaction;
     568                 :     246232 :     CAmount& nModifiedFees = ws.m_modified_fees;
     569                 :     246232 :     CAmount& nConflictingFees = ws.m_conflicting_fees;
     570                 :     246232 :     size_t& nConflictingSize = ws.m_conflicting_size;
     571                 :            : 
     572         [ +  + ]:     246232 :     if (!CheckTransaction(tx, state)) {
     573                 :            :         return false; // state filled in by CheckTransaction
     574                 :            :     }
     575                 :            : 
     576                 :            :     // Coinbase is only valid in a block, not as a loose transaction
     577         [ +  + ]:     246220 :     if (tx.IsCoinBase())
     578   [ +  -  +  - ]:          2 :         return state.Invalid(TxValidationResult::TX_CONSENSUS, "coinbase");
     579                 :            : 
     580                 :            :     // Rather not work on nonstandard transactions (unless -testnet/-regtest)
     581         [ +  + ]:     492450 :     std::string reason;
     582   [ +  +  +  + ]:     255988 :     if (fRequireStandard && !IsStandardTx(tx, reason))
     583   [ +  -  +  - ]:       1592 :         return state.Invalid(TxValidationResult::TX_NOT_STANDARD, reason);
     584                 :            : 
     585                 :            :     // Do not work on transactions that are too small.
     586                 :            :     // A transaction with 1 segwit input and 1 P2WPHK output has non-witness size of 82 bytes.
     587                 :            :     // Transactions smaller than this are not relayed to mitigate CVE-2017-12842 by not relaying
     588                 :            :     // 64-byte transactions.
     589         [ +  + ]:     244626 :     if (::GetSerializeSize(tx, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) < MIN_STANDARD_TX_NONWITNESS_SIZE)
     590   [ +  -  +  -  :          6 :         return state.Invalid(TxValidationResult::TX_NOT_STANDARD, "tx-size-small");
                   +  - ]
     591                 :            : 
     592                 :            :     // Only accept nLockTime-using transactions that can be mined in the next
     593                 :            :     // block; we don't want our mempool filled up with transactions that can't
     594                 :            :     // be mined yet.
     595   [ +  -  +  + ]:     244620 :     if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
     596   [ +  -  +  -  :         84 :         return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "non-final");
                   +  - ]
     597                 :            : 
     598                 :            :     // is it already in the memory pool?
     599   [ +  -  +  + ]:     244536 :     if (m_pool.exists(hash)) {
     600   [ +  -  +  -  :         71 :         return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-already-in-mempool");
                   +  - ]
     601                 :            :     }
     602                 :            : 
     603                 :            :     // Check for conflicts with in-memory transactions
     604         [ +  + ]:     735192 :     for (const CTxIn &txin : tx.vin)
     605                 :            :     {
     606         [ +  - ]:     490731 :         const CTransaction* ptxConflicting = m_pool.GetConflictTx(txin.prevout);
     607         [ +  + ]:     490731 :         if (ptxConflicting) {
     608         [ +  + ]:        609 :             if (!setConflicts.count(ptxConflicting->GetHash()))
     609                 :            :             {
     610                 :            :                 // Allow opt-out of transaction replacement by setting
     611                 :            :                 // nSequence > MAX_BIP125_RBF_SEQUENCE (SEQUENCE_FINAL-2) on all inputs.
     612                 :            :                 //
     613                 :            :                 // SEQUENCE_FINAL-1 is picked to still allow use of nLockTime by
     614                 :            :                 // non-replaceable transactions. All inputs rather than just one
     615                 :            :                 // is for the sake of multi-party protocols, where we don't
     616                 :            :                 // want a single party to be able to disable replacement.
     617                 :            :                 //
     618                 :            :                 // The opt-out ignores descendants as anyone relying on
     619                 :            :                 // first-seen mempool behavior should be checking all
     620                 :            :                 // unconfirmed ancestors anyway; doing otherwise is hopelessly
     621                 :            :                 // insecure.
     622                 :        601 :                 bool fReplacementOptOut = true;
     623         [ +  + ]:        606 :                 for (const CTxIn &_txin : ptxConflicting->vin)
     624                 :            :                 {
     625         [ +  + ]:        602 :                     if (_txin.nSequence <= MAX_BIP125_RBF_SEQUENCE)
     626                 :            :                     {
     627                 :            :                         fReplacementOptOut = false;
     628                 :            :                         break;
     629                 :            :                     }
     630                 :            :                 }
     631         [ +  + ]:        601 :                 if (fReplacementOptOut) {
     632   [ +  -  +  -  :          4 :                     return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "txn-mempool-conflict");
                   +  - ]
     633                 :            :                 }
     634                 :            : 
     635         [ +  - ]:        597 :                 setConflicts.insert(ptxConflicting->GetHash());
     636                 :            :             }
     637                 :            :         }
     638                 :            :     }
     639                 :            : 
     640         [ +  - ]:     244461 :     LockPoints lp;
     641         [ +  - ]:     244461 :     m_view.SetBackend(m_viewmempool);
     642                 :            : 
     643         [ +  - ]:     244461 :     CCoinsViewCache& coins_cache = ::ChainstateActive().CoinsTip();
     644                 :            :     // do all inputs exist?
     645         [ +  + ]:     728275 :     for (const CTxIn& txin : tx.vin) {
     646   [ +  -  +  + ]:     487385 :         if (!coins_cache.HaveCoinInCache(txin.prevout)) {
     647         [ +  - ]:      12049 :             coins_to_uncache.push_back(txin.prevout);
     648                 :            :         }
     649                 :            : 
     650                 :            :         // Note: this call may add txin.prevout to the coins cache
     651                 :            :         // (coins_cache.cacheCoins) by way of FetchCoin(). It should be removed
     652                 :            :         // later (via coins_to_uncache) if this tx turns out to be invalid.
     653   [ +  -  +  + ]:     487385 :         if (!m_view.HaveCoin(txin.prevout)) {
     654                 :            :             // Are inputs missing because we already have the tx?
     655         [ +  + ]:       7161 :             for (size_t out = 0; out < tx.vout.size(); out++) {
     656                 :            :                 // Optimistically just do efficient check of cache for outputs
     657   [ +  -  +  + ]:       3591 :                 if (coins_cache.HaveCoinInCache(COutPoint(hash, out))) {
     658   [ +  -  +  -  :          1 :                     return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-already-known");
                   +  - ]
     659                 :            :                 }
     660                 :            :             }
     661                 :            :             // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
     662   [ +  -  +  -  :       3570 :             return state.Invalid(TxValidationResult::TX_MISSING_INPUTS, "bad-txns-inputs-missingorspent");
                   +  - ]
     663                 :            :         }
     664                 :            :     }
     665                 :            : 
     666                 :            :     // Bring the best block into scope
     667         [ +  - ]:     240890 :     m_view.GetBestBlock();
     668                 :            : 
     669                 :            :     // we have all inputs cached now, so switch back to dummy (to protect
     670                 :            :     // against bugs where we pull more inputs from disk that miss being added
     671                 :            :     // to coins_to_uncache)
     672         [ +  - ]:     240890 :     m_view.SetBackend(m_dummy);
     673                 :            : 
     674                 :            :     // Only accept BIP68 sequence locked transactions that can be mined in the next
     675                 :            :     // block; we don't want our mempool filled up with transactions that can't
     676                 :            :     // be mined yet.
     677                 :            :     // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
     678                 :            :     // CoinsViewCache instead of create its own
     679   [ +  -  +  + ]:     240890 :     if (!CheckSequenceLocks(m_pool, tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
     680   [ +  -  +  -  :        367 :         return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "non-BIP68-final");
                   +  - ]
     681                 :            : 
     682                 :     240523 :     CAmount nFees = 0;
     683   [ +  -  +  -  :     240523 :     if (!Consensus::CheckTxInputs(tx, state, m_view, GetSpendHeight(m_view), nFees)) {
                   +  + ]
     684                 :            :         return false; // state filled in by CheckTxInputs
     685                 :            :     }
     686                 :            : 
     687                 :            :     // If fee_out is passed, return the fee to the caller
     688         [ +  + ]:     240520 :     if (args.m_fee_out) {
     689                 :     104757 :         *args.m_fee_out = nFees;
     690                 :            :     }
     691                 :            : 
     692                 :            :     // Check for non-standard pay-to-script-hash in inputs
     693         [ +  - ]:     240520 :     const auto& params = args.m_chainparams.GetConsensus();
     694   [ +  -  +  -  :     481040 :     auto taproot_state = VersionBitsState(::ChainActive().Tip(), params, Consensus::DEPLOYMENT_TAPROOT, versionbitscache);
                   +  - ]
     695   [ +  +  +  -  :     240520 :     if (fRequireStandard && !AreInputsStandard(tx, m_view, taproot_state == ThresholdState::ACTIVE)) {
                   +  + ]
     696   [ +  -  +  -  :     246428 :         return state.Invalid(TxValidationResult::TX_INPUTS_NOT_STANDARD, "bad-txns-nonstandard-inputs");
                   +  - ]
     697                 :            :     }
     698                 :            : 
     699                 :            :     // Check for non-standard witnesses.
     700   [ +  +  +  +  :     240310 :     if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, m_view))
             +  -  +  + ]
     701   [ +  -  +  -  :        156 :         return state.Invalid(TxValidationResult::TX_WITNESS_MUTATED, "bad-witness-nonstandard");
                   +  - ]
     702                 :            : 
     703         [ +  - ]:     240154 :     int64_t nSigOpsCost = GetTransactionSigOpCost(tx, m_view, STANDARD_SCRIPT_VERIFY_FLAGS);
     704                 :            : 
     705                 :            :     // nModifiedFees includes any fee deltas from PrioritiseTransaction
     706                 :     240154 :     nModifiedFees = nFees;
     707         [ +  - ]:     240154 :     m_pool.ApplyDelta(hash, nModifiedFees);
     708                 :            : 
     709                 :            :     // Keep track of transactions that spend a coinbase, which we re-scan
     710                 :            :     // during reorgs to ensure COINBASE_MATURITY is still met.
     711                 :     240154 :     bool fSpendsCoinbase = false;
     712         [ +  + ]:     709351 :     for (const CTxIn &txin : tx.vin) {
     713         [ +  - ]:     476326 :         const Coin &coin = m_view.AccessCoin(txin.prevout);
     714         [ +  + ]:     476326 :         if (coin.IsCoinBase()) {
     715                 :            :             fSpendsCoinbase = true;
     716                 :            :             break;
     717                 :            :         }
     718                 :            :     }
     719                 :            : 
     720   [ +  -  +  - ]:     240154 :     entry.reset(new CTxMemPoolEntry(ptx, nFees, nAcceptTime, ::ChainActive().Height(),
     721   [ +  -  +  - ]:     240154 :             fSpendsCoinbase, nSigOpsCost, lp));
     722         [ +  - ]:     240154 :     unsigned int nSize = entry->GetTxSize();
     723                 :            : 
     724         [ +  + ]:     240154 :     if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
     725         [ +  - ]:          4 :         return state.Invalid(TxValidationResult::TX_NOT_STANDARD, "bad-txns-too-many-sigops",
     726   [ +  -  +  - ]:          8 :                 strprintf("%d", nSigOpsCost));
     727                 :            : 
     728                 :            :     // No transactions are allowed below minRelayTxFee except from disconnected
     729                 :            :     // blocks
     730   [ +  +  +  -  :     240150 :     if (!bypass_limits && !CheckFeeRate(nSize, nModifiedFees, state)) return false;
                   +  + ]
     731                 :            : 
     732         [ +  - ]:     486353 :     const CTxMemPool::setEntries setIterConflicting = m_pool.GetIterSet(setConflicts);
     733                 :            :     // Calculate in-mempool ancestors, up to a limit.
     734         [ +  + ]:     240135 :     if (setConflicts.size() == 1) {
     735                 :            :         // In general, when we receive an RBF transaction with mempool conflicts, we want to know whether we
     736                 :            :         // would meet the chain limits after the conflicts have been removed. However, there isn't a practical
     737                 :            :         // way to do this short of calculating the ancestor and descendant sets with an overlay cache of
     738                 :            :         // changed mempool entries. Due to both implementation and runtime complexity concerns, this isn't
     739                 :            :         // very realistic, thus we only ensure a limited set of transactions are RBF'able despite mempool
     740                 :            :         // conflicts here. Importantly, we need to ensure that some transactions which were accepted using
     741                 :            :         // the below carve-out are able to be RBF'ed, without impacting the security the carve-out provides
     742                 :            :         // for off-chain contract systems (see link in the comment below).
     743                 :            :         //
     744                 :            :         // Specifically, the subset of RBF transactions which we allow despite chain limits are those which
     745                 :            :         // conflict directly with exactly one other transaction (but may evict children of said transaction),
     746                 :            :         // and which are not adding any new mempool dependencies. Note that the "no new mempool dependencies"
     747                 :            :         // check is accomplished later, so we don't bother doing anything about it here, but if BIP 125 is
     748                 :            :         // amended, we may need to move that check to here instead of removing it wholesale.
     749                 :            :         //
     750                 :            :         // Such transactions are clearly not merging any existing packages, so we are only concerned with
     751                 :            :         // ensuring that (a) no package is growing past the package size (not count) limits and (b) we are
     752                 :            :         // not allowing something to effectively use the (below) carve-out spot when it shouldn't be allowed
     753                 :            :         // to.
     754                 :            :         //
     755                 :            :         // To check these we first check if we meet the RBF criteria, above, and increment the descendant
     756                 :            :         // limits by the direct conflict and its descendants (as these are recalculated in
     757                 :            :         // CalculateMempoolAncestors by assuming the new transaction being added is a new descendant, with no
     758                 :            :         // removals, of each parent's existing dependent set). The ancestor count limits are unmodified (as
     759                 :            :         // the ancestor limits should be the same for both our new transaction and any conflicts).
     760                 :            :         // We don't bother incrementing m_limit_descendants by the full removal count as that limit never comes
     761                 :            :         // into force here (as we're only adding a single transaction).
     762         [ -  + ]:        396 :         assert(setIterConflicting.size() == 1);
     763                 :        396 :         CTxMemPool::txiter conflict = *setIterConflicting.begin();
     764                 :            : 
     765                 :        396 :         m_limit_descendants += 1;
     766                 :        396 :         m_limit_descendant_size += conflict->GetSizeWithDescendants();
     767                 :            :     }
     768                 :            : 
     769         [ +  - ]:     480270 :     std::string errString;
     770   [ +  -  +  + ]:     240135 :     if (!m_pool.CalculateMemPoolAncestors(*entry, setAncestors, m_limit_ancestors, m_limit_ancestor_size, m_limit_descendants, m_limit_descendant_size, errString)) {
     771                 :         70 :         setAncestors.clear();
     772                 :            :         // If CalculateMemPoolAncestors fails second time, we want the original error string.
     773         [ +  + ]:         70 :         std::string dummy_err_string;
     774                 :            :         // Contracting/payment channels CPFP carve-out:
     775                 :            :         // If the new transaction is relatively small (up to 40k weight)
     776                 :            :         // and has at most one ancestor (ie ancestor limit of 2, including
     777                 :            :         // the new transaction), allow it if its parent has exactly the
     778                 :            :         // descendant limit descendants.
     779                 :            :         //
     780                 :            :         // This allows protocols which rely on distrusting counterparties
     781                 :            :         // being able to broadcast descendants of an unconfirmed transaction
     782                 :            :         // to be secure by simply only having two immediately-spendable
     783                 :            :         // outputs - one for each counterparty. For more info on the uses for
     784                 :            :         // this, see https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-November/016518.html
     785   [ +  +  +  + ]:        120 :         if (nSize >  EXTRA_DESCENDANT_TX_SIZE_LIMIT ||
     786         [ +  - ]:         50 :                 !m_pool.CalculateMemPoolAncestors(*entry, setAncestors, 2, m_limit_ancestor_size, m_limit_descendants + 1, m_limit_descendant_size + EXTRA_DESCENDANT_TX_SIZE_LIMIT, dummy_err_string)) {
     787   [ +  -  +  - ]:         64 :             return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "too-long-mempool-chain", errString);
     788                 :            :         }
     789                 :            :     }
     790                 :            : 
     791                 :            :     // A transaction that spends outputs that would be replaced by it is invalid. Now
     792                 :            :     // that we have the set of all ancestors we can detect this
     793                 :            :     // pathological case by making sure setConflicts and setAncestors don't
     794                 :            :     // intersect.
     795         [ +  + ]:     249625 :     for (CTxMemPool::txiter ancestorIt : setAncestors)
     796                 :            :     {
     797                 :       9556 :         const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
     798         [ +  + ]:       9556 :         if (setConflicts.count(hashAncestor))
     799                 :            :         {
     800         [ +  - ]:          2 :             return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-spends-conflicting-tx",
     801                 :          2 :                     strprintf("%s spends conflicting transaction %s",
     802         [ +  - ]:          4 :                         hash.ToString(),
     803   [ +  -  +  -  :          6 :                         hashAncestor.ToString()));
                   +  - ]
     804                 :            :         }
     805                 :            :     }
     806                 :            : 
     807                 :            :     // Check if it's economically rational to mine this transaction rather
     808                 :            :     // than the ones it replaces.
     809                 :     240069 :     nConflictingFees = 0;
     810                 :     240069 :     nConflictingSize = 0;
     811                 :     240069 :     uint64_t nConflictingCount = 0;
     812                 :            : 
     813                 :            :     // If we don't hold the lock allConflicting might be incomplete; the
     814                 :            :     // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
     815                 :            :     // mempool consistency for us.
     816         [ +  + ]:     240069 :     fReplacementTransaction = setConflicts.size();
     817         [ +  + ]:     240069 :     if (fReplacementTransaction)
     818                 :            :     {
     819         [ +  - ]:        396 :         CFeeRate newFeeRate(nModifiedFees, nSize);
     820                 :     240531 :         std::set<uint256> setConflictsParents;
     821                 :        396 :         const int maxDescendantsToVisit = 100;
     822         [ +  + ]:        987 :         for (const auto& mi : setIterConflicting) {
     823                 :            :             // Don't allow the replacement to reduce the feerate of the
     824                 :            :             // mempool.
     825                 :            :             //
     826                 :            :             // We usually don't want to accept replacements with lower
     827                 :            :             // feerates than what they replaced as that would lower the
     828                 :            :             // feerate of the next block. Requiring that the feerate always
     829                 :            :             // be increased is also an easy-to-reason about way to prevent
     830                 :            :             // DoS attacks via replacements.
     831                 :            :             //
     832                 :            :             // We only consider the feerates of transactions being directly
     833                 :            :             // replaced, not their indirect descendants. While that does
     834                 :            :             // mean high feerate children are ignored when deciding whether
     835                 :            :             // or not to replace, we do require the replacement to pay more
     836                 :            :             // overall fees too, mitigating most cases.
     837   [ +  -  +  - ]:        595 :             CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
     838         [ +  + ]:        595 :             if (newFeeRate <= oldFeeRate)
     839                 :            :             {
     840   [ +  -  +  - ]:          8 :                 return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee",
     841                 :          4 :                         strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
     842         [ +  - ]:          8 :                             hash.ToString(),
     843         [ +  - ]:          8 :                             newFeeRate.ToString(),
     844   [ +  -  +  -  :         12 :                             oldFeeRate.ToString()));
                   +  - ]
     845                 :            :             }
     846                 :            : 
     847         [ +  + ]:       1191 :             for (const CTxIn &txin : mi->GetTx().vin)
     848                 :            :             {
     849         [ +  - ]:        600 :                 setConflictsParents.insert(txin.prevout.hash);
     850                 :            :             }
     851                 :            : 
     852                 :        591 :             nConflictingCount += mi->GetCountWithDescendants();
     853                 :            :         }
     854                 :            :         // This potentially overestimates the number of actual descendants
     855                 :            :         // but we just want to be conservative to avoid doing too much
     856                 :            :         // work.
     857         [ +  + ]:        392 :         if (nConflictingCount <= maxDescendantsToVisit) {
     858                 :            :             // If not too many to replace, then calculate the set of
     859                 :            :             // transactions that would have to be evicted
     860         [ +  + ]:        877 :             for (CTxMemPool::txiter it : setIterConflicting) {
     861         [ +  - ]:        488 :                 m_pool.CalculateDescendants(it, allConflicting);
     862                 :            :             }
     863         [ +  + ]:       1159 :             for (CTxMemPool::txiter it : allConflicting) {
     864         [ +  - ]:        770 :                 nConflictingFees += it->GetModifiedFee();
     865         [ +  - ]:        770 :                 nConflictingSize += it->GetTxSize();
     866                 :            :             }
     867                 :            :         } else {
     868         [ +  - ]:          3 :             return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "too many potential replacements",
     869                 :          3 :                     strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
     870         [ +  - ]:          3 :                         hash.ToString(),
     871                 :            :                         nConflictingCount,
     872   [ +  -  +  - ]:          6 :                         maxDescendantsToVisit));
     873                 :            :         }
     874                 :            : 
     875         [ +  + ]:        937 :         for (unsigned int j = 0; j < tx.vin.size(); j++)
     876                 :            :         {
     877                 :            :             // We don't want to accept replacements that require low
     878                 :            :             // feerate junk to be mined first. Ideally we'd keep track of
     879                 :            :             // the ancestor feerates and make the decision based on that,
     880                 :            :             // but for now requiring all new inputs to be confirmed works.
     881                 :            :             //
     882                 :            :             // Note that if you relax this to make RBF a little more useful,
     883                 :            :             // this may break the CalculateMempoolAncestors RBF relaxation,
     884                 :            :             // above. See the comment above the first CalculateMempoolAncestors
     885                 :            :             // call for more info.
     886         [ +  + ]:        549 :             if (!setConflictsParents.count(tx.vin[j].prevout.hash))
     887                 :            :             {
     888                 :            :                 // Rather than check the UTXO set - potentially expensive -
     889                 :            :                 // it's cheaper to just check if the new input refers to a
     890                 :            :                 // tx that's in the mempool.
     891   [ +  -  +  + ]:         49 :                 if (m_pool.exists(tx.vin[j].prevout.hash)) {
     892         [ +  - ]:          1 :                     return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "replacement-adds-unconfirmed",
     893                 :          1 :                             strprintf("replacement %s adds unconfirmed input, idx %d",
     894   [ +  -  +  -  :          2 :                                 hash.ToString(), j));
                   +  - ]
     895                 :            :                 }
     896                 :            :             }
     897                 :            :         }
     898                 :            : 
     899                 :            :         // The replacement must pay greater fees than the transactions it
     900                 :            :         // replaces - if we did the bandwidth used by those conflicting
     901                 :            :         // transactions would not be paid for.
     902         [ +  + ]:        388 :         if (nModifiedFees < nConflictingFees)
     903                 :            :         {
     904         [ +  - ]:          2 :             return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee",
     905                 :          2 :                     strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
     906   [ +  -  +  -  :          6 :                         hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
          +  -  +  -  +  
                      - ]
     907                 :            :         }
     908                 :            : 
     909                 :            :         // Finally in addition to paying more fees than the conflicts the
     910                 :            :         // new transaction must pay for its own bandwidth.
     911                 :        386 :         CAmount nDeltaFees = nModifiedFees - nConflictingFees;
     912   [ +  -  -  + ]:        386 :         if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
     913                 :            :         {
     914         [ #  # ]:          0 :             return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee",
     915                 :          0 :                     strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
     916         [ #  # ]:          0 :                         hash.ToString(),
     917         [ #  # ]:          0 :                         FormatMoney(nDeltaFees),
     918   [ -  -  -  -  :         10 :                         FormatMoney(::incrementalRelayFee.GetFee(nSize))));
             -  -  -  - ]
     919                 :            :         }
     920                 :            :     }
     921                 :            :     return true;
     922                 :            : }
     923                 :            : 
     924                 :     240059 : bool MemPoolAccept::PolicyScriptChecks(ATMPArgs& args, Workspace& ws, PrecomputedTransactionData& txdata)
     925                 :            : {
     926                 :     240059 :     const CTransaction& tx = *ws.m_ptx;
     927                 :            : 
     928                 :     240059 :     TxValidationState &state = args.m_state;
     929                 :            : 
     930                 :     240059 :     constexpr unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
     931                 :            : 
     932                 :            :     // Check input scripts and signatures.
     933                 :            :     // This is done last to help prevent CPU exhaustion denial-of-service attacks.
     934         [ +  + ]:     240059 :     if (!CheckInputScripts(tx, state, m_view, scriptVerifyFlags, true, false, txdata)) {
     935                 :            :         // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
     936                 :            :         // need to turn both off, and compare against just turning off CLEANSTACK
     937                 :            :         // to see if the failure is specifically due to witness validation.
     938                 :     242215 :         TxValidationState state_dummy; // Want reported failures to be from first CheckInputScripts
     939   [ +  +  +  -  :       2165 :         if (!tx.HasWitness() && CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, txdata) &&
             +  +  +  - ]
     940         [ +  - ]:          9 :                 !CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, txdata)) {
     941                 :            :             // Only the witness is missing, so the transaction itself may be fine.
     942                 :         18 :             state.Invalid(TxValidationResult::TX_WITNESS_STRIPPED,
     943   [ +  -  +  -  :         18 :                     state.GetRejectReason(), state.GetDebugMessage());
                   +  - ]
     944                 :            :         }
     945                 :       2156 :         return false; // state filled in by CheckInputScripts
     946                 :            :     }
     947                 :            : 
     948                 :            :     return true;
     949                 :            : }
     950                 :            : 
     951                 :     237903 : bool MemPoolAccept::ConsensusScriptChecks(ATMPArgs& args, Workspace& ws, PrecomputedTransactionData& txdata)
     952                 :            : {
     953                 :     237903 :     const CTransaction& tx = *ws.m_ptx;
     954                 :     237903 :     const uint256& hash = ws.m_hash;
     955                 :            : 
     956                 :     237903 :     TxValidationState &state = args.m_state;
     957                 :     237903 :     const CChainParams& chainparams = args.m_chainparams;
     958                 :            : 
     959                 :            :     // Check again against the current block tip's script verification
     960                 :            :     // flags to cache our script execution flags. This is, of course,
     961                 :            :     // useless if the next block has different script flags from the
     962                 :            :     // previous one, but because the cache tracks script flags for us it
     963                 :            :     // will auto-invalidate and we'll just have a few blocks of extra
     964                 :            :     // misses on soft-fork activation.
     965                 :            :     //
     966                 :            :     // This is also useful in case of bugs in the standard flags that cause
     967                 :            :     // transactions to pass as valid when they're actually invalid. For
     968                 :            :     // instance the STRICTENC flag was incorrectly allowing certain
     969                 :            :     // CHECKSIG NOT scripts to pass, even though they were invalid.
     970                 :            :     //
     971                 :            :     // There is a similar check in CreateNewBlock() to prevent creating
     972                 :            :     // invalid blocks (using TestBlockValidity), however allowing such
     973                 :            :     // transactions into the mempool can be exploited as a DoS attack.
     974         [ +  - ]:     475806 :     unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(::ChainActive().Tip(), chainparams.GetConsensus());
     975         [ -  + ]:     237903 :     if (!CheckInputsFromMempoolAndCache(tx, state, m_view, m_pool, currentBlockScriptVerifyFlags, txdata)) {
     976         [ #  # ]:          0 :         return error("%s: BUG! PLEASE REPORT THIS! CheckInputScripts failed against latest-block but not STANDARD flags %s, %s",
     977         [ -  - ]:     237903 :                 __func__, hash.ToString(), state.ToString());
     978                 :            :     }
     979                 :            : 
     980                 :            :     return true;
     981                 :            : }
     982                 :            : 
     983                 :     133179 : bool MemPoolAccept::Finalize(ATMPArgs& args, Workspace& ws)
     984                 :            : {
     985                 :     133179 :     const CTransaction& tx = *ws.m_ptx;
     986                 :     133179 :     const uint256& hash = ws.m_hash;
     987                 :     133179 :     TxValidationState &state = args.m_state;
     988                 :     133179 :     const bool bypass_limits = args.m_bypass_limits;
     989                 :            : 
     990                 :     133179 :     CTxMemPool::setEntries& allConflicting = ws.m_all_conflicting;
     991                 :     133179 :     CTxMemPool::setEntries& setAncestors = ws.m_ancestors;
     992                 :     133179 :     const CAmount& nModifiedFees = ws.m_modified_fees;
     993                 :     133179 :     const CAmount& nConflictingFees = ws.m_conflicting_fees;
     994                 :     133179 :     const size_t& nConflictingSize = ws.m_conflicting_size;
     995                 :     133179 :     const bool fReplacementTransaction = ws.m_replacement_transaction;
     996                 :     133179 :     std::unique_ptr<CTxMemPoolEntry>& entry = ws.m_entry;
     997                 :            : 
     998                 :            :     // Remove conflicting transactions from the mempool
     999         [ +  + ]:     133627 :     for (CTxMemPool::txiter it : allConflicting)
    1000                 :            :     {
    1001   [ +  -  +  -  :        896 :         LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s additional fees, %d delta bytes\n",
             +  -  +  - ]
    1002                 :            :                 it->GetTx().GetHash().ToString(),
    1003                 :            :                 hash.ToString(),
    1004                 :            :                 FormatMoney(nModifiedFees - nConflictingFees),
    1005                 :            :                 (int)entry->GetTxSize() - (int)nConflictingSize);
    1006         [ +  + ]:        448 :         if (args.m_replaced_transactions)
    1007   [ +  -  +  - ]:        490 :             args.m_replaced_transactions->push_back(it->GetSharedTx());
    1008                 :            :     }
    1009                 :     133179 :     m_pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
    1010                 :            : 
    1011                 :            :     // This transaction should only count for fee estimation if:
    1012                 :            :     // - it isn't a BIP 125 replacement transaction (may not be widely supported)
    1013                 :            :     // - it's not being re-added during a reorg which bypasses typical mempool fee limits
    1014                 :            :     // - the node is not behind
    1015                 :            :     // - the transaction is not dependent on any other transactions in the mempool
    1016   [ +  +  +  +  :     133179 :     bool validForFeeEstimation = !fReplacementTransaction && !bypass_limits && IsCurrentForFeeEstimation() && m_pool.HasNoInputsOf(tx);
                   +  + ]
    1017                 :            : 
    1018                 :            :     // Store transaction in memory
    1019                 :     133179 :     m_pool.addUnchecked(*entry, setAncestors, validForFeeEstimation);
    1020                 :            : 
    1021                 :            :     // trim mempool and check if tx was trimmed
    1022         [ +  + ]:     133179 :     if (!bypass_limits) {
    1023   [ +  -  +  -  :     240764 :         LimitMempoolSize(m_pool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, std::chrono::hours{gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)});
             +  -  +  - ]
    1024         [ -  + ]:     120382 :         if (!m_pool.exists(hash))
    1025   [ -  -  -  - ]:     133179 :             return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool full");
    1026                 :            :     }
    1027                 :            :     return true;
    1028                 :            : }
    1029                 :            : 
    1030                 :     246232 : bool MemPoolAccept::AcceptSingleTransaction(const CTransactionRef& ptx, ATMPArgs& args)
    1031                 :            : {
    1032                 :     246232 :     AssertLockHeld(cs_main);
    1033                 :     492464 :     LOCK(m_pool.cs); // mempool "read lock" (held through GetMainSignals().TransactionAddedToMempool())
    1034                 :            : 
    1035         [ +  - ]:     492464 :     Workspace workspace(ptx);
    1036                 :            : 
    1037   [ +  -  +  + ]:     246232 :     if (!PreChecks(args, workspace)) return false;
    1038                 :            : 
    1039                 :            :     // Only compute the precomputed transaction data if we need to verify
    1040                 :            :     // scripts (ie, other policy checks pass). We perform the inexpensive
    1041                 :            :     // checks first and avoid hashing and signature verification unless those
    1042                 :            :     // checks pass, to mitigate CPU exhaustion denial-of-service attacks.
    1043                 :     486291 :     PrecomputedTransactionData txdata;
    1044                 :            : 
    1045   [ +  -  +  + ]:     240059 :     if (!PolicyScriptChecks(args, workspace, txdata)) return false;
    1046                 :            : 
    1047   [ +  -  +  - ]:     237903 :     if (!ConsensusScriptChecks(args, workspace, txdata)) return false;
    1048                 :            : 
    1049                 :            :     // Tx was accepted, but not added
    1050         [ +  + ]:     237903 :     if (args.m_test_accept) return true;
    1051                 :            : 
    1052   [ +  -  +  - ]:     133179 :     if (!Finalize(args, workspace)) return false;
    1053                 :            : 
    1054   [ +  -  +  - ]:     133179 :     GetMainSignals().TransactionAddedToMempool(ptx, m_pool.GetAndIncrementSequence());
    1055                 :            : 
    1056                 :            :     return true;
    1057                 :            : }
    1058                 :            : 
    1059                 :            : } // anon namespace
    1060                 :            : 
    1061                 :            : /** (try to) add transaction to memory pool with a specified acceptance time **/
    1062                 :     246232 : static bool AcceptToMemoryPoolWithTime(const CChainParams& chainparams, CTxMemPool& pool, TxValidationState &state, const CTransactionRef &tx,
    1063                 :            :                         int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
    1064                 :            :                         bool bypass_limits, bool test_accept, CAmount* fee_out=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
    1065                 :            : {
    1066         [ +  - ]:     246232 :     std::vector<COutPoint> coins_to_uncache;
    1067                 :     246232 :     MemPoolAccept::ATMPArgs args { chainparams, state, nAcceptTime, plTxnReplaced, bypass_limits, coins_to_uncache, test_accept, fee_out };
    1068   [ +  -  +  - ]:     246232 :     bool res = MemPoolAccept(pool).AcceptSingleTransaction(tx, args);
    1069         [ +  + ]:     246232 :     if (!res) {
    1070                 :            :         // Remove coins that were not present in the coins cache before calling ATMPW;
    1071                 :            :         // this is to prevent memory DoS in case we receive a large number of
    1072                 :            :         // invalid transactions that attempt to overrun the in-memory coins cache
    1073                 :            :         // (`CCoinsViewCache::cacheCoins`).
    1074                 :            : 
    1075         [ +  + ]:      12106 :         for (const COutPoint& hashTx : coins_to_uncache)
    1076   [ +  -  +  - ]:       3777 :             ::ChainstateActive().CoinsTip().Uncache(hashTx);
    1077                 :            :     }
    1078                 :            :     // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
    1079         [ +  - ]:     492464 :     BlockValidationState state_dummy;
    1080   [ +  -  +  - ]:     246232 :     ::ChainstateActive().FlushStateToDisk(chainparams, state_dummy, FlushStateMode::PERIODIC);
    1081                 :     492464 :     return res;
    1082                 :            : }
    1083                 :            : 
    1084                 :     246112 : bool AcceptToMemoryPool(CTxMemPool& pool, TxValidationState &state, const CTransactionRef &tx,
    1085                 :            :                         std::list<CTransactionRef>* plTxnReplaced,
    1086                 :            :                         bool bypass_limits, bool test_accept, CAmount* fee_out)
    1087                 :            : {
    1088                 :     246112 :     const CChainParams& chainparams = Params();
    1089                 :     246112 :     return AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, GetTime(), plTxnReplaced, bypass_limits, test_accept, fee_out);
    1090                 :            : }
    1091                 :            : 
    1092                 :        798 : CTransactionRef GetTransaction(const CBlockIndex* const block_index, const CTxMemPool* const mempool, const uint256& hash, const Consensus::Params& consensusParams, uint256& hashBlock)
    1093                 :            : {
    1094                 :       1596 :     LOCK(cs_main);
    1095                 :            : 
    1096         [ +  + ]:        798 :     if (block_index) {
    1097                 :         77 :         CBlock block;
    1098   [ +  -  +  - ]:         77 :         if (ReadBlockFromDisk(block, block_index, consensusParams)) {
    1099         [ +  + ]:        191 :             for (const auto& tx : block.vtx) {
    1100         [ +  + ]:        189 :                 if (tx->GetHash() == hash) {
    1101         [ +  - ]:         75 :                     hashBlock = block_index->GetBlockHash();
    1102         [ +  - ]:         75 :                     return tx;
    1103                 :            :                 }
    1104                 :            :             }
    1105                 :            :         }
    1106                 :         77 :         return nullptr;
    1107                 :            :     }
    1108         [ +  + ]:        721 :     if (mempool) {
    1109         [ +  - ]:        717 :         CTransactionRef ptx = mempool->get(hash);
    1110   [ +  +  -  + ]:        717 :         if (ptx) return ptx;
    1111                 :            :     }
    1112         [ +  + ]:          9 :     if (g_txindex) {
    1113                 :          0 :         CTransactionRef tx;
    1114   [ +  -  +  -  :          6 :         if (g_txindex->FindTx(hash, hashBlock, tx)) return tx;
                   -  + ]
    1115                 :            :     }
    1116         [ +  - ]:        798 :     return nullptr;
    1117                 :            : }
    1118                 :            : 
    1119                 :            : //////////////////////////////////////////////////////////////////////////////
    1120                 :            : //
    1121                 :            : // CBlock and CBlockIndex
    1122                 :            : //
    1123                 :            : 
    1124                 :      69750 : static bool WriteBlockToDisk(const CBlock& block, FlatFilePos& pos, const CMessageHeader::MessageStartChars& messageStart)
    1125                 :            : {
    1126                 :            :     // Open history file to append
    1127         [ -  + ]:     139500 :     CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
    1128         [ -  + ]:      69750 :     if (fileout.IsNull())
    1129         [ #  # ]:          0 :         return error("WriteBlockToDisk: OpenBlockFile failed");
    1130                 :            : 
    1131                 :            :     // Write index header
    1132                 :      69750 :     unsigned int nSize = GetSerializeSize(block, fileout.GetVersion());
    1133   [ +  -  +  - ]:      69750 :     fileout << messageStart << nSize;
    1134                 :            : 
    1135                 :            :     // Write block
    1136         [ +  - ]:      69750 :     long fileOutPos = ftell(fileout.Get());
    1137         [ -  + ]:      69750 :     if (fileOutPos < 0)
    1138         [ #  # ]:          0 :         return error("WriteBlockToDisk: ftell failed");
    1139                 :      69750 :     pos.nPos = (unsigned int)fileOutPos;
    1140         [ +  - ]:      69750 :     fileout << block;
    1141                 :            : 
    1142                 :            :     return true;
    1143                 :            : }
    1144                 :            : 
    1145                 :     120860 : bool ReadBlockFromDisk(CBlock& block, const FlatFilePos& pos, const Consensus::Params& consensusParams)
    1146                 :            : {
    1147                 :     120860 :     block.SetNull();
    1148                 :            : 
    1149                 :            :     // Open history file to read
    1150         [ +  + ]:     241720 :     CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
    1151         [ +  + ]:     120860 :     if (filein.IsNull())
    1152   [ +  -  +  - ]:        108 :         return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
    1153                 :            : 
    1154                 :            :     // Read block
    1155                 :     120752 :     try {
    1156         [ +  - ]:     120752 :         filein >> block;
    1157                 :            :     }
    1158         [ -  - ]:          0 :     catch (const std::exception& e) {
    1159   [ -  -  -  - ]:          0 :         return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
    1160                 :            :     }
    1161                 :            : 
    1162                 :            :     // Check the header
    1163   [ +  -  +  -  :     120752 :     if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
                   -  + ]
    1164   [ #  #  #  # ]:          0 :         return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
    1165                 :            : 
    1166                 :            :     // Signet only: check block solution
    1167   [ +  +  +  -  :     120752 :     if (consensusParams.signet_blocks && !CheckSignetBlockSolution(block, consensusParams)) {
                   -  + ]
    1168   [ -  -  -  -  :     120860 :         return error("ReadBlockFromDisk: Errors in block solution at %s", pos.ToString());
                   +  + ]
    1169                 :            :     }
    1170                 :            : 
    1171                 :            :     return true;
    1172                 :            : }
    1173                 :            : 
    1174                 :     120746 : bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
    1175                 :            : {
    1176                 :     120746 :     FlatFilePos blockPos;
    1177                 :     120746 :     {
    1178                 :     120746 :         LOCK(cs_main);
    1179         [ +  - ]:     120746 :         blockPos = pindex->GetBlockPos();
    1180                 :            :     }
    1181                 :            : 
    1182         [ +  + ]:     120746 :     if (!ReadBlockFromDisk(block, blockPos, consensusParams))
    1183                 :            :         return false;
    1184         [ -  + ]:     120638 :     if (block.GetHash() != pindex->GetBlockHash())
    1185         [ #  # ]:          0 :         return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
    1186         [ -  - ]:     120746 :                 pindex->ToString(), pindex->GetBlockPos().ToString());
    1187                 :            :     return true;
    1188                 :            : }
    1189                 :            : 
    1190                 :       7837 : bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const FlatFilePos& pos, const CMessageHeader::MessageStartChars& message_start)
    1191                 :            : {
    1192                 :       7837 :     FlatFilePos hpos = pos;
    1193                 :       7837 :     hpos.nPos -= 8; // Seek back 8 bytes for meta header
    1194         [ -  + ]:      15674 :     CAutoFile filein(OpenBlockFile(hpos, true), SER_DISK, CLIENT_VERSION);
    1195         [ -  + ]:       7837 :     if (filein.IsNull()) {
    1196   [ #  #  #  # ]:          0 :         return error("%s: OpenBlockFile failed for %s", __func__, pos.ToString());
    1197                 :            :     }
    1198                 :            : 
    1199                 :       7837 :     try {
    1200                 :       7837 :         CMessageHeader::MessageStartChars blk_start;
    1201                 :       7837 :         unsigned int blk_size;
    1202                 :            : 
    1203   [ +  -  +  - ]:       7837 :         filein >> blk_start >> blk_size;
    1204                 :            : 
    1205         [ -  + ]:       7837 :         if (memcmp(blk_start, message_start, CMessageHeader::MESSAGE_START_SIZE)) {
    1206   [ #  #  #  #  :          0 :             return error("%s: Block magic mismatch for %s: %s versus expected %s", __func__, pos.ToString(),
                   #  # ]
    1207         [ #  # ]:          0 :                     HexStr(blk_start),
    1208         [ #  # ]:          0 :                     HexStr(message_start));
    1209                 :            :         }
    1210                 :            : 
    1211         [ -  + ]:       7837 :         if (blk_size > MAX_SIZE) {
    1212   [ -  -  -  -  :       7837 :             return error("%s: Block data is larger than maximum deserialization size for %s: %s versus %s", __func__, pos.ToString(),
                   +  - ]
    1213                 :            :                     blk_size, MAX_SIZE);
    1214                 :            :         }
    1215                 :            : 
    1216         [ +  - ]:       7837 :         block.resize(blk_size); // Zeroing of memory is intentional here
    1217         [ +  - ]:       7837 :         filein.read((char*)block.data(), blk_size);
    1218         [ -  - ]:          0 :     } catch(const std::exception& e) {
    1219   [ -  -  -  - ]:          0 :         return error("%s: Read from block file failed: %s for %s", __func__, e.what(), pos.ToString());
    1220                 :            :     }
    1221                 :            : 
    1222                 :            :     return true;
    1223                 :            : }
    1224                 :            : 
    1225                 :       7837 : bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const CBlockIndex* pindex, const CMessageHeader::MessageStartChars& message_start)
    1226                 :            : {
    1227                 :       7837 :     FlatFilePos block_pos;
    1228                 :       7837 :     {
    1229                 :       7837 :         LOCK(cs_main);
    1230         [ +  - ]:       7837 :         block_pos = pindex->GetBlockPos();
    1231                 :            :     }
    1232                 :            : 
    1233                 :       7837 :     return ReadRawBlockFromDisk(block, block_pos, message_start);
    1234                 :            : }
    1235                 :            : 
    1236                 :     138547 : CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
    1237                 :            : {
    1238                 :     138547 :     int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
    1239                 :            :     // Force block reward to zero when right shift is undefined.
    1240         [ +  + ]:     138547 :     if (halvings >= 64)
    1241                 :            :         return 0;
    1242                 :            : 
    1243                 :     137984 :     CAmount nSubsidy = 50 * COIN;
    1244                 :            :     // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
    1245                 :     137984 :     nSubsidy >>= halvings;
    1246                 :     137984 :     return nSubsidy;
    1247                 :            : }
    1248                 :            : 
    1249                 :        728 : CoinsViews::CoinsViews(
    1250                 :            :     std::string ldb_name,
    1251                 :            :     size_t cache_size_bytes,
    1252                 :            :     bool in_memory,
    1253                 :        728 :     bool should_wipe) : m_dbview(
    1254   [ +  -  +  - ]:       1456 :                             GetDataDir() / ldb_name, cache_size_bytes, in_memory, should_wipe),
    1255   [ +  -  +  - ]:       2184 :                         m_catcherview(&m_dbview) {}
    1256                 :            : 
    1257                 :        728 : void CoinsViews::InitCache()
    1258                 :            : {
    1259                 :        728 :     m_cacheview = MakeUnique<CCoinsViewCache>(&m_catcherview);
    1260                 :        728 : }
    1261                 :            : 
    1262                 :        728 : CChainState::CChainState(CTxMemPool& mempool, BlockManager& blockman, uint256 from_snapshot_blockhash)
    1263                 :            :     : m_blockman(blockman),
    1264                 :            :       m_mempool(mempool),
    1265                 :        728 :       m_from_snapshot_blockhash(from_snapshot_blockhash) {}
    1266                 :            : 
    1267                 :        728 : void CChainState::InitCoinsDB(
    1268                 :            :     size_t cache_size_bytes,
    1269                 :            :     bool in_memory,
    1270                 :            :     bool should_wipe,
    1271                 :            :     std::string leveldb_name)
    1272                 :            : {
    1273         [ +  + ]:       1456 :     if (!m_from_snapshot_blockhash.IsNull()) {
    1274         [ +  - ]:          4 :         leveldb_name += "_" + m_from_snapshot_blockhash.ToString();
    1275                 :            :     }
    1276                 :            : 
    1277                 :       1456 :     m_coins_views = MakeUnique<CoinsViews>(
    1278                 :        728 :         leveldb_name, cache_size_bytes, in_memory, should_wipe);
    1279                 :        728 : }
    1280                 :            : 
    1281                 :        728 : void CChainState::InitCoinsCache(size_t cache_size_bytes)
    1282                 :            : {
    1283         [ -  + ]:        728 :     assert(m_coins_views != nullptr);
    1284                 :        728 :     m_coinstip_cache_size_bytes = cache_size_bytes;
    1285                 :        728 :     m_coins_views->InitCache();
    1286                 :        728 : }
    1287                 :            : 
    1288                 :            : // Note that though this is marked const, we may end up modifying `m_cached_finished_ibd`, which
    1289                 :            : // is a performance-related implementation detail. This function must be marked
    1290                 :            : // `const` so that `CValidationInterface` clients (which are given a `const CChainState*`)
    1291                 :            : // can call it.
    1292                 :            : //
    1293                 :    1565089 : bool CChainState::IsInitialBlockDownload() const
    1294                 :            : {
    1295                 :            :     // Optimization: pre-test latch before taking the lock.
    1296         [ +  + ]:    1565089 :     if (m_cached_finished_ibd.load(std::memory_order_relaxed))
    1297                 :            :         return false;
    1298                 :            : 
    1299                 :    1621504 :     LOCK(cs_main);
    1300         [ +  - ]:      56415 :     if (m_cached_finished_ibd.load(std::memory_order_relaxed))
    1301                 :            :         return false;
    1302   [ +  +  -  + ]:      56415 :     if (fImporting || fReindex)
    1303                 :       9559 :         return true;
    1304   [ +  +  +  -  :     103267 :     if (m_chain.Tip() == nullptr)
                   +  - ]
    1305                 :            :         return true;
    1306   [ +  -  +  + ]:      46852 :     if (m_chain.Tip()->nChainWork < nMinimumChainWork)
    1307                 :            :         return true;
    1308   [ +  -  +  -  :      87912 :     if (m_chain.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
                   +  + ]
    1309                 :            :         return true;
    1310         [ +  - ]:        509 :     LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
    1311                 :        509 :     m_cached_finished_ibd.store(true, std::memory_order_relaxed);
    1312                 :        509 :     return false;
    1313                 :            : }
    1314                 :            : 
    1315                 :         10 : static void AlertNotify(const std::string& strMessage)
    1316                 :            : {
    1317                 :         10 :     uiInterface.NotifyAlertChanged();
    1318                 :            : #if HAVE_SYSTEM
    1319   [ +  -  +  - ]:         10 :     std::string strCmd = gArgs.GetArg("-alertnotify", "");
    1320         [ +  + ]:         20 :     if (strCmd.empty()) return;
    1321                 :            : 
    1322                 :            :     // Alert text should be plain ascii coming from a trusted source, but to
    1323                 :            :     // be safe we first strip anything not in safeChars, then add single quotes around
    1324                 :            :     // the whole string before passing it to the shell:
    1325         [ +  - ]:          4 :     std::string singleQuote("'");
    1326         [ +  - ]:          4 :     std::string safeStatus = SanitizeString(strMessage);
    1327   [ +  -  +  - ]:          2 :     safeStatus = singleQuote+safeStatus+singleQuote;
    1328         [ +  - ]:          2 :     boost::replace_all(strCmd, "%s", safeStatus);
    1329                 :            : 
    1330         [ +  - ]:          4 :     std::thread t(runCommand, strCmd);
    1331         [ +  - ]:          2 :     t.detach(); // thread runs free
    1332                 :            : #endif
    1333                 :            : }
    1334                 :            : 
    1335                 :      73485 : static void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
    1336                 :            : {
    1337                 :      73485 :     AssertLockHeld(cs_main);
    1338                 :            :     // Before we get past initial download, we cannot reliably alert about forks
    1339                 :            :     // (we assume we don't get stuck on a fork before finishing our initial sync)
    1340         [ +  + ]:      73485 :     if (::ChainstateActive().IsInitialBlockDownload()) {
    1341                 :            :         return;
    1342                 :            :     }
    1343                 :            : 
    1344   [ +  +  +  -  :      96971 :     if (pindexBestInvalid && pindexBestInvalid->nChainWork > ::ChainActive().Tip()->nChainWork + (GetBlockProof(*::ChainActive().Tip()) * 6)) {
             +  -  +  + ]
    1345                 :         13 :         LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
    1346                 :         13 :         SetfLargeWorkInvalidChainFound(true);
    1347                 :            :     } else {
    1348                 :      68264 :         SetfLargeWorkInvalidChainFound(false);
    1349                 :            :     }
    1350                 :            : }
    1351                 :            : 
    1352                 :            : // Called both upon regular invalid block discovery *and* InvalidateBlock
    1353                 :       5589 : void static InvalidChainFound(CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
    1354                 :            : {
    1355   [ +  +  +  + ]:       5589 :     if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
    1356                 :       1525 :         pindexBestInvalid = pindexNew;
    1357   [ +  -  +  + ]:       5589 :     if (pindexBestHeader != nullptr && pindexBestHeader->GetAncestor(pindexNew->nHeight) == pindexNew) {
    1358         [ +  - ]:       5636 :         pindexBestHeader = ::ChainActive().Tip();
    1359                 :            :     }
    1360                 :            : 
    1361         [ +  - ]:      11178 :     LogPrintf("%s: invalid block=%s  height=%d  log2_work=%f  date=%s\n", __func__,
    1362                 :       5589 :       pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
    1363   [ +  -  +  - ]:       5589 :       log(pindexNew->nChainWork.getdouble())/log(2.0), FormatISO8601DateTime(pindexNew->GetBlockTime()));
    1364         [ +  - ]:       5589 :     CBlockIndex *tip = ::ChainActive().Tip();
    1365         [ -  + ]:       5589 :     assert (tip);
    1366         [ +  - ]:      11178 :     LogPrintf("%s:  current best=%s  height=%d  log2_work=%f  date=%s\n", __func__,
    1367   [ +  -  +  -  :      11178 :       tip->GetBlockHash().ToString(), ::ChainActive().Height(), log(tip->nChainWork.getdouble())/log(2.0),
                   +  - ]
    1368                 :       5589 :       FormatISO8601DateTime(tip->GetBlockTime()));
    1369                 :       5589 :     CheckForkWarningConditions();
    1370                 :       5589 : }
    1371                 :            : 
    1372                 :            : // Same as InvalidChainFound, above, except not called directly from InvalidateBlock,
    1373                 :            : // which does its own setBlockIndexCandidates manageent.
    1374                 :       2758 : void CChainState::InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) {
    1375         [ +  - ]:       2758 :     if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
    1376                 :       2758 :         pindex->nStatus |= BLOCK_FAILED_VALID;
    1377                 :       2758 :         m_blockman.m_failed_blocks.insert(pindex);
    1378                 :       2758 :         setDirtyBlockIndex.insert(pindex);
    1379                 :       2758 :         setBlockIndexCandidates.erase(pindex);
    1380                 :       2758 :         InvalidChainFound(pindex);
    1381                 :            :     }
    1382                 :       2758 : }
    1383                 :            : 
    1384                 :    5624215 : void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
    1385                 :            : {
    1386                 :            :     // mark inputs spent
    1387         [ +  + ]:    5624215 :     if (!tx.IsCoinBase()) {
    1388                 :    5519738 :         txundo.vprevout.reserve(tx.vin.size());
    1389         [ +  + ]:   13169953 :         for (const CTxIn &txin : tx.vin) {
    1390                 :    7650215 :             txundo.vprevout.emplace_back();
    1391                 :    7650215 :             bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
    1392         [ -  + ]:    7650215 :             assert(is_spent);
    1393                 :            :         }
    1394                 :            :     }
    1395                 :            :     // add outputs
    1396                 :    5624215 :     AddCoins(inputs, tx, nHeight);
    1397                 :    5624215 : }
    1398                 :            : 
    1399                 :    5166888 : void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
    1400                 :            : {
    1401         [ +  - ]:    5166888 :     CTxUndo txundo;
    1402         [ +  - ]:    5166888 :     UpdateCoins(tx, inputs, txundo, nHeight);
    1403                 :    5166888 : }
    1404                 :            : 
    1405                 :    1058392 : bool CScriptCheck::operator()() {
    1406         [ +  - ]:    1058392 :     const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
    1407                 :    1058392 :     const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
    1408         [ +  - ]:    1058392 :     return VerifyScript(scriptSig, m_tx_out.scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, m_tx_out.nValue, cacheStore, *txdata), &error);
    1409                 :            : }
    1410                 :            : 
    1411                 :     326021 : int GetSpendHeight(const CCoinsViewCache& inputs)
    1412                 :            : {
    1413                 :     326021 :     LOCK(cs_main);
    1414         [ +  - ]:     326021 :     CBlockIndex* pindexPrev = LookupBlockIndex(inputs.GetBestBlock());
    1415         [ +  - ]:     652042 :     return pindexPrev->nHeight + 1;
    1416                 :            : }
    1417                 :            : 
    1418                 :            : 
    1419                 :            : static CuckooCache::cache<uint256, SignatureCacheHasher> g_scriptExecutionCache;
    1420                 :            : static CSHA256 g_scriptExecutionCacheHasher;
    1421                 :            : 
    1422                 :       1134 : void InitScriptExecutionCache() {
    1423                 :            :     // Setup the salted hasher
    1424                 :       1134 :     uint256 nonce = GetRandHash();
    1425                 :            :     // We want the nonce to be 64 bytes long to force the hasher to process
    1426                 :            :     // this chunk, which makes later hash computations more efficient. We
    1427                 :            :     // just write our 32-byte entropy twice to fill the 64 bytes.
    1428                 :       1134 :     g_scriptExecutionCacheHasher.Write(nonce.begin(), 32);
    1429                 :       1134 :     g_scriptExecutionCacheHasher.Write(nonce.begin(), 32);
    1430                 :            :     // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
    1431                 :            :     // setup_bytes creates the minimum possible cache (2 elements).
    1432   [ +  -  +  -  :       2268 :     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);
                   -  + ]
    1433                 :       1134 :     size_t nElems = g_scriptExecutionCache.setup_bytes(nMaxCacheSize);
    1434                 :       1134 :     LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
    1435                 :       1134 :             (nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
    1436                 :       1134 : }
    1437                 :            : 
    1438                 :            : /**
    1439                 :            :  * Check whether all of this transaction's input scripts succeed.
    1440                 :            :  *
    1441                 :            :  * This involves ECDSA signature checks so can be computationally intensive. This function should
    1442                 :            :  * only be called after the cheap sanity checks in CheckTxInputs passed.
    1443                 :            :  *
    1444                 :            :  * If pvChecks is not nullptr, script checks are pushed onto it instead of being performed inline. Any
    1445                 :            :  * script checks which are not necessary (eg due to script execution cache hits) are, obviously,
    1446                 :            :  * not pushed onto pvChecks/run.
    1447                 :            :  *
    1448                 :            :  * Setting cacheSigStore/cacheFullScriptStore to false will remove elements from the corresponding cache
    1449                 :            :  * which are matched. This is useful for checking blocks where we will likely never need the cache
    1450                 :            :  * entry again.
    1451                 :            :  *
    1452                 :            :  * Note that we may set state.reason to NOT_STANDARD for extra soft-fork flags in flags, block-checking
    1453                 :            :  * callers should probably reset it to CONSENSUS in such cases.
    1454                 :            :  *
    1455                 :            :  * Non-static (and re-declared) in src/test/txvalidationcache_tests.cpp
    1456                 :            :  */
    1457                 :    1058106 : bool CheckInputScripts(const CTransaction& tx, TxValidationState &state, const CCoinsViewCache &inputs, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
    1458                 :            : {
    1459         [ +  - ]:    1058106 :     if (tx.IsCoinBase()) return true;
    1460                 :            : 
    1461         [ +  + ]:    1058106 :     if (pvChecks) {
    1462                 :     443815 :         pvChecks->reserve(tx.vin.size());
    1463                 :            :     }
    1464                 :            : 
    1465                 :            :     // First check if script executions have been cached with the same
    1466                 :            :     // flags. Note that this assumes that the inputs provided are
    1467                 :            :     // correct (ie that the transaction hash which is in tx's prevouts
    1468                 :            :     // properly commits to the scriptPubKey in the inputs view of that
    1469                 :            :     // transaction).
    1470                 :    1058106 :     uint256 hashCacheEntry;
    1471                 :    1058106 :     CSHA256 hasher = g_scriptExecutionCacheHasher;
    1472                 :    1058106 :     hasher.Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
    1473                 :    1058106 :     AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
    1474         [ +  + ]:    1058106 :     if (g_scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
    1475                 :            :         return true;
    1476                 :            :     }
    1477                 :            : 
    1478         [ +  + ]:     622430 :     if (!txdata.m_spent_outputs_ready) {
    1479         [ +  - ]:     614474 :         std::vector<CTxOut> spent_outputs;
    1480         [ +  - ]:     307237 :         spent_outputs.reserve(tx.vin.size());
    1481                 :            : 
    1482         [ +  + ]:     913665 :         for (const auto& txin : tx.vin) {
    1483                 :     606428 :             const COutPoint& prevout = txin.prevout;
    1484         [ +  - ]:     606428 :             const Coin& coin = inputs.AccessCoin(prevout);
    1485         [ -  + ]:     606428 :             assert(!coin.IsSpent());
    1486         [ +  - ]:     606428 :             spent_outputs.emplace_back(coin.out);
    1487                 :            :         }
    1488         [ +  - ]:     307237 :         txdata.Init(tx, std::move(spent_outputs));
    1489                 :            :     }
    1490         [ -  + ]:     622430 :     assert(txdata.m_spent_outputs.size() == tx.vin.size());
    1491                 :            : 
    1492         [ +  + ]:    1605599 :     for (unsigned int i = 0; i < tx.vin.size(); i++) {
    1493                 :            : 
    1494                 :            :         // We very carefully only pass in things to CScriptCheck which
    1495                 :            :         // are clearly committed to by tx' witness hash. This provides
    1496                 :            :         // a sanity check that our caching is not introducing consensus
    1497                 :            :         // failures through additional data in, eg, the coins being
    1498                 :            :         // spent being checked as a part of CScriptCheck.
    1499                 :            : 
    1500                 :            :         // Verify signature
    1501                 :    2034444 :         CScriptCheck check(txdata.m_spent_outputs[i], tx, i, flags, cacheSigStore, &txdata);
    1502         [ +  + ]:    1051275 :         if (pvChecks) {
    1503         [ +  - ]:     176305 :             pvChecks->push_back(CScriptCheck());
    1504                 :     176305 :             check.swap(pvChecks->back());
    1505   [ +  -  +  + ]:     874970 :         } else if (!check()) {
    1506         [ +  + ]:      68106 :             if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
    1507                 :            :                 // Check whether the failure was caused by a
    1508                 :            :                 // non-mandatory script verification check, such as
    1509                 :            :                 // non-standard DER encodings or non-null dummy
    1510                 :            :                 // arguments; if so, ensure we return NOT_STANDARD
    1511                 :            :                 // instead of CONSENSUS to avoid downstream users
    1512                 :            :                 // splitting the network between upgraded and
    1513                 :            :                 // non-upgraded nodes by banning CONSENSUS-failing
    1514                 :            :                 // data providers.
    1515                 :      68104 :                 CScriptCheck check2(txdata.m_spent_outputs[i], tx, i,
    1516                 :      68104 :                         flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
    1517   [ +  -  +  + ]:      68104 :                 if (check2())
    1518   [ +  -  +  -  :      51512 :                     return state.Invalid(TxValidationResult::TX_NOT_STANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
             +  -  +  - ]
    1519                 :            :             }
    1520                 :            :             // MANDATORY flag failures correspond to
    1521                 :            :             // TxValidationResult::TX_CONSENSUS. Because CONSENSUS
    1522                 :            :             // failures are the most serious case of validation
    1523                 :            :             // failures, we may need to consider using
    1524                 :            :             // RECENT_CONSENSUS_CHANGE for any script failure that
    1525                 :            :             // could be due to non-upgraded nodes which we may want to
    1526                 :            :             // support, to avoid splitting the network (but this
    1527                 :            :             // depends on the details of how net_processing handles
    1528                 :            :             // such errors).
    1529   [ +  -  +  -  :      84700 :             return state.Invalid(TxValidationResult::TX_CONSENSUS, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
             +  -  +  - ]
    1530                 :            :         }
    1531                 :            :     }
    1532                 :            : 
    1533         [ +  + ]:     554324 :     if (cacheFullScriptStore && !pvChecks) {
    1534                 :            :         // We executed all of the provided scripts, and were told to
    1535                 :            :         // cache the result. Do so now.
    1536                 :     184076 :         g_scriptExecutionCache.insert(hashCacheEntry);
    1537                 :            :     }
    1538                 :            : 
    1539                 :            :     return true;
    1540                 :            : }
    1541                 :            : 
    1542                 :      67919 : static bool UndoWriteToDisk(const CBlockUndo& blockundo, FlatFilePos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
    1543                 :            : {
    1544                 :            :     // Open history file to append
    1545         [ -  + ]:     135838 :     CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
    1546         [ -  + ]:      67919 :     if (fileout.IsNull())
    1547         [ #  # ]:          0 :         return error("%s: OpenUndoFile failed", __func__);
    1548                 :            : 
    1549                 :            :     // Write index header
    1550         [ +  - ]:      67919 :     unsigned int nSize = GetSerializeSize(blockundo, fileout.GetVersion());
    1551   [ +  -  +  - ]:      67919 :     fileout << messageStart << nSize;
    1552                 :            : 
    1553                 :            :     // Write undo data
    1554         [ +  - ]:      67919 :     long fileOutPos = ftell(fileout.Get());
    1555         [ -  + ]:      67919 :     if (fileOutPos < 0)
    1556         [ #  # ]:          0 :         return error("%s: ftell failed", __func__);
    1557                 :      67919 :     pos.nPos = (unsigned int)fileOutPos;
    1558         [ +  - ]:      67919 :     fileout << blockundo;
    1559                 :            : 
    1560                 :            :     // calculate & write checksum
    1561         [ +  - ]:      67919 :     CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
    1562         [ +  - ]:      67919 :     hasher << hashBlock;
    1563         [ +  - ]:      67919 :     hasher << blockundo;
    1564   [ +  -  +  - ]:      67919 :     fileout << hasher.GetHash();
    1565                 :            : 
    1566                 :            :     return true;
    1567                 :            : }
    1568                 :            : 
    1569                 :      16515 : bool UndoReadFromDisk(CBlockUndo& blockundo, const CBlockIndex* pindex)
    1570                 :            : {
    1571                 :      16515 :     FlatFilePos pos = pindex->GetUndoPos();
    1572         [ -  + ]:      16515 :     if (pos.IsNull()) {
    1573                 :          0 :         return error("%s: no undo data available", __func__);
    1574                 :            :     }
    1575                 :            : 
    1576                 :            :     // Open history file to read
    1577         [ +  + ]:      33030 :     CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
    1578         [ +  + ]:      16515 :     if (filein.IsNull())
    1579         [ +  - ]:          1 :         return error("%s: OpenUndoFile failed", __func__);
    1580                 :            : 
    1581                 :            :     // Read block
    1582                 :      16514 :     uint256 hashChecksum;
    1583         [ +  - ]:      16514 :     CHashVerifier<CAutoFile> verifier(&filein); // We need a CHashVerifier as reserializing may lose data
    1584                 :      16514 :     try {
    1585         [ +  - ]:      16514 :         verifier << pindex->pprev->GetBlockHash();
    1586         [ +  + ]:      16514 :         verifier >> blockundo;
    1587         [ +  - ]:      16513 :         filein >> hashChecksum;
    1588                 :            :     }
    1589         [ -  + ]:          2 :     catch (const std::exception& e) {
    1590         [ +  - ]:          1 :         return error("%s: Deserialize or I/O error - %s", __func__, e.what());
    1591                 :            :     }
    1592                 :            : 
    1593                 :            :     // Verify checksum
    1594   [ +  -  -  + ]:      16513 :     if (hashChecksum != verifier.GetHash())
    1595         [ #  # ]:          0 :         return error("%s: Checksum mismatch", __func__);
    1596                 :            : 
    1597                 :            :     return true;
    1598                 :            : }
    1599                 :            : 
    1600                 :            : /** Abort with a message */
    1601                 :          0 : static bool AbortNode(const std::string& strMessage, bilingual_str user_message = bilingual_str())
    1602                 :            : {
    1603   [ +  -  +  - ]:          3 :     SetMiscWarning(Untranslated(strMessage));
    1604                 :          1 :     LogPrintf("*** %s\n", strMessage);
    1605         [ +  - ]:          1 :     if (user_message.empty()) {
    1606                 :          1 :         user_message = _("A fatal internal error occurred, see debug.log for details");
    1607                 :            :     }
    1608                 :          1 :     AbortError(user_message);
    1609                 :          1 :     StartShutdown();
    1610                 :          1 :     return false;
    1611                 :            : }
    1612                 :            : 
    1613         [ -  - ]:      70726 : static bool AbortNode(BlockValidationState& state, const std::string& strMessage, const bilingual_str& userMessage = bilingual_str())
    1614                 :            : {
    1615         [ +  - ]:          1 :     AbortNode(strMessage, userMessage);
    1616         [ +  - ]:          2 :     return state.Error(strMessage);
    1617                 :            : }
    1618                 :            : 
    1619                 :            : /**
    1620                 :            :  * Restore the UTXO in a Coin at a given COutPoint
    1621                 :            :  * @param undo The Coin to be restored.
    1622                 :            :  * @param view The coins view to which to apply the changes.
    1623                 :            :  * @param out The out point that corresponds to the tx input.
    1624                 :            :  * @return A DisconnectResult as an int
    1625                 :            :  */
    1626                 :      97134 : int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
    1627                 :            : {
    1628                 :      97134 :     bool fClean = true;
    1629                 :            : 
    1630         [ -  + ]:      97134 :     if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
    1631                 :            : 
    1632         [ -  + ]:      97134 :     if (undo.nHeight == 0) {
    1633                 :            :         // Missing undo metadata (height and coinbase). Older versions included this
    1634                 :            :         // information only in undo records for the last spend of a transactions'
    1635                 :            :         // outputs. This implies that it must be present for some other output of the same tx.
    1636                 :          0 :         const Coin& alternate = AccessByTxid(view, out.hash);
    1637         [ #  # ]:          0 :         if (!alternate.IsSpent()) {
    1638                 :          0 :             undo.nHeight = alternate.nHeight;
    1639                 :          0 :             undo.fCoinBase = alternate.fCoinBase;
    1640                 :            :         } else {
    1641                 :            :             return DISCONNECT_FAILED; // adding output for transaction without known metadata
    1642                 :            :         }
    1643                 :            :     }
    1644                 :            :     // If the coin already exists as an unspent coin in the cache, then the
    1645                 :            :     // possible_overwrite parameter to AddCoin must be set to true. We have
    1646                 :            :     // already checked whether an unspent coin exists above using HaveCoin, so
    1647                 :            :     // we don't need to guess. When fClean is false, an unspent coin already
    1648                 :            :     // existed and it is an overwrite.
    1649                 :      97134 :     view.AddCoin(out, std::move(undo), !fClean);
    1650                 :            : 
    1651         [ -  + ]:      97134 :     return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
    1652                 :            : }
    1653                 :            : 
    1654                 :            : /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
    1655                 :            :  *  When FAILED is returned, view is left in an indeterminate state. */
    1656                 :       9355 : DisconnectResult CChainState::DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
    1657                 :            : {
    1658                 :       9355 :     bool fClean = true;
    1659                 :            : 
    1660         [ +  - ]:      18710 :     CBlockUndo blockUndo;
    1661   [ +  -  +  + ]:       9355 :     if (!UndoReadFromDisk(blockUndo, pindex)) {
    1662         [ +  - ]:          1 :         error("DisconnectBlock(): failure reading undo data");
    1663                 :            :         return DISCONNECT_FAILED;
    1664                 :            :     }
    1665                 :            : 
    1666         [ -  + ]:       9354 :     if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
    1667         [ #  # ]:          0 :         error("DisconnectBlock(): block and undo data inconsistent");
    1668                 :            :         return DISCONNECT_FAILED;
    1669                 :            :     }
    1670                 :            : 
    1671                 :            :     // undo transactions in reverse order
    1672         [ +  + ]:      64722 :     for (int i = block.vtx.size() - 1; i >= 0; i--) {
    1673                 :      55368 :         const CTransaction &tx = *(block.vtx[i]);
    1674                 :      55368 :         uint256 hash = tx.GetHash();
    1675                 :      55368 :         bool is_coinbase = tx.IsCoinBase();
    1676                 :            : 
    1677                 :            :         // Check that all outputs are available and match the outputs in the block itself
    1678                 :            :         // exactly.
    1679         [ +  + ]:     210677 :         for (size_t o = 0; o < tx.vout.size(); o++) {
    1680         [ +  + ]:     155309 :             if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
    1681                 :     138493 :                 COutPoint out(hash, o);
    1682                 :     293802 :                 Coin coin;
    1683         [ +  - ]:     138493 :                 bool is_spent = view.SpendCoin(out, &coin);
    1684   [ +  -  +  -  :     138493 :                 if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
             +  -  -  + ]
    1685                 :            :                     fClean = false; // transaction output mismatch
    1686                 :            :                 }
    1687                 :            :             }
    1688                 :            :         }
    1689                 :            : 
    1690                 :            :         // restore inputs
    1691         [ +  + ]:      55368 :         if (i > 0) { // not coinbases
    1692         [ -  + ]:      46014 :             CTxUndo &txundo = blockUndo.vtxundo[i-1];
    1693         [ -  + ]:      46014 :             if (txundo.vprevout.size() != tx.vin.size()) {
    1694         [ #  # ]:          0 :                 error("DisconnectBlock(): transaction and undo data inconsistent");
    1695                 :            :                 return DISCONNECT_FAILED;
    1696                 :            :             }
    1697         [ +  + ]:     141427 :             for (unsigned int j = tx.vin.size(); j-- > 0;) {
    1698         [ +  - ]:      95413 :                 const COutPoint &out = tx.vin[j].prevout;
    1699         [ +  - ]:      95413 :                 int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
    1700         [ +  - ]:      95413 :                 if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
    1701                 :      95413 :                 fClean = fClean && res != DISCONNECT_UNCLEAN;
    1702                 :            :             }
    1703                 :            :             // At this point, all of txundo.vprevout should have been moved out.
    1704                 :            :         }
    1705                 :            :     }
    1706                 :            : 
    1707                 :            :     // move best block pointer to prevout block
    1708         [ +  - ]:       9354 :     view.SetBestBlock(pindex->pprev->GetBlockHash());
    1709                 :            : 
    1710         [ -  + ]:       9354 :     return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
    1711                 :            : }
    1712                 :            : 
    1713                 :       1824 : static void FlushUndoFile(int block_file, bool finalize = false)
    1714                 :            : {
    1715                 :       1824 :     FlatFilePos undo_pos_old(block_file, vinfoBlockFile[block_file].nUndoSize);
    1716   [ +  -  -  + ]:       1824 :     if (!UndoFileSeq().Flush(undo_pos_old, finalize)) {
    1717   [ #  #  #  # ]:          0 :         AbortNode("Flushing undo file to disk failed. This is likely the result of an I/O error.");
    1718                 :            :     }
    1719                 :       1824 : }
    1720                 :            : 
    1721                 :       1824 : static void FlushBlockFile(bool fFinalize = false, bool finalize_undo = false)
    1722                 :            : {
    1723                 :       1824 :     LOCK(cs_LastBlockFile);
    1724         [ +  - ]:       1824 :     FlatFilePos block_pos_old(nLastBlockFile, vinfoBlockFile[nLastBlockFile].nSize);
    1725   [ +  -  +  -  :       1824 :     if (!BlockFileSeq().Flush(block_pos_old, fFinalize)) {
                   -  + ]
    1726   [ #  #  #  # ]:          0 :         AbortNode("Flushing block file to disk failed. This is likely the result of an I/O error.");
    1727                 :            :     }
    1728                 :            :     // we do not always flush the undo file, as the chain tip may be lagging behind the incoming blocks,
    1729                 :            :     // e.g. during IBD or a sync after a node going offline
    1730   [ +  -  +  - ]:       1824 :     if (!fFinalize || finalize_undo) FlushUndoFile(nLastBlockFile, finalize_undo);
    1731                 :       1824 : }
    1732                 :            : 
    1733                 :            : static bool FindUndoPos(BlockValidationState &state, int nFile, FlatFilePos &pos, unsigned int nAddSize);
    1734                 :            : 
    1735                 :      70726 : static bool WriteUndoDataForBlock(const CBlockUndo& blockundo, BlockValidationState& state, CBlockIndex* pindex, const CChainParams& chainparams)
    1736                 :            : {
    1737                 :            :     // Write undo information to disk
    1738         [ +  + ]:      70726 :     if (pindex->GetUndoPos().IsNull()) {
    1739                 :      67919 :         FlatFilePos _pos;
    1740         [ -  + ]:      67919 :         if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, CLIENT_VERSION) + 40))
    1741                 :          0 :             return error("ConnectBlock(): FindUndoPos failed");
    1742         [ -  + ]:      67919 :         if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
    1743   [ #  #  #  # ]:          0 :             return AbortNode(state, "Failed to write undo data");
    1744                 :            :         // rev files are written in block height order, whereas blk files are written as blocks come in (often out of order)
    1745                 :            :         // we want to flush the rev (undo) file once we've written the last block, which is indicated by the last height
    1746                 :            :         // in the block file info as below; note that this does not catch the case where the undo writes are keeping up
    1747                 :            :         // with the block writes (usually when a synced up node is getting newly mined blocks) -- this case is caught in
    1748                 :            :         // the FindBlockPos function
    1749   [ -  +  -  - ]:      67919 :         if (_pos.nFile < nLastBlockFile && static_cast<uint32_t>(pindex->nHeight) == vinfoBlockFile[_pos.nFile].nHeightLast) {
    1750                 :          0 :             FlushUndoFile(_pos.nFile, true);
    1751                 :            :         }
    1752                 :            : 
    1753                 :            :         // update nUndoPos in block index
    1754                 :      67919 :         pindex->nUndoPos = _pos.nPos;
    1755                 :      67919 :         pindex->nStatus |= BLOCK_HAVE_UNDO;
    1756                 :      67919 :         setDirtyBlockIndex.insert(pindex);
    1757                 :            :     }
    1758                 :            : 
    1759                 :            :     return true;
    1760                 :            : }
    1761                 :            : 
    1762                 :            : static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
    1763                 :            : 
    1764                 :        841 : void ThreadScriptCheck(int worker_num) {
    1765         [ +  - ]:        841 :     util::ThreadRename(strprintf("scriptch.%i", worker_num));
    1766                 :        841 :     scriptcheckqueue.Thread();
    1767                 :          0 : }
    1768                 :            : 
    1769                 :            : VersionBitsCache versionbitscache GUARDED_BY(cs_main);
    1770                 :            : 
    1771                 :      56557 : int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
    1772                 :            : {
    1773                 :     113114 :     LOCK(cs_main);
    1774                 :      56557 :     int32_t nVersion = VERSIONBITS_TOP_BITS;
    1775                 :            : 
    1776         [ +  + ]:     169671 :     for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
    1777         [ +  - ]:     113114 :         ThresholdState state = VersionBitsState(pindexPrev, params, static_cast<Consensus::DeploymentPos>(i), versionbitscache);
    1778         [ +  + ]:     113114 :         if (state == ThresholdState::LOCKED_IN || state == ThresholdState::STARTED) {
    1779         [ +  - ]:      44815 :             nVersion |= VersionBitsMask(params, static_cast<Consensus::DeploymentPos>(i));
    1780                 :            :         }
    1781                 :            :     }
    1782                 :            : 
    1783         [ +  - ]:     113114 :     return nVersion;
    1784                 :            : }
    1785                 :            : 
    1786                 :            : /**
    1787                 :            :  * Threshold condition checker that triggers when unknown versionbits are seen on the network.
    1788                 :            :  */
    1789                 :            : class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
    1790                 :            : {
    1791                 :            : private:
    1792                 :            :     int bit;
    1793                 :            : 
    1794                 :            : public:
    1795                 :    2056303 :     explicit WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
    1796                 :            : 
    1797                 :    2056303 :     int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
    1798                 :    2056303 :     int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
    1799                 :    2056303 :     int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; }
    1800                 :    2056303 :     int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; }
    1801                 :            : 
    1802                 :    1216944 :     bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
    1803                 :            :     {
    1804                 :    2433888 :         return pindex->nHeight >= params.MinBIP9WarningHeight &&
    1805         [ +  + ]:    1216944 :                ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
    1806   [ +  -  +  + ]:    2237703 :                ((pindex->nVersion >> bit) & 1) != 0 &&
    1807         [ +  + ]:      17715 :                ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
    1808                 :            :     }
    1809                 :            : };
    1810                 :            : 
    1811                 :            : static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS] GUARDED_BY(cs_main);
    1812                 :            : 
    1813                 :            : // 0.13.0 was shipped with a segwit deployment defined for testnet, but not for
    1814                 :            : // mainnet. We no longer need to support disabling the segwit deployment
    1815                 :            : // except for testing purposes, due to limitations of the functional test
    1816                 :            : // environment. See test/functional/p2p-segwit.py.
    1817                 :     338132 : static bool IsScriptWitnessEnabled(const Consensus::Params& params)
    1818                 :            : {
    1819                 :     338132 :     return params.SegwitHeight != std::numeric_limits<int>::max();
    1820                 :            : }
    1821                 :            : 
    1822                 :     338132 : static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& consensusparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
    1823                 :     338132 :     AssertLockHeld(cs_main);
    1824                 :            : 
    1825                 :     338132 :     unsigned int flags = SCRIPT_VERIFY_NONE;
    1826                 :            : 
    1827                 :            :     // BIP16 didn't become active until Apr 1 2012 (on mainnet, and
    1828                 :            :     // retroactively applied to testnet)
    1829                 :            :     // However, only one historical block violated the P2SH rules (on both
    1830                 :            :     // mainnet and testnet), so for simplicity, always leave P2SH
    1831                 :            :     // on except for the one violating block.
    1832                 :     338132 :     if (consensusparams.BIP16Exception.IsNull() || // no bip16 exception on this chain
    1833   [ +  +  +  -  :     338132 :         pindex->phashBlock == nullptr || // this is a new candidate block, eg from TestBlockValidity()
                   +  - ]
    1834         [ +  - ]:        127 :         *pindex->phashBlock != consensusparams.BIP16Exception) // this block isn't the historical exception
    1835                 :            :     {
    1836                 :            :         flags |= SCRIPT_VERIFY_P2SH;
    1837                 :            :     }
    1838                 :            : 
    1839                 :            :     // Enforce WITNESS rules whenever P2SH is in effect (and the segwit
    1840                 :            :     // deployment is defined).
    1841   [ +  -  +  + ]:     338132 :     if (flags & SCRIPT_VERIFY_P2SH && IsScriptWitnessEnabled(consensusparams)) {
    1842                 :     337864 :         flags |= SCRIPT_VERIFY_WITNESS;
    1843                 :            :     }
    1844                 :            : 
    1845                 :            :     // Start enforcing the DERSIG (BIP66) rule
    1846         [ +  + ]:     338132 :     if (pindex->nHeight >= consensusparams.BIP66Height) {
    1847                 :     227858 :         flags |= SCRIPT_VERIFY_DERSIG;
    1848                 :            :     }
    1849                 :            : 
    1850                 :            :     // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
    1851         [ +  + ]:     338132 :     if (pindex->nHeight >= consensusparams.BIP65Height) {
    1852                 :     225397 :         flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
    1853                 :            :     }
    1854                 :            : 
    1855                 :            :     // Start enforcing BIP112 (CHECKSEQUENCEVERIFY)
    1856         [ +  + ]:     338132 :     if (pindex->nHeight >= consensusparams.CSVHeight) {
    1857                 :     250992 :         flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
    1858                 :            :     }
    1859                 :            : 
    1860                 :            :     // Start enforcing Taproot using versionbits logic.
    1861         [ +  + ]:     338132 :     if (VersionBitsState(pindex->pprev, consensusparams, Consensus::DEPLOYMENT_TAPROOT, versionbitscache) == ThresholdState::ACTIVE) {
    1862                 :     335031 :         flags |= SCRIPT_VERIFY_TAPROOT;
    1863                 :            :     }
    1864                 :            : 
    1865                 :            :     // Start enforcing BIP147 NULLDUMMY (activated simultaneously with segwit)
    1866         [ +  + ]:     338132 :     if (IsWitnessEnabled(pindex->pprev, consensusparams)) {
    1867                 :     332897 :         flags |= SCRIPT_VERIFY_NULLDUMMY;
    1868                 :            :     }
    1869                 :            : 
    1870                 :     338132 :     return flags;
    1871                 :            : }
    1872                 :            : 
    1873                 :            : 
    1874                 :            : 
    1875                 :            : static int64_t nTimeCheck = 0;
    1876                 :            : static int64_t nTimeForks = 0;
    1877                 :            : static int64_t nTimeVerify = 0;
    1878                 :            : static int64_t nTimeConnect = 0;
    1879                 :            : static int64_t nTimeIndex = 0;
    1880                 :            : static int64_t nTimeCallbacks = 0;
    1881                 :            : static int64_t nTimeTotal = 0;
    1882                 :            : static int64_t nBlocksTotal = 0;
    1883                 :            : 
    1884                 :            : /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
    1885                 :            :  *  Validity checks that depend on the UTXO set are also done; ConnectBlock()
    1886                 :            :  *  can fail if those validity checks fail (among other reasons). */
    1887                 :     100566 : bool CChainState::ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
    1888                 :            :                   CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck)
    1889                 :            : {
    1890         [ -  + ]:     100566 :     AssertLockHeld(cs_main);
    1891         [ -  + ]:     100566 :     assert(pindex);
    1892         [ -  + ]:     100566 :     assert(*pindex->phashBlock == block.GetHash());
    1893                 :     100566 :     int64_t nTimeStart = GetTimeMicros();
    1894                 :            : 
    1895                 :            :     // Check it again in case a previous version let a bad block in
    1896                 :            :     // NOTE: We don't currently (re-)invoke ContextualCheckBlock() or
    1897                 :            :     // ContextualCheckBlockHeader() here. This means that if we add a new
    1898                 :            :     // consensus rule that is enforced in one of those two functions, then we
    1899                 :            :     // may have let in a block that violates the rule prior to updating the
    1900                 :            :     // software, and we would NOT be enforcing the rule here. Fully solving
    1901                 :            :     // upgrade from one software version to the next after a consensus rule
    1902                 :            :     // change is potentially tricky and issue-specific (see RewindBlockIndex()
    1903                 :            :     // for one general approach that was used for BIP 141 deployment).
    1904                 :            :     // Also, currently the rule against blocks more than 2 hours in the future
    1905                 :            :     // is enforced in ContextualCheckBlockHeader(); we wouldn't want to
    1906                 :            :     // re-enforce that rule here (at least until we make it impossible for
    1907                 :            :     // GetAdjustedTime() to go backward).
    1908         [ -  + ]:     100566 :     if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck)) {
    1909         [ #  # ]:          0 :         if (state.GetResult() == BlockValidationResult::BLOCK_MUTATED) {
    1910                 :            :             // We don't write down blocks to disk if they may have been
    1911                 :            :             // corrupted, so this should be impossible unless we're having hardware
    1912                 :            :             // problems.
    1913   [ #  #  #  # ]:          0 :             return AbortNode(state, "Corrupt block found indicating potential hardware failure; shutting down");
    1914                 :            :         }
    1915         [ -  - ]:     100566 :         return error("%s: Consensus::CheckBlock: %s", __func__, state.ToString());
    1916                 :            :     }
    1917                 :            : 
    1918                 :            :     // verify that the view's current state corresponds to the previous block
    1919         [ +  + ]:     100902 :     uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
    1920         [ -  + ]:     100566 :     assert(hashPrevBlock == view.GetBestBlock());
    1921                 :            : 
    1922                 :     100566 :     nBlocksTotal++;
    1923                 :            : 
    1924                 :            :     // Special case for the genesis block, skipping connection of its transactions
    1925                 :            :     // (its coinbase is unspendable)
    1926         [ +  + ]:     100566 :     if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
    1927         [ +  - ]:        336 :         if (!fJustCheck)
    1928                 :        336 :             view.SetBestBlock(pindex->GetBlockHash());
    1929                 :        336 :         return true;
    1930                 :            :     }
    1931                 :            : 
    1932                 :    3229478 :     bool fScriptChecks = true;
    1933   [ +  +  +  + ]:    3231919 :     if (!hashAssumeValid.IsNull()) {
    1934                 :            :         // We've been configured with the hash of a block which has been externally verified to have a valid history.
    1935                 :            :         // A suitable default value is included with the software and updated from time to time.  Because validity
    1936                 :            :         //  relative to a piece of software is an objective fact these defaults can be easily reviewed.
    1937                 :            :         // This setting doesn't force the selection of any particular chain but makes validating some faster by
    1938                 :            :         //  effectively caching the result of part of the verification.
    1939         [ +  + ]:       2441 :         BlockMap::const_iterator  it = m_blockman.m_block_index.find(hashAssumeValid);
    1940         [ +  + ]:       2441 :         if (it != m_blockman.m_block_index.end()) {
    1941                 :       2304 :             if (it->second->GetAncestor(pindex->nHeight) == pindex &&
    1942   [ +  +  +  - ]:       2304 :                 pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
    1943         [ +  - ]:        204 :                 pindexBestHeader->nChainWork >= nMinimumChainWork) {
    1944                 :            :                 // This block is a member of the assumed verified chain and an ancestor of the best header.
    1945                 :            :                 // Script verification is skipped when connecting blocks under the
    1946                 :            :                 // assumevalid block. Assuming the assumevalid block is valid this
    1947                 :            :                 // is safe because block merkle hashes are still computed and checked,
    1948                 :            :                 // Of course, if an assumed valid block is invalid due to false scriptSigs
    1949                 :            :                 // this optimization would allow an invalid chain to be accepted.
    1950                 :            :                 // The equivalent time check discourages hash power from extorting the network via DOS attack
    1951                 :            :                 //  into accepting an invalid block through telling users they must manually set assumevalid.
    1952                 :            :                 //  Requiring a software change or burying the invalid block, regardless of the setting, makes
    1953                 :            :                 //  it hard to hide the implication of the demand.  This also avoids having release candidates
    1954                 :            :                 //  that are hardly doing any signature verification at all in testing without having to
    1955                 :            :                 //  artificially set the default assumed verified block further back.
    1956                 :            :                 // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
    1957                 :            :                 //  least as good as the expected chain.
    1958                 :        204 :                 fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
    1959                 :            :             }
    1960                 :            :         }
    1961                 :            :     }
    1962                 :            : 
    1963                 :     100230 :     int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
    1964         [ +  - ]:     100230 :     LogPrint(BCLog::BENCH, "    - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime1 - nTimeStart), nTimeCheck * MICRO, nTimeCheck * MILLI / nBlocksTotal);
    1965                 :            : 
    1966                 :            :     // Do not allow blocks that contain transactions which 'overwrite' older transactions,
    1967                 :            :     // unless those are already completely spent.
    1968                 :            :     // If such overwrites are allowed, coinbases and transactions depending upon those
    1969                 :            :     // can be duplicated to remove the ability to spend the first instance -- even after
    1970                 :            :     // being sent to another address.
    1971                 :            :     // See BIP30, CVE-2012-1909, and http://r6.ca/blog/20120206T005236Z.html for more information.
    1972                 :            :     // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
    1973                 :            :     // already refuses previously-known transaction ids entirely.
    1974                 :            :     // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
    1975                 :            :     // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
    1976                 :            :     // two in the chain that violate it. This prevents exploiting the issue against nodes during their
    1977                 :            :     // initial block download.
    1978   [ -  +  -  - ]:     100230 :     bool fEnforceBIP30 = !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
    1979   [ -  +  -  - ]:     100230 :                            (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
    1980                 :            : 
    1981                 :            :     // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
    1982                 :            :     // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs.  But by the
    1983                 :            :     // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
    1984                 :            :     // before the first had been spent.  Since those coinbases are sufficiently buried it's no longer possible to create further
    1985                 :            :     // duplicate transactions descending from the known pairs either.
    1986                 :            :     // 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.
    1987                 :            : 
    1988                 :            :     // BIP34 requires that a block at height X (block X) has its coinbase
    1989                 :            :     // scriptSig start with a CScriptNum of X (indicated height X).  The above
    1990                 :            :     // logic of no longer requiring BIP30 once BIP34 activates is flawed in the
    1991                 :            :     // case that there is a block X before the BIP34 height of 227,931 which has
    1992                 :            :     // an indicated height Y where Y is greater than X.  The coinbase for block
    1993                 :            :     // X would also be a valid coinbase for block Y, which could be a BIP30
    1994                 :            :     // violation.  An exhaustive search of all mainnet coinbases before the
    1995                 :            :     // BIP34 height which have an indicated height greater than the block height
    1996                 :            :     // reveals many occurrences. The 3 lowest indicated heights found are
    1997                 :            :     // 209,921, 490,897, and 1,983,702 and thus coinbases for blocks at these 3
    1998                 :            :     // heights would be the first opportunity for BIP30 to be violated.
    1999                 :            : 
    2000                 :            :     // The search reveals a great many blocks which have an indicated height
    2001                 :            :     // greater than 1,983,702, so we simply remove the optimization to skip
    2002                 :            :     // BIP30 checking for blocks at height 1,983,702 or higher.  Before we reach
    2003                 :            :     // that block in another 25 years or so, we should take advantage of a
    2004                 :            :     // future consensus change to do a new and improved version of BIP34 that
    2005                 :            :     // will actually prevent ever creating any duplicate coinbases in the
    2006                 :            :     // future.
    2007                 :     100230 :     static constexpr int BIP34_IMPLIES_BIP30_LIMIT = 1983702;
    2008                 :            : 
    2009                 :            :     // There is no potential to create a duplicate coinbase at block 209,921
    2010                 :            :     // because this is still before the BIP34 height and so explicit BIP30
    2011                 :            :     // checking is still active.
    2012                 :            : 
    2013                 :            :     // The final case is block 176,684 which has an indicated height of
    2014                 :            :     // 490,897. Unfortunately, this issue was not discovered until about 2 weeks
    2015                 :            :     // before block 490,897 so there was not much opportunity to address this
    2016                 :            :     // case other than to carefully analyze it and determine it would not be a
    2017                 :            :     // problem. Block 490,897 was, in fact, mined with a different coinbase than
    2018                 :            :     // block 176,684, but it is important to note that even if it hadn't been or
    2019                 :            :     // is remined on an alternate fork with a duplicate coinbase, we would still
    2020                 :            :     // not run into a BIP30 violation.  This is because the coinbase for 176,684
    2021                 :            :     // is spent in block 185,956 in transaction
    2022                 :            :     // d4f7fbbf92f4a3014a230b2dc70b8058d02eb36ac06b4a0736d9d60eaa9e8781.  This
    2023                 :            :     // spending transaction can't be duplicated because it also spends coinbase
    2024                 :            :     // 0328dd85c331237f18e781d692c92de57649529bd5edf1d01036daea32ffde29.  This
    2025                 :            :     // coinbase has an indicated height of over 4.2 billion, and wouldn't be
    2026                 :            :     // duplicatable until that height, and it's currently impossible to create a
    2027                 :            :     // chain that long. Nevertheless we may wish to consider a future soft fork
    2028                 :            :     // which retroactively prevents block 490,897 from creating a duplicate
    2029                 :            :     // coinbase. The two historical BIP30 violations often provide a confusing
    2030                 :            :     // edge case when manipulating the UTXO and it would be simpler not to have
    2031                 :            :     // another edge case to deal with.
    2032                 :            : 
    2033                 :            :     // testnet3 has no blocks before the BIP34 height with indicated heights
    2034                 :            :     // post BIP34 before approximately height 486,000,000 and presumably will
    2035                 :            :     // be reset before it reaches block 1,983,702 and starts doing unnecessary
    2036                 :            :     // BIP30 checking again.
    2037         [ -  + ]:     100230 :     assert(pindex->pprev);
    2038                 :     100230 :     CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
    2039                 :            :     //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
    2040   [ +  -  +  +  :     100230 :     fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
                   -  + ]
    2041                 :            : 
    2042                 :            :     // TODO: Remove BIP30 checking from block height 1,983,702 on, once we have a
    2043                 :            :     // consensus change that ensures coinbases at those heights can not
    2044                 :            :     // duplicate earlier coinbases.
    2045         [ #  # ]:          0 :     if (fEnforceBIP30 || pindex->nHeight >= BIP34_IMPLIES_BIP30_LIMIT) {
    2046         [ +  + ]:     522543 :         for (const auto& tx : block.vtx) {
    2047         [ +  + ]:    1685677 :             for (size_t o = 0; o < tx->vout.size(); o++) {
    2048         [ +  + ]:    1263364 :                 if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
    2049                 :          1 :                     LogPrintf("ERROR: ConnectBlock(): tried to overwrite transaction\n");
    2050   [ +  -  +  - ]:          1 :                     return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-BIP30");
    2051                 :            :                 }
    2052                 :            :             }
    2053                 :            :         }
    2054                 :            :     }
    2055                 :            : 
    2056                 :            :     // Start enforcing BIP68 (sequence locks)
    2057                 :     100229 :     int nLockTimeFlags = 0;
    2058         [ +  + ]:     100229 :     if (pindex->nHeight >= chainparams.GetConsensus().CSVHeight) {
    2059                 :      33235 :         nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
    2060                 :            :     }
    2061                 :            : 
    2062                 :            :     // Get the script flags for this block
    2063                 :     100229 :     unsigned int flags = GetBlockScriptFlags(pindex, chainparams.GetConsensus());
    2064                 :            : 
    2065                 :     100229 :     int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
    2066         [ +  - ]:     100229 :     LogPrint(BCLog::BENCH, "    - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime2 - nTime1), nTimeForks * MICRO, nTimeForks * MILLI / nBlocksTotal);
    2067                 :            : 
    2068         [ +  + ]:     200795 :     CBlockUndo blockundo;
    2069                 :            : 
    2070                 :            :     // Precomputed transaction data pointers must not be invalidated
    2071                 :            :     // until after `control` has run the script checks (potentially
    2072                 :            :     // in multiple threads). Preallocate the vector size so a new allocation
    2073                 :            :     // doesn't invalidate pointers into the vector, and keep txsdata in scope
    2074                 :            :     // for as long as `control`.
    2075   [ +  +  +  + ]:     200458 :     CCheckQueueControl<CScriptCheck> control(fScriptChecks && g_parallel_script_checks ? &scriptcheckqueue : nullptr);
    2076         [ +  - ]:     100229 :     std::vector<PrecomputedTransactionData> txsdata(block.vtx.size());
    2077                 :            : 
    2078         [ +  - ]:     200458 :     std::vector<int> prevheights;
    2079                 :     100229 :     CAmount nFees = 0;
    2080                 :     100229 :     int nInputs = 0;
    2081                 :     100229 :     int64_t nSigOpsCost = 0;
    2082         [ +  - ]:     100229 :     blockundo.vtxundo.reserve(block.vtx.size() - 1);
    2083         [ +  + ]:     519824 :     for (unsigned int i = 0; i < block.vtx.size(); i++)
    2084                 :            :     {
    2085         [ +  + ]:     422310 :         const CTransaction &tx = *(block.vtx[i]);
    2086                 :            : 
    2087         [ +  + ]:     422310 :         nInputs += tx.vin.size();
    2088                 :            : 
    2089         [ +  + ]:     422310 :         if (!tx.IsCoinBase())
    2090                 :            :         {
    2091                 :     322081 :             CAmount txfee = 0;
    2092         [ +  - ]:     322081 :             TxValidationState tx_state;
    2093   [ +  -  +  + ]:     322081 :             if (!Consensus::CheckTxInputs(tx, tx_state, view, pindex->nHeight, txfee)) {
    2094                 :            :                 // Any transaction validation failure in ConnectBlock is a block consensus failure
    2095         [ +  - ]:         25 :                 state.Invalid(BlockValidationResult::BLOCK_CONSENSUS,
    2096   [ +  -  +  - ]:         50 :                             tx_state.GetRejectReason(), tx_state.GetDebugMessage());
    2097   [ +  -  +  -  :         25 :                 return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), state.ToString());
                   +  - ]
    2098                 :            :             }
    2099                 :     322056 :             nFees += txfee;
    2100         [ -  + ]:     322056 :             if (!MoneyRange(nFees)) {
    2101         [ #  # ]:          0 :                 LogPrintf("ERROR: %s: accumulated fee in the block out of range.\n", __func__);
    2102   [ -  -  -  -  :         37 :                 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-accumulated-fee-outofrange");
                   -  - ]
    2103                 :            :             }
    2104                 :            : 
    2105                 :            :             // Check that transaction is BIP68 final
    2106                 :            :             // BIP68 lock checks (as opposed to nLockTime checks) must
    2107                 :            :             // be in ConnectBlock because they require the UTXO set
    2108         [ +  - ]:     322056 :             prevheights.resize(tx.vin.size());
    2109         [ +  + ]:     948141 :             for (size_t j = 0; j < tx.vin.size(); j++) {
    2110         [ +  - ]:     626085 :                 prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
    2111                 :            :             }
    2112                 :            : 
    2113   [ +  -  +  + ]:     322056 :             if (!SequenceLocks(tx, nLockTimeFlags, prevheights, *pindex)) {
    2114         [ +  - ]:         12 :                 LogPrintf("ERROR: %s: contains a non-BIP68-final transaction\n", __func__);
    2115   [ +  -  +  -  :         49 :                 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-nonfinal");
                   +  - ]
    2116                 :            :             }
    2117                 :            :         }
    2118                 :            : 
    2119                 :            :         // GetTransactionSigOpCost counts 3 types of sigops:
    2120                 :            :         // * legacy (always)
    2121                 :            :         // * p2sh (when P2SH enabled in flags and excludes coinbase)
    2122                 :            :         // * witness (when witness enabled in flags and excludes coinbase)
    2123         [ +  - ]:     422273 :         nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
    2124         [ +  + ]:     422273 :         if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST) {
    2125         [ +  - ]:          5 :             LogPrintf("ERROR: ConnectBlock(): too many sigops\n");
    2126   [ +  -  +  -  :          5 :             return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-sigops");
                   +  - ]
    2127                 :            :         }
    2128                 :            : 
    2129         [ +  + ]:     422268 :         if (!tx.IsCoinBase())
    2130                 :            :         {
    2131         [ +  + ]:     322039 :             std::vector<CScriptCheck> vChecks;
    2132                 :     322039 :             bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
    2133         [ +  + ]:     641405 :             TxValidationState tx_state;
    2134   [ +  +  +  +  :     329288 :             if (fScriptChecks && !CheckInputScripts(tx, tx_state, view, flags, fCacheResults, fCacheResults, txsdata[i], g_parallel_script_checks ? &vChecks : nullptr)) {
             +  -  +  + ]
    2135                 :            :                 // Any transaction validation failure in ConnectBlock is a block consensus failure
    2136         [ +  - ]:       2673 :                 state.Invalid(BlockValidationResult::BLOCK_CONSENSUS,
    2137   [ +  -  +  - ]:       5346 :                               tx_state.GetRejectReason(), tx_state.GetDebugMessage());
    2138         [ +  - ]:       2673 :                 return error("ConnectBlock(): CheckInputScripts on %s failed with %s",
    2139   [ +  -  +  - ]:       5346 :                     tx.GetHash().ToString(), state.ToString());
    2140                 :            :             }
    2141         [ +  + ]:     634155 :             control.Add(vChecks);
    2142                 :            :         }
    2143                 :            : 
    2144         [ +  + ]:     839190 :         CTxUndo undoDummy;
    2145         [ +  + ]:     419595 :         if (i > 0) {
    2146         [ +  - ]:     319366 :             blockundo.vtxundo.push_back(CTxUndo());
    2147                 :            :         }
    2148   [ +  +  +  - ]:     419595 :         UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
    2149                 :            :     }
    2150         [ +  - ]:      97514 :     int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
    2151   [ +  -  +  -  :      97514 :     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);
             +  +  +  - ]
    2152                 :            : 
    2153         [ +  - ]:      97514 :     CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
    2154   [ +  -  +  + ]:      97514 :     if (block.vtx[0]->GetValueOut() > blockReward) {
    2155   [ +  -  +  - ]:          5 :         LogPrintf("ERROR: ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)\n", block.vtx[0]->GetValueOut(), blockReward);
    2156   [ +  -  +  -  :     100234 :         return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-amount");
                   +  - ]
    2157                 :            :     }
    2158                 :            : 
    2159   [ +  -  +  + ]:      97509 :     if (!control.Wait()) {
    2160         [ +  - ]:         42 :         LogPrintf("ERROR: %s: CheckQueue failed\n", __func__);
    2161   [ +  -  +  -  :     100271 :         return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "block-validation-failed");
                   +  - ]
    2162                 :            :     }
    2163         [ +  - ]:      97467 :     int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
    2164   [ +  -  +  -  :      97467 :     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);
             +  +  +  - ]
    2165                 :            : 
    2166         [ +  + ]:      97467 :     if (fJustCheck)
    2167                 :            :         return true;
    2168                 :            : 
    2169   [ +  -  +  - ]:      70726 :     if (!WriteUndoDataForBlock(blockundo, state, pindex, chainparams))
    2170                 :            :         return false;
    2171                 :            : 
    2172   [ +  -  +  + ]:      70726 :     if (!pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
    2173                 :      67896 :         pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
    2174         [ +  - ]:      67896 :         setDirtyBlockIndex.insert(pindex);
    2175                 :            :     }
    2176                 :            : 
    2177         [ -  + ]:      70726 :     assert(pindex->phashBlock);
    2178                 :            :     // add this block to the view's block chain
    2179         [ +  - ]:      70726 :     view.SetBestBlock(pindex->GetBlockHash());
    2180                 :            : 
    2181         [ +  - ]:      70726 :     int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
    2182   [ +  -  +  -  :      70726 :     LogPrint(BCLog::BENCH, "    - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime5 - nTime4), nTimeIndex * MICRO, nTimeIndex * MILLI / nBlocksTotal);
                   +  - ]
    2183                 :            : 
    2184         [ +  - ]:      70726 :     int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
    2185   [ +  -  +  -  :      70726 :     LogPrint(BCLog::BENCH, "    - Callbacks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime6 - nTime5), nTimeCallbacks * MICRO, nTimeCallbacks * MILLI / nBlocksTotal);
                   +  - ]
    2186                 :            : 
    2187                 :            :     return true;
    2188                 :            : }
    2189                 :            : 
    2190                 :     460050 : CoinsCacheSizeState CChainState::GetCoinsCacheSizeState(const CTxMemPool* tx_pool)
    2191                 :            : {
    2192                 :     920100 :     return this->GetCoinsCacheSizeState(
    2193                 :            :         tx_pool,
    2194                 :            :         m_coinstip_cache_size_bytes,
    2195   [ +  -  +  - ]:     920100 :         gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
    2196                 :            : }
    2197                 :            : 
    2198                 :     460064 : CoinsCacheSizeState CChainState::GetCoinsCacheSizeState(
    2199                 :            :     const CTxMemPool* tx_pool,
    2200                 :            :     size_t max_coins_cache_size_bytes,
    2201                 :            :     size_t max_mempool_size_bytes)
    2202                 :            : {
    2203         [ +  - ]:     460064 :     const int64_t nMempoolUsage = tx_pool ? tx_pool->DynamicMemoryUsage() : 0;
    2204                 :     460064 :     int64_t cacheSize = CoinsTip().DynamicMemoryUsage();
    2205                 :     460064 :     int64_t nTotalSpace =
    2206         [ -  + ]:     460064 :         max_coins_cache_size_bytes + std::max<int64_t>(max_mempool_size_bytes - nMempoolUsage, 0);
    2207                 :            : 
    2208                 :            :     //! No need to periodic flush if at least this much space still available.
    2209                 :     460064 :     static constexpr int64_t MAX_BLOCK_COINSDB_USAGE_BYTES = 10 * 1024 * 1024;  // 10MB
    2210                 :     460064 :     int64_t large_threshold =
    2211         [ +  + ]:     460064 :         std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE_BYTES);
    2212                 :            : 
    2213         [ +  + ]:     460064 :     if (cacheSize > nTotalSpace) {
    2214                 :          5 :         LogPrintf("Cache size (%s) exceeds total space (%s)\n", cacheSize, nTotalSpace);
    2215                 :          5 :         return CoinsCacheSizeState::CRITICAL;
    2216         [ +  + ]:     460059 :     } else if (cacheSize > large_threshold) {
    2217                 :          4 :         return CoinsCacheSizeState::LARGE;
    2218                 :            :     }
    2219                 :            :     return CoinsCacheSizeState::OK;
    2220                 :            : }
    2221                 :            : 
    2222                 :     459050 : bool CChainState::FlushStateToDisk(
    2223                 :            :     const CChainParams& chainparams,
    2224                 :            :     BlockValidationState &state,
    2225                 :            :     FlushStateMode mode,
    2226                 :            :     int nManualPruneHeight)
    2227                 :            : {
    2228                 :     918100 :     LOCK(cs_main);
    2229         [ +  - ]:     459050 :     assert(this->CanFlushToDisk());
    2230                 :     459050 :     static std::chrono::microseconds nLastWrite{0};
    2231                 :     459050 :     static std::chrono::microseconds nLastFlush{0};
    2232         [ +  - ]:     918100 :     std::set<int> setFilesToPrune;
    2233                 :     459050 :     bool full_flush_completed = false;
    2234                 :            : 
    2235         [ +  - ]:     459050 :     const size_t coins_count = CoinsTip().GetCacheSize();
    2236         [ +  - ]:     459050 :     const size_t coins_mem_usage = CoinsTip().DynamicMemoryUsage();
    2237                 :            : 
    2238                 :     459050 :     try {
    2239                 :     459050 :     {
    2240                 :     459050 :         bool fFlushForPrune = false;
    2241                 :     459050 :         bool fDoFullFlush = false;
    2242         [ +  - ]:     459050 :         CoinsCacheSizeState cache_state = GetCoinsCacheSizeState(&m_mempool);
    2243         [ +  - ]:     459050 :         LOCK(cs_LastBlockFile);
    2244   [ +  +  +  +  :     459050 :         if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
             +  +  +  - ]
    2245         [ +  + ]:        163 :             if (nManualPruneHeight > 0) {
    2246   [ +  -  +  -  :         20 :                 LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune (manual)", BCLog::BENCH);
                   +  - ]
    2247                 :            : 
    2248         [ +  - ]:         10 :                 m_blockman.FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight, m_chain.Height());
    2249                 :            :             } else {
    2250   [ +  -  +  -  :        153 :                 LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune", BCLog::BENCH);
                   +  - ]
    2251                 :            : 
    2252   [ +  -  +  - ]:        153 :                 m_blockman.FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight(), m_chain.Height(), IsInitialBlockDownload());
    2253                 :        153 :                 fCheckForPruning = false;
    2254                 :            :             }
    2255         [ +  + ]:        163 :             if (!setFilesToPrune.empty()) {
    2256                 :         14 :                 fFlushForPrune = true;
    2257         [ +  + ]:         14 :                 if (!fHavePruned) {
    2258   [ +  -  +  - ]:          8 :                     pblocktree->WriteFlag("prunedblockfiles", true);
    2259                 :          4 :                     fHavePruned = true;
    2260                 :            :                 }
    2261                 :            :             }
    2262                 :            :         }
    2263         [ +  - ]:     459050 :         const auto nNow = GetTime<std::chrono::microseconds>();
    2264                 :            :         // Avoid writing/flushing immediately after startup.
    2265         [ +  + ]:     459050 :         if (nLastWrite.count() == 0) {
    2266                 :        656 :             nLastWrite = nNow;
    2267                 :            :         }
    2268         [ +  + ]:     459050 :         if (nLastFlush.count() == 0) {
    2269                 :        656 :             nLastFlush = nNow;
    2270                 :            :         }
    2271                 :            :         // 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).
    2272                 :     459050 :         bool fCacheLarge = mode == FlushStateMode::PERIODIC && cache_state >= CoinsCacheSizeState::LARGE;
    2273                 :            :         // The cache is over the limit, we have to write now.
    2274                 :     459050 :         bool fCacheCritical = mode == FlushStateMode::IF_NEEDED && cache_state >= CoinsCacheSizeState::CRITICAL;
    2275                 :            :         // 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.
    2276   [ +  +  +  + ]:     459050 :         bool fPeriodicWrite = mode == FlushStateMode::PERIODIC && nNow > nLastWrite + DATABASE_WRITE_INTERVAL;
    2277                 :            :         // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
    2278   [ +  +  +  + ]:     459050 :         bool fPeriodicFlush = mode == FlushStateMode::PERIODIC && nNow > nLastFlush + DATABASE_FLUSH_INTERVAL;
    2279                 :            :         // Combine all conditions that result in a full cache flush.
    2280   [ +  +  +  +  :     459050 :         fDoFullFlush = (mode == FlushStateMode::ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
                   +  + ]
    2281                 :            :         // Write blocks and block index to disk.
    2282         [ +  + ]:     459050 :         if (fDoFullFlush || fPeriodicWrite) {
    2283                 :            :             // Depend on nMinDiskSpace to ensure we can write block index
    2284   [ +  -  +  -  :       1776 :             if (!CheckDiskSpace(GetBlocksDir())) {
                   -  + ]
    2285   [ #  #  #  #  :          0 :                 return AbortNode(state, "Disk space is too low!", _("Disk space is too low!"));
             #  #  #  # ]
    2286                 :            :             }
    2287                 :       1776 :             {
    2288   [ +  -  +  -  :       3552 :                 LOG_TIME_MILLIS_WITH_CATEGORY("write block and undo data to disk", BCLog::BENCH);
                   +  - ]
    2289                 :            : 
    2290                 :            :                 // First make sure all block and undo data is flushed to disk.
    2291         [ +  - ]:       1776 :                 FlushBlockFile();
    2292                 :            :             }
    2293                 :            : 
    2294                 :            :             // Then update all block file information (which may refer to block and undo files).
    2295                 :       1776 :             {
    2296   [ +  -  +  -  :       1776 :                 LOG_TIME_MILLIS_WITH_CATEGORY("write block index to disk", BCLog::BENCH);
                   +  - ]
    2297                 :            : 
    2298         [ +  - ]:       3552 :                 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
    2299         [ +  - ]:       1776 :                 vFiles.reserve(setDirtyFileInfo.size());
    2300         [ +  + ]:       2348 :                 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
    2301         [ +  - ]:        572 :                     vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
    2302                 :        572 :                     setDirtyFileInfo.erase(it++);
    2303                 :            :                 }
    2304         [ +  - ]:       3552 :                 std::vector<const CBlockIndex*> vBlocks;
    2305         [ +  - ]:       1776 :                 vBlocks.reserve(setDirtyBlockIndex.size());
    2306         [ +  + ]:      76428 :                 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
    2307         [ +  - ]:      74652 :                     vBlocks.push_back(*it);
    2308                 :      74652 :                     setDirtyBlockIndex.erase(it++);
    2309                 :            :                 }
    2310   [ +  -  -  + ]:       1776 :                 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
    2311   [ #  #  #  # ]:          0 :                     return AbortNode(state, "Failed to write to block index database");
    2312                 :            :                 }
    2313                 :            :             }
    2314                 :            :             // Finally remove any pruned files
    2315         [ +  + ]:       1776 :             if (fFlushForPrune) {
    2316   [ +  -  +  -  :         28 :                 LOG_TIME_MILLIS_WITH_CATEGORY("unlink pruned files", BCLog::BENCH);
                   +  - ]
    2317                 :            : 
    2318         [ +  - ]:         14 :                 UnlinkPrunedFiles(setFilesToPrune);
    2319                 :            :             }
    2320                 :       1776 :             nLastWrite = nNow;
    2321                 :            :         }
    2322                 :            :         // Flush best chain related state. This can only be done if the blocks / block index write was also done.
    2323   [ +  +  +  -  :     460816 :         if (fDoFullFlush && !CoinsTip().GetBestBlock().IsNull()) {
                   +  - ]
    2324   [ +  -  +  -  :       1766 :             LOG_TIME_SECONDS(strprintf("write coins cache to disk (%d coins, %.2fkB)",
                   +  - ]
    2325                 :            :                 coins_count, coins_mem_usage / 1000));
    2326                 :            : 
    2327                 :            :             // Typical Coin structures on disk are around 48 bytes in size.
    2328                 :            :             // Pushing a new one to the database can cause it to be written
    2329                 :            :             // twice (once in the log, and once in the tables). This is already
    2330                 :            :             // an overestimation, as most will delete an existing entry or
    2331                 :            :             // overwrite one. Still, use a conservative safety factor of 2.
    2332   [ +  -  +  -  :       1766 :             if (!CheckDiskSpace(GetDataDir(), 48 * 2 * 2 * CoinsTip().GetCacheSize())) {
             +  -  -  + ]
    2333   [ #  #  #  #  :          0 :                 return AbortNode(state, "Disk space is too low!", _("Disk space is too low!"));
                   #  # ]
    2334                 :            :             }
    2335                 :            :             // Flush the chainstate (which may refer to block index entries).
    2336   [ +  -  -  + ]:       1766 :             if (!CoinsTip().Flush())
    2337   [ #  #  #  # ]:          0 :                 return AbortNode(state, "Failed to write to coin database");
    2338                 :       1766 :             nLastFlush = nNow;
    2339                 :       1766 :             full_flush_completed = true;
    2340                 :            :         }
    2341                 :            :     }
    2342         [ +  + ]:     459050 :     if (full_flush_completed) {
    2343                 :            :         // Update best block in wallet (so we can detect restored wallets).
    2344   [ +  -  +  -  :     460816 :         GetMainSignals().ChainStateFlushed(m_chain.GetLocator());
                   +  - ]
    2345                 :            :     }
    2346         [ -  - ]:          0 :     } catch (const std::runtime_error& e) {
    2347   [ -  -  -  -  :          0 :         return AbortNode(state, std::string("System error while flushing: ") + e.what());
                   -  - ]
    2348                 :            :     }
    2349                 :            :     return true;
    2350                 :            : }
    2351                 :            : 
    2352                 :       1357 : void CChainState::ForceFlushStateToDisk() {
    2353         [ +  - ]:       1357 :     BlockValidationState state;
    2354         [ +  - ]:       1357 :     const CChainParams& chainparams = Params();
    2355   [ +  -  -  + ]:       1357 :     if (!this->FlushStateToDisk(chainparams, state, FlushStateMode::ALWAYS)) {
    2356   [ -  -  -  - ]:       1357 :         LogPrintf("%s: failed to flush state (%s)\n", __func__, state.ToString());
    2357                 :            :     }
    2358                 :       1357 : }
    2359                 :            : 
    2360                 :         13 : void CChainState::PruneAndFlush() {
    2361         [ +  - ]:         13 :     BlockValidationState state;
    2362                 :         13 :     fCheckForPruning = true;
    2363         [ +  - ]:         13 :     const CChainParams& chainparams = Params();
    2364                 :            : 
    2365   [ +  -  -  + ]:         13 :     if (!this->FlushStateToDisk(chainparams, state, FlushStateMode::NONE)) {
    2366   [ -  -  -  - ]:         13 :         LogPrintf("%s: failed to flush state (%s)\n", __func__, state.ToString());
    2367                 :            :     }
    2368                 :         13 : }
    2369                 :            : 
    2370                 :       8293 : static void DoWarning(const bilingual_str& warning)
    2371                 :            : {
    2372                 :       8293 :     static bool fWarned = false;
    2373                 :       8293 :     SetMiscWarning(warning);
    2374         [ +  + ]:       8293 :     if (!fWarned) {
    2375                 :         10 :         AlertNotify(warning.original);
    2376                 :         10 :         fWarned = true;
    2377                 :            :     }
    2378                 :       8293 : }
    2379                 :            : 
    2380                 :            : /** Private helper function that concatenates warning messages. */
    2381                 :       1008 : static void AppendWarning(bilingual_str& res, const bilingual_str& warn)
    2382                 :            : {
    2383   [ -  +  -  - ]:       1008 :     if (!res.empty()) res += Untranslated(", ");
    2384                 :       1008 :     res += warn;
    2385                 :       1008 : }
    2386                 :            : 
    2387                 :            : /** Check warning conditions and do some notifications on new chain tip set. */
    2388                 :      77067 : static void UpdateTip(CTxMemPool& mempool, const CBlockIndex* pindexNew, const CChainParams& chainParams)
    2389                 :            :     EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
    2390                 :            : {
    2391                 :            :     // New best block
    2392                 :      77067 :     mempool.AddTransactionsUpdated(1);
    2393                 :            : 
    2394                 :      77067 :     {
    2395                 :      77067 :         LOCK(g_best_block_mutex);
    2396                 :      77067 :         g_best_block = pindexNew->GetBlockHash();
    2397         [ +  - ]:      77067 :         g_best_block_cv.notify_all();
    2398                 :            :     }
    2399                 :            : 
    2400         [ +  - ]:      77067 :     bilingual_str warning_messages;
    2401   [ +  -  +  -  :      77067 :     if (!::ChainstateActive().IsInitialBlockDownload()) {
                   +  + ]
    2402                 :      70907 :         const CBlockIndex* pindex = pindexNew;
    2403         [ +  + ]:    2127210 :         for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
    2404         [ +  - ]:    2056303 :             WarningBitsConditionChecker checker(bit);
    2405         [ +  - ]:    2056303 :             ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
    2406         [ +  + ]:    2056303 :             if (state == ThresholdState::ACTIVE || state == ThresholdState::LOCKED_IN) {
    2407   [ +  -  +  - ]:    2065604 :                 const bilingual_str warning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
    2408         [ +  + ]:       9301 :                 if (state == ThresholdState::ACTIVE) {
    2409         [ +  - ]:       8293 :                     DoWarning(warning);
    2410                 :            :                 } else {
    2411         [ +  - ]:       1008 :                     AppendWarning(warning_messages, warning);
    2412                 :            :                 }
    2413                 :            :             }
    2414                 :            :         }
    2415                 :            :     }
    2416   [ +  +  +  - ]:     154134 :     LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%f tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)%s\n", __func__,
    2417                 :      77067 :       pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, pindexNew->nVersion,
    2418   [ +  -  +  - ]:      77067 :       log(pindexNew->nChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx,
    2419         [ +  - ]:     154134 :       FormatISO8601DateTime(pindexNew->GetBlockTime()),
    2420   [ +  -  +  -  :      77067 :       GuessVerificationProgress(chainParams.TxData(), pindexNew), ::ChainstateActive().CoinsTip().DynamicMemoryUsage() * (1.0 / (1<<20)), ::ChainstateActive().CoinsTip().GetCacheSize(),
          +  -  +  -  +  
                      - ]
    2421   [ +  +  +  -  :     154134 :       !warning_messages.empty() ? strprintf(" warning='%s'", warning_messages.original) : "");
                   +  - ]
    2422                 :      77067 : }
    2423                 :            : 
    2424                 :            : /** Disconnect m_chain's tip.
    2425                 :            :   * After calling, the mempool will be in an inconsistent state, with
    2426                 :            :   * transactions from disconnected blocks being added to disconnectpool.  You
    2427                 :            :   * should make the mempool consistent again by calling UpdateMempoolForReorg.
    2428                 :            :   * with cs_main held.
    2429                 :            :   *
    2430                 :            :   * If disconnectpool is nullptr, then no disconnected transactions are added to
    2431                 :            :   * disconnectpool (note that the caller is responsible for mempool consistency
    2432                 :            :   * in any case).
    2433                 :            :   */
    2434                 :       6733 : bool CChainState::DisconnectTip(BlockValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions* disconnectpool)
    2435                 :            : {
    2436         [ +  - ]:       6733 :     AssertLockHeld(cs_main);
    2437                 :       6733 :     AssertLockHeld(m_mempool.cs);
    2438                 :            : 
    2439         [ +  - ]:       6733 :     CBlockIndex *pindexDelete = m_chain.Tip();
    2440         [ -  + ]:       6733 :     assert(pindexDelete);
    2441                 :            :     // Read block from disk.
    2442                 :      13466 :     std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
    2443         [ +  - ]:       6733 :     CBlock& block = *pblock;
    2444   [ +  -  -  + ]:       6733 :     if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
    2445         [ #  # ]:          0 :         return error("DisconnectTip(): Failed to read block");
    2446                 :            :     // Apply the block atomically to the chain state.
    2447         [ +  - ]:       6733 :     int64_t nStart = GetTimeMicros();
    2448                 :       6733 :     {
    2449         [ +  - ]:       6733 :         CCoinsViewCache view(&CoinsTip());
    2450   [ +  -  -  + ]:       6733 :         assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
    2451   [ +  -  +  + ]:       6733 :         if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
    2452   [ +  -  +  - ]:          1 :             return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
    2453         [ +  - ]:       6732 :         bool flushed = view.Flush();
    2454         [ -  + ]:       6732 :         assert(flushed);
    2455                 :            :     }
    2456   [ +  -  +  -  :       6732 :     LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI);
             +  -  +  - ]
    2457                 :            :     // Write the chain state to disk, if necessary.
    2458   [ +  -  +  - ]:       6732 :     if (!FlushStateToDisk(chainparams, state, FlushStateMode::IF_NEEDED))
    2459                 :            :         return false;
    2460                 :            : 
    2461         [ +  + ]:       6732 :     if (disconnectpool) {
    2462                 :            :         // Save transactions to re-add to mempool at end of reorg
    2463         [ +  + ]:      33270 :         for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
    2464         [ +  - ]:      26685 :             disconnectpool->addTransaction(*it);
    2465                 :            :         }
    2466         [ +  + ]:      10324 :         while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
    2467                 :            :             // Drop the earliest entry, and remove its children from the mempool.
    2468         [ +  - ]:       3739 :             auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
    2469         [ +  - ]:       3739 :             m_mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
    2470                 :       3739 :             disconnectpool->removeEntry(it);
    2471                 :            :         }
    2472                 :            :     }
    2473                 :            : 
    2474         [ +  - ]:       6732 :     m_chain.SetTip(pindexDelete->pprev);
    2475                 :            : 
    2476         [ +  - ]:       6732 :     UpdateTip(m_mempool, pindexDelete->pprev, chainparams);
    2477                 :            :     // Let wallets know transactions went from 1-confirmed to
    2478                 :            :     // 0-confirmed or conflicted:
    2479   [ +  -  +  -  :      13464 :     GetMainSignals().BlockDisconnected(pblock, pindexDelete);
                   +  - ]
    2480                 :       6732 :     return true;
    2481                 :            : }
    2482                 :            : 
    2483                 :            : static int64_t nTimeReadFromDisk = 0;
    2484                 :            : static int64_t nTimeConnectTotal = 0;
    2485                 :            : static int64_t nTimeFlush = 0;
    2486                 :            : static int64_t nTimeChainState = 0;
    2487                 :            : static int64_t nTimePostConnect = 0;
    2488                 :            : 
    2489   [ -  +  +  +  :     301883 : struct PerBlockConnectTrace {
                   -  + ]
    2490                 :            :     CBlockIndex* pindex = nullptr;
    2491                 :            :     std::shared_ptr<const CBlock> pblock;
    2492                 :     157072 :     PerBlockConnectTrace() {}
    2493                 :            : };
    2494                 :            : /**
    2495                 :            :  * Used to track blocks whose transactions were applied to the UTXO state as a
    2496                 :            :  * part of a single ActivateBestChainStep call.
    2497                 :            :  *
    2498                 :            :  * This class is single-use, once you call GetBlocksConnected() you have to throw
    2499                 :            :  * it away and make a new one.
    2500                 :            :  */
    2501                 :      18841 : class ConnectTrace {
    2502                 :            : private:
    2503                 :            :     std::vector<PerBlockConnectTrace> blocksConnected;
    2504                 :            : 
    2505                 :            : public:
    2506                 :      86737 :     explicit ConnectTrace() : blocksConnected(1) {}
    2507                 :            : 
    2508                 :      70335 :     void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
    2509         [ -  + ]:      70335 :         assert(!blocksConnected.back().pindex);
    2510         [ -  + ]:      70335 :         assert(pindex);
    2511         [ -  + ]:      70335 :         assert(pblock);
    2512                 :      70335 :         blocksConnected.back().pindex = pindex;
    2513                 :      70335 :         blocksConnected.back().pblock = std::move(pblock);
    2514                 :      70335 :         blocksConnected.emplace_back();
    2515                 :      70335 :     }
    2516                 :            : 
    2517                 :      67896 :     std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
    2518                 :            :         // We always keep one extra block at the end of our list because
    2519                 :            :         // blocks are added after all the conflicted transactions have
    2520                 :            :         // been filled in. Thus, the last entry should always be an empty
    2521                 :            :         // one waiting for the transactions from the next block. We pop
    2522                 :            :         // the last entry here to make sure the list we return is sane.
    2523         [ -  + ]:      67896 :         assert(!blocksConnected.back().pindex);
    2524                 :      67896 :         blocksConnected.pop_back();
    2525                 :      67896 :         return blocksConnected;
    2526                 :            :     }
    2527                 :            : };
    2528                 :            : 
    2529                 :            : /**
    2530                 :            :  * Connect a new block to m_chain. pblock is either nullptr or a pointer to a CBlock
    2531                 :            :  * corresponding to pindexNew, to bypass loading it again from disk.
    2532                 :            :  *
    2533                 :            :  * The block is added to connectTrace if connection succeeds.
    2534                 :            :  */
    2535                 :      73093 : bool CChainState::ConnectTip(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool)
    2536                 :            : {
    2537         [ +  + ]:      73093 :     AssertLockHeld(cs_main);
    2538                 :      73093 :     AssertLockHeld(m_mempool.cs);
    2539                 :            : 
    2540   [ +  +  -  + ]:     145850 :     assert(pindexNew->pprev == m_chain.Tip());
    2541                 :            :     // Read block from disk.
    2542                 :      73093 :     int64_t nTime1 = GetTimeMicros();
    2543                 :      73093 :     std::shared_ptr<const CBlock> pthisBlock;
    2544         [ +  + ]:      73093 :     if (!pblock) {
    2545         [ +  - ]:       7764 :         std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
    2546   [ +  -  -  + ]:       7764 :         if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
    2547   [ #  #  #  # ]:          0 :             return AbortNode(state, "Failed to read block");
    2548         [ +  - ]:       7764 :         pthisBlock = pblockNew;
    2549                 :            :     } else {
    2550                 :      65329 :         pthisBlock = pblock;
    2551                 :            :     }
    2552         [ +  - ]:      73093 :     const CBlock& blockConnecting = *pthisBlock;
    2553                 :            :     // Apply the block atomically to the chain state.
    2554         [ +  - ]:      73093 :     int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
    2555                 :      73093 :     int64_t nTime3;
    2556   [ +  -  +  -  :      73093 :     LogPrint(BCLog::BENCH, "  - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * MILLI, nTimeReadFromDisk * MICRO);
                   +  - ]
    2557                 :      73093 :     {
    2558         [ +  - ]:      73093 :         CCoinsViewCache view(&CoinsTip());
    2559         [ +  - ]:      73093 :         bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
    2560   [ +  -  +  - ]:      73093 :         GetMainSignals().BlockChecked(blockConnecting, state);
    2561         [ +  + ]:      73093 :         if (!rv) {
    2562         [ +  - ]:       2758 :             if (state.IsInvalid())
    2563         [ +  - ]:       2758 :                 InvalidBlockFound(pindexNew, state);
    2564   [ +  -  +  -  :       2758 :             return error("%s: ConnectBlock %s failed, %s", __func__, pindexNew->GetBlockHash().ToString(), state.ToString());
                   +  - ]
    2565                 :            :         }
    2566         [ +  - ]:      70335 :         nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
    2567         [ -  + ]:      70335 :         assert(nBlocksTotal > 0);
    2568   [ +  -  +  -  :      70335 :         LogPrint(BCLog::BENCH, "  - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime3 - nTime2) * MILLI, nTimeConnectTotal * MICRO, nTimeConnectTotal * MILLI / nBlocksTotal);
                   +  - ]
    2569         [ +  - ]:      70335 :         bool flushed = view.Flush();
    2570         [ -  + ]:      70335 :         assert(flushed);
    2571                 :            :     }
    2572         [ +  - ]:      70335 :     int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
    2573   [ +  -  +  -  :      70335 :     LogPrint(BCLog::BENCH, "  - Flush: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime4 - nTime3) * MILLI, nTimeFlush * MICRO, nTimeFlush * MILLI / nBlocksTotal);
                   +  - ]
    2574                 :            :     // Write the chain state to disk, if necessary.
    2575   [ +  -  +  - ]:      70335 :     if (!FlushStateToDisk(chainparams, state, FlushStateMode::IF_NEEDED))
    2576                 :            :         return false;
    2577         [ +  - ]:      70335 :     int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
    2578   [ +  -  +  -  :      70335 :     LogPrint(BCLog::BENCH, "  - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime5 - nTime4) * MILLI, nTimeChainState * MICRO, nTimeChainState * MILLI / nBlocksTotal);
                   +  - ]
    2579                 :            :     // Remove conflicting transactions from the mempool.;
    2580         [ +  - ]:      70335 :     m_mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
    2581         [ +  - ]:      70335 :     disconnectpool.removeForBlock(blockConnecting.vtx);
    2582                 :            :     // Update m_chain & related variables.
    2583         [ +  - ]:      70335 :     m_chain.SetTip(pindexNew);
    2584         [ +  - ]:      70335 :     UpdateTip(m_mempool, pindexNew, chainparams);
    2585                 :            : 
    2586         [ +  - ]:      70335 :     int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
    2587   [ +  -  +  -  :      70335 :     LogPrint(BCLog::BENCH, "  - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime5) * MILLI, nTimePostConnect * MICRO, nTimePostConnect * MILLI / nBlocksTotal);
                   +  - ]
    2588   [ +  -  +  -  :      70335 :     LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime1) * MILLI, nTimeTotal * MICRO, nTimeTotal * MILLI / nBlocksTotal);
                   +  - ]
    2589                 :            : 
    2590         [ +  - ]:      70335 :     connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
    2591                 :      70335 :     return true;
    2592                 :            : }
    2593                 :            : 
    2594                 :            : /**
    2595                 :            :  * Return the tip of the chain with the most work in it, that isn't
    2596                 :            :  * known to be invalid (it's however far from certain to be valid).
    2597                 :            :  */
    2598                 :      84683 : CBlockIndex* CChainState::FindMostWorkChain() {
    2599                 :      84689 :     do {
    2600                 :      84689 :         CBlockIndex *pindexNew = nullptr;
    2601                 :            : 
    2602                 :            :         // Find the best candidate header.
    2603                 :      84689 :         {
    2604                 :      84689 :             std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
    2605         [ +  - ]:      84689 :             if (it == setBlockIndexCandidates.rend())
    2606                 :            :                 return nullptr;
    2607                 :      84689 :             pindexNew = *it;
    2608                 :            :         }
    2609                 :            : 
    2610                 :            :         // Check whether all blocks on the path between the currently active chain and the candidate are valid.
    2611                 :            :         // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
    2612                 :      84689 :         CBlockIndex *pindexTest = pindexNew;
    2613                 :      84689 :         bool fInvalidAncestor = false;
    2614   [ +  +  +  + ]:     158059 :         while (pindexTest && !m_chain.Contains(pindexTest)) {
    2615   [ -  +  -  - ]:      73376 :             assert(pindexTest->HaveTxsDownloaded() || pindexTest->nHeight == 0);
    2616                 :            : 
    2617                 :            :             // Pruned nodes may have entries in setBlockIndexCandidates for
    2618                 :            :             // which block files have been deleted.  Remove those as candidates
    2619                 :            :             // for the most work chain if we come across them; we can't switch
    2620                 :            :             // to a chain unless we have all the non-active-chain parent blocks.
    2621                 :      73376 :             bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
    2622                 :      73376 :             bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
    2623         [ +  + ]:      73376 :             if (fFailedChain || fMissingData) {
    2624                 :            :                 // Candidate chain is not usable (either invalid or missing data)
    2625   [ +  +  +  -  :          6 :                 if (fFailedChain && (pindexBestInvalid == nullptr || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
                   +  + ]
    2626                 :          1 :                     pindexBestInvalid = pindexNew;
    2627                 :          6 :                 CBlockIndex *pindexFailed = pindexNew;
    2628                 :            :                 // Remove the entire chain from the set.
    2629         [ +  + ]:        276 :                 while (pindexTest != pindexFailed) {
    2630         [ +  + ]:        270 :                     if (fFailedChain) {
    2631                 :          5 :                         pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
    2632         [ +  - ]:        265 :                     } else if (fMissingData) {
    2633                 :            :                         // If we're missing data, then add back to m_blocks_unlinked,
    2634                 :            :                         // so that if the block arrives in the future we can try adding
    2635                 :            :                         // to setBlockIndexCandidates again.
    2636                 :        265 :                         m_blockman.m_blocks_unlinked.insert(
    2637                 :        265 :                             std::make_pair(pindexFailed->pprev, pindexFailed));
    2638                 :            :                     }
    2639                 :        270 :                     setBlockIndexCandidates.erase(pindexFailed);
    2640                 :        270 :                     pindexFailed = pindexFailed->pprev;
    2641                 :            :                 }
    2642                 :          6 :                 setBlockIndexCandidates.erase(pindexTest);
    2643                 :          6 :                 fInvalidAncestor = true;
    2644                 :          6 :                 break;
    2645                 :            :             }
    2646                 :      73370 :             pindexTest = pindexTest->pprev;
    2647                 :            :         }
    2648                 :          6 :         if (!fInvalidAncestor)
    2649                 :            :             return pindexNew;
    2650                 :            :     } while(true);
    2651                 :            : }
    2652                 :            : 
    2653                 :            : /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
    2654                 :      71117 : void CChainState::PruneBlockIndexCandidates() {
    2655                 :            :     // Note that we can't delete the current block itself, as we may need to return to it later in case a
    2656                 :            :     // reorganization to a better block fails.
    2657                 :      71117 :     std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
    2658   [ +  -  +  -  :     427714 :     while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, m_chain.Tip())) {
                   +  + ]
    2659                 :     142740 :         setBlockIndexCandidates.erase(it++);
    2660                 :            :     }
    2661                 :            :     // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
    2662         [ -  + ]:      71117 :     assert(!setBlockIndexCandidates.empty());
    2663                 :      71117 : }
    2664                 :            : 
    2665                 :            : /**
    2666                 :            :  * Try to make some progress towards making pindexMostWork the active block.
    2667                 :            :  * pblock is either nullptr or a pointer to a CBlock corresponding to pindexMostWork.
    2668                 :            :  *
    2669                 :            :  * @returns true unless a system error occurred
    2670                 :            :  */
    2671                 :      67897 : bool CChainState::ActivateBestChainStep(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
    2672                 :            : {
    2673         [ +  + ]:      67897 :     AssertLockHeld(cs_main);
    2674                 :      67897 :     AssertLockHeld(m_mempool.cs);
    2675                 :            : 
    2676         [ +  + ]:      67897 :     const CBlockIndex* pindexOldTip = m_chain.Tip();
    2677                 :      67897 :     const CBlockIndex* pindexFork = m_chain.FindFork(pindexMostWork);
    2678                 :            : 
    2679                 :            :     // Disconnect active blocks which are no longer in the best chain.
    2680                 :      67897 :     bool fBlocksDisconnected = false;
    2681                 :      67897 :     DisconnectedBlockTransactions disconnectpool;
    2682   [ +  +  +  -  :      73197 :     while (m_chain.Tip() && m_chain.Tip() != pindexFork) {
                   +  + ]
    2683   [ +  -  +  + ]:       5301 :         if (!DisconnectTip(state, chainparams, &disconnectpool)) {
    2684                 :            :             // This is likely a fatal error, but keep the mempool consistent,
    2685                 :            :             // just in case. Only remove from the mempool in this case.
    2686         [ +  - ]:          1 :             UpdateMempoolForReorg(m_mempool, disconnectpool, false);
    2687                 :            : 
    2688                 :            :             // If we're unable to disconnect a block during normal operation,
    2689                 :            :             // then that is a failure of our local system -- we should abort
    2690                 :            :             // rather than stay on a less work chain.
    2691   [ +  -  +  - ]:          2 :             AbortNode(state, "Failed to disconnect block; see debug.log for details");
    2692                 :          1 :             return false;
    2693                 :            :         }
    2694                 :            :         fBlocksDisconnected = true;
    2695                 :            :     }
    2696                 :            : 
    2697                 :            :     // Build list of new blocks to connect (in descending height order).
    2698         [ +  + ]:     135793 :     std::vector<CBlockIndex*> vpindexToConnect;
    2699                 :      67896 :     bool fContinue = true;
    2700         [ +  + ]:      67896 :     int nHeight = pindexFork ? pindexFork->nHeight : -1;
    2701   [ +  +  +  + ]:     135903 :     while (fContinue && nHeight != pindexMostWork->nHeight) {
    2702                 :            :         // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
    2703                 :            :         // a few blocks along the way.
    2704         [ +  + ]:      68007 :         int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
    2705         [ +  + ]:      68007 :         vpindexToConnect.clear();
    2706         [ +  - ]:      68007 :         vpindexToConnect.reserve(nTargetHeight - nHeight);
    2707         [ +  - ]:      68007 :         CBlockIndex* pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
    2708   [ +  +  +  + ]:     196110 :         while (pindexIter && pindexIter->nHeight != nHeight) {
    2709         [ +  - ]:     128103 :             vpindexToConnect.push_back(pindexIter);
    2710                 :     128103 :             pindexIter = pindexIter->pprev;
    2711                 :            :         }
    2712                 :      68007 :         nHeight = nTargetHeight;
    2713                 :            : 
    2714                 :            :         // Connect new blocks.
    2715         [ +  + ]:      73304 :         for (CBlockIndex* pindexConnect : reverse_iterate(vpindexToConnect)) {
    2716   [ +  +  +  -  :     211515 :             if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
             +  +  +  + ]
    2717         [ +  - ]:       2758 :                 if (state.IsInvalid()) {
    2718                 :            :                     // The block violates a consensus rule.
    2719         [ +  - ]:       2758 :                     if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
    2720         [ +  - ]:       2758 :                         InvalidChainFound(vpindexToConnect.front());
    2721                 :            :                     }
    2722                 :       2758 :                     state = BlockValidationState();
    2723                 :       2758 :                     fInvalidFound = true;
    2724                 :       2758 :                     fContinue = false;
    2725                 :       2758 :                     break;
    2726                 :            :                 } else {
    2727                 :            :                     // A system error occurred (disk space, database error, ...).
    2728                 :            :                     // Make the mempool consistent with the current tip, just in case
    2729                 :            :                     // any observers try to use it before shutdown.
    2730         [ #  # ]:          0 :                     UpdateMempoolForReorg(m_mempool, disconnectpool, false);
    2731                 :            :                     return false;
    2732                 :            :                 }
    2733                 :            :             } else {
    2734         [ +  - ]:      70335 :                 PruneBlockIndexCandidates();
    2735   [ +  +  +  -  :     140334 :                 if (!pindexOldTip || m_chain.Tip()->nChainWork > pindexOldTip->nChainWork) {
             +  -  +  + ]
    2736                 :            :                     // We're in a better position than we were. Return temporarily to release the lock.
    2737                 :            :                     fContinue = false;
    2738                 :            :                     break;
    2739                 :            :                 }
    2740                 :            :             }
    2741                 :            :         }
    2742                 :            :     }
    2743                 :            : 
    2744         [ +  + ]:      67896 :     if (fBlocksDisconnected) {
    2745                 :            :         // If any blocks were disconnected, disconnectpool may be non empty.  Add
    2746                 :            :         // any disconnected transactions back to the mempool.
    2747         [ +  - ]:       1479 :         UpdateMempoolForReorg(m_mempool, disconnectpool, true);
    2748                 :            :     }
    2749         [ +  - ]:      67896 :     m_mempool.check(&CoinsTip());
    2750                 :            : 
    2751         [ +  - ]:      67896 :     CheckForkWarningConditions();
    2752                 :            : 
    2753                 :            :     return true;
    2754                 :            : }
    2755                 :            : 
    2756                 :     123317 : static SynchronizationState GetSynchronizationState(bool init)
    2757                 :            : {
    2758         [ +  + ]:     123317 :     if (!init) return SynchronizationState::POST_INIT;
    2759         [ +  + ]:       7744 :     if (::fReindex) return SynchronizationState::INIT_REINDEX;
    2760                 :            :     return SynchronizationState::INIT_DOWNLOAD;
    2761                 :            : }
    2762                 :            : 
    2763                 :     116295 : static bool NotifyHeaderTip() LOCKS_EXCLUDED(cs_main) {
    2764                 :     116295 :     bool fNotify = false;
    2765                 :     116295 :     bool fInitialBlockDownload = false;
    2766                 :     116295 :     static CBlockIndex* pindexHeaderOld = nullptr;
    2767                 :     116295 :     CBlockIndex* pindexHeader = nullptr;
    2768                 :     116295 :     {
    2769                 :     116295 :         LOCK(cs_main);
    2770                 :     116295 :         pindexHeader = pindexBestHeader;
    2771                 :            : 
    2772         [ +  + ]:     116295 :         if (pindexHeader != pindexHeaderOld) {
    2773                 :      58200 :             fNotify = true;
    2774   [ +  -  +  - ]:      58200 :             fInitialBlockDownload = ::ChainstateActive().IsInitialBlockDownload();
    2775                 :      58200 :             pindexHeaderOld = pindexHeader;
    2776                 :            :         }
    2777                 :            :     }
    2778                 :            :     // Send block tip changed notifications without cs_main
    2779         [ +  + ]:     116295 :     if (fNotify) {
    2780                 :      58200 :         uiInterface.NotifyHeaderTip(GetSynchronizationState(fInitialBlockDownload), pindexHeader);
    2781                 :            :     }
    2782                 :     116295 :     return fNotify;
    2783                 :            : }
    2784                 :            : 
    2785                 :      88149 : static void LimitValidationInterfaceQueue() LOCKS_EXCLUDED(cs_main) {
    2786                 :      88149 :     AssertLockNotHeld(cs_main);
    2787                 :            : 
    2788         [ +  + ]:      88149 :     if (GetMainSignals().CallbacksPending() > 10) {
    2789                 :        805 :         SyncWithValidationInterfaceQueue();
    2790                 :            :     }
    2791                 :      88149 : }
    2792                 :            : 
    2793                 :      81925 : bool CChainState::ActivateBestChain(BlockValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
    2794                 :            :     // Note that while we're often called here from ProcessNewBlock, this is
    2795                 :            :     // far from a guarantee. Things in the P2P/RPC will often end up calling
    2796                 :            :     // us in the middle of ProcessNewBlock - do not assume pblock is set
    2797                 :            :     // sanely for performance or correctness!
    2798                 :      81925 :     AssertLockNotHeld(cs_main);
    2799                 :            : 
    2800                 :            :     // ABC maintains a fair degree of expensive-to-calculate internal state
    2801                 :            :     // because this function periodically releases cs_main so that it does not lock up other threads for too long
    2802                 :            :     // during large connects - and to allow for e.g. the callback queue to drain
    2803                 :            :     // we use m_cs_chainstate to enforce mutual exclusion so that only one caller may execute this function at a time
    2804                 :     163850 :     LOCK(m_cs_chainstate);
    2805                 :            : 
    2806                 :      81925 :     CBlockIndex *pindexMostWork = nullptr;
    2807                 :      81925 :     CBlockIndex *pindexNewTip = nullptr;
    2808   [ +  -  +  -  :     168569 :     int nStopAtHeight = gArgs.GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
                   +  - ]
    2809                 :      86644 :     do {
    2810                 :            :         // Block until the validation queue drains. This should largely
    2811                 :            :         // never happen in normal operation, however may happen during
    2812                 :            :         // reindex, causing memory blowup if we run too far ahead.
    2813                 :            :         // Note that if a validationinterface callback ends up calling
    2814                 :            :         // ActivateBestChain this may lead to a deadlock! We should
    2815                 :            :         // probably have a DEBUG_LOCKORDER test for this in the future.
    2816         [ +  - ]:      86644 :         LimitValidationInterfaceQueue();
    2817                 :            : 
    2818                 :      86644 :         {
    2819         [ +  - ]:      86644 :             LOCK(cs_main);
    2820   [ +  -  +  - ]:     154447 :             LOCK(m_mempool.cs); // Lock transaction pool for at least as long as it takes for connectTrace to be consumed
    2821         [ +  + ]:      86644 :             CBlockIndex* starting_tip = m_chain.Tip();
    2822                 :      86644 :             bool blocks_connected = false;
    2823                 :      86737 :             do {
    2824                 :            :                 // We absolutely may not unlock cs_main until we've made forward progress
    2825                 :            :                 // (with the exception of shutdown due to hardware issues, low disk space, etc).
    2826                 :          0 :                 ConnectTrace connectTrace; // Destructed before cs_main is unlocked
    2827                 :            : 
    2828         [ +  + ]:      86737 :                 if (pindexMostWork == nullptr) {
    2829         [ +  - ]:      84683 :                     pindexMostWork = FindMostWorkChain();
    2830                 :            :                 }
    2831                 :            : 
    2832                 :            :                 // Whether we have anything to do at all.
    2833   [ +  -  +  +  :     173138 :                 if (pindexMostWork == nullptr || pindexMostWork == m_chain.Tip()) {
                   +  + ]
    2834                 :            :                     break;
    2835                 :            :                 }
    2836                 :            : 
    2837                 :      67897 :                 bool fInvalidFound = false;
    2838                 :      67896 :                 std::shared_ptr<const CBlock> nullBlockPtr;
    2839   [ +  +  +  -  :      68465 :                 if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace)) {
          +  +  +  -  +  
                      + ]
    2840                 :            :                     // A system error occurred
    2841         [ -  + ]:          1 :                     return false;
    2842                 :            :                 }
    2843                 :      67896 :                 blocks_connected = true;
    2844                 :            : 
    2845         [ +  + ]:      67896 :                 if (fInvalidFound) {
    2846                 :            :                     // Wipe cache, we may need another branch now.
    2847                 :       2758 :                     pindexMostWork = nullptr;
    2848                 :            :                 }
    2849         [ +  - ]:      67896 :                 pindexNewTip = m_chain.Tip();
    2850                 :            : 
    2851         [ +  + ]:     138231 :                 for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
    2852   [ +  -  -  + ]:      70335 :                     assert(trace.pblock && trace.pindex);
    2853   [ +  -  +  - ]:      70335 :                     GetMainSignals().BlockConnected(trace.pblock, trace.pindex);
    2854                 :            :                 }
    2855   [ +  -  -  +  :     154633 :             } while (!m_chain.Tip() || (starting_tip && CBlockIndexWorkComparator()(m_chain.Tip(), starting_tip)));
          -  +  +  +  +  
                -  +  + ]
    2856         [ +  + ]:      86643 :             if (!blocks_connected) return true;
    2857                 :            : 
    2858         [ +  - ]:      67803 :             const CBlockIndex* pindexFork = m_chain.FindFork(starting_tip);
    2859         [ +  - ]:      67803 :             bool fInitialDownload = IsInitialBlockDownload();
    2860                 :            : 
    2861                 :            :             // Notify external listeners about the new tip.
    2862                 :            :             // Enqueue while holding cs_main to ensure that UpdatedBlockTip is called in the order in which blocks are connected
    2863         [ +  + ]:      67803 :             if (pindexFork != pindexNewTip) {
    2864                 :            :                 // Notify ValidationInterface subscribers
    2865   [ +  -  +  - ]:      65045 :                 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
    2866                 :            : 
    2867                 :            :                 // Always notify the UI if a new block tip was connected
    2868         [ +  - ]:      65045 :                 uiInterface.NotifyBlockTip(GetSynchronizationState(fInitialDownload), pindexNewTip);
    2869                 :            :             }
    2870                 :            :         }
    2871                 :            :         // When we reach this point, we switched to a new tip (stored in pindexNewTip).
    2872                 :            : 
    2873   [ +  +  +  +  :      67803 :         if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
                   +  - ]
    2874                 :            : 
    2875                 :            :         // We check shutdown only after giving ActivateBestChainStep a chance to run once so that we
    2876                 :            :         // never shutdown before connecting the genesis block during LoadChainTip(). Previously this
    2877                 :            :         // caused an assert() failure during shutdown in such cases as the UTXO DB flushing checks
    2878                 :            :         // that the best block hash is non-null.
    2879   [ +  -  +  + ]:      67803 :         if (ShutdownRequested()) break;
    2880         [ +  + ]:      67773 :     } while (pindexNewTip != pindexMostWork);
    2881         [ +  - ]:      63084 :     CheckBlockIndex(chainparams.GetConsensus());
    2882                 :            : 
    2883                 :            :     // Write changes periodically to disk, after relay.
    2884   [ +  -  -  + ]:      63084 :     if (!FlushStateToDisk(chainparams, state, FlushStateMode::PERIODIC)) {
    2885                 :          0 :         return false;
    2886                 :            :     }
    2887                 :            : 
    2888                 :            :     return true;
    2889                 :            : }
    2890                 :            : 
    2891                 :        179 : bool ActivateBestChain(BlockValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
    2892   [ +  -  +  + ]:        187 :     return ::ChainstateActive().ActivateBestChain(state, chainparams, std::move(pblock));
    2893                 :            : }
    2894                 :            : 
    2895                 :          9 : bool CChainState::PreciousBlock(BlockValidationState& state, const CChainParams& params, CBlockIndex *pindex)
    2896                 :            : {
    2897                 :          9 :     {
    2898                 :          9 :         LOCK(cs_main);
    2899   [ +  -  +  -  :         18 :         if (pindex->nChainWork < m_chain.Tip()->nChainWork) {
                   +  + ]
    2900                 :            :             // Nothing to do, this block is not at the tip.
    2901         [ +  - ]:          1 :             return true;
    2902                 :            :         }
    2903   [ +  -  +  -  :         16 :         if (m_chain.Tip()->nChainWork > nLastPreciousChainwork) {
                   +  + ]
    2904                 :            :             // The chain has been extended since the last call, reset the counter.
    2905                 :          4 :             nBlockReverseSequenceId = -1;
    2906                 :            :         }
    2907         [ +  - ]:         16 :         nLastPreciousChainwork = m_chain.Tip()->nChainWork;
    2908         [ +  - ]:          8 :         setBlockIndexCandidates.erase(pindex);
    2909                 :          8 :         pindex->nSequenceId = nBlockReverseSequenceId;
    2910         [ +  - ]:          8 :         if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
    2911                 :            :             // We can't keep reducing the counter if somebody really wants to
    2912                 :            :             // call preciousblock 2**31-1 times on the same set of tips...
    2913                 :          8 :             nBlockReverseSequenceId--;
    2914                 :            :         }
    2915   [ +  -  +  -  :         16 :         if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->HaveTxsDownloaded()) {
             +  -  +  - ]
    2916         [ +  - ]:          8 :             setBlockIndexCandidates.insert(pindex);
    2917         [ +  - ]:          8 :             PruneBlockIndexCandidates();
    2918                 :            :         }
    2919                 :            :     }
    2920                 :            : 
    2921   [ +  -  -  + ]:         17 :     return ActivateBestChain(state, params, std::shared_ptr<const CBlock>());
    2922                 :            : }
    2923                 :          9 : bool PreciousBlock(BlockValidationState& state, const CChainParams& params, CBlockIndex *pindex) {
    2924                 :          9 :     return ::ChainstateActive().PreciousBlock(state, params, pindex);
    2925                 :            : }
    2926                 :            : 
    2927                 :         73 : bool CChainState::InvalidateBlock(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
    2928                 :            : {
    2929                 :         73 :     CBlockIndex* to_mark_failed = pindex;
    2930                 :         73 :     bool pindex_was_in_chain = false;
    2931                 :         73 :     int disconnected = 0;
    2932                 :            : 
    2933                 :            :     // We do not allow ActivateBestChain() to run while InvalidateBlock() is
    2934                 :            :     // running, as that could cause the tip to change while we disconnect
    2935                 :            :     // blocks.
    2936                 :        146 :     LOCK(m_cs_chainstate);
    2937                 :            : 
    2938                 :            :     // We'll be acquiring and releasing cs_main below, to allow the validation
    2939                 :            :     // callbacks to run. However, we should keep the block index in a
    2940                 :            :     // consistent state as we disconnect blocks -- in particular we need to
    2941                 :            :     // add equal-work blocks to setBlockIndexCandidates as we disconnect.
    2942                 :            :     // To avoid walking the block index repeatedly in search of candidates,
    2943                 :            :     // build a map once so that we can look up candidate blocks by chain
    2944                 :            :     // work as we go.
    2945   [ +  -  +  - ]:        146 :     std::multimap<const arith_uint256, CBlockIndex *> candidate_blocks_by_work;
    2946                 :            : 
    2947                 :         73 :     {
    2948         [ +  - ]:         73 :         LOCK(cs_main);
    2949         [ +  + ]:      25925 :         for (const auto& entry : m_blockman.m_block_index) {
    2950                 :      25852 :             CBlockIndex *candidate = entry.second;
    2951                 :            :             // We don't need to put anything in our active chain into the
    2952                 :            :             // multimap, because those candidates will be found and considered
    2953                 :            :             // as we disconnect.
    2954                 :            :             // Instead, consider only non-active-chain blocks that have at
    2955                 :            :             // least as much work as where we expect the new tip to end up.
    2956         [ +  + ]:       1155 :             if (!m_chain.Contains(candidate) &&
    2957         [ +  - ]:       1155 :                     !CBlockIndexWorkComparator()(candidate, pindex->pprev) &&
    2958   [ +  +  +  +  :      26217 :                     candidate->IsValid(BLOCK_VALID_TRANSACTIONS) &&
             +  +  +  - ]
    2959         [ +  - ]:         10 :                     candidate->HaveTxsDownloaded()) {
    2960   [ +  +  +  - ]:      25942 :                 candidate_blocks_by_work.insert(std::make_pair(candidate->nChainWork, candidate));
    2961                 :            :             }
    2962                 :            :         }
    2963                 :            :     }
    2964                 :            : 
    2965                 :            :     // Disconnect (descendants of) pindex, and mark them invalid.
    2966                 :       1358 :     while (true) {
    2967         [ +  - ]:       1358 :         if (ShutdownRequested()) break;
    2968                 :            : 
    2969                 :            :         // Make sure the queue of validation callbacks doesn't grow unboundedly.
    2970         [ +  - ]:       1358 :         LimitValidationInterfaceQueue();
    2971                 :            : 
    2972   [ +  -  +  - ]:       2716 :         LOCK(cs_main);
    2973   [ +  -  +  - ]:       2643 :         LOCK(m_mempool.cs); // Lock for as long as disconnectpool is in scope to make sure UpdateMempoolForReorg is called after DisconnectTip without unlocking in between
    2974         [ +  + ]:       1358 :         if (!m_chain.Contains(pindex)) break;
    2975                 :       1285 :         pindex_was_in_chain = true;
    2976         [ +  - ]:       1285 :         CBlockIndex *invalid_walk_tip = m_chain.Tip();
    2977                 :            : 
    2978                 :            :         // ActivateBestChain considers blocks already in m_chain
    2979                 :            :         // unconditionally valid already, so force disconnect away from it.
    2980   [ +  -  +  - ]:       2570 :         DisconnectedBlockTransactions disconnectpool;
    2981         [ +  - ]:       1285 :         bool ret = DisconnectTip(state, chainparams, &disconnectpool);
    2982                 :            :         // DisconnectTip will add transactions to disconnectpool.
    2983                 :            :         // Adjust the mempool to be consistent with the new tip, adding
    2984                 :            :         // transactions back to the mempool if disconnecting was successful,
    2985                 :            :         // and we're not doing a very deep invalidation (in which case
    2986                 :            :         // keeping the mempool up to date is probably futile anyway).
    2987   [ +  +  -  +  :       2383 :         UpdateMempoolForReorg(m_mempool, disconnectpool, /* fAddToMempool = */ (++disconnected <= 10) && ret);
                   +  - ]
    2988   [ -  +  -  - ]:       1285 :         if (!ret) return false;
    2989   [ +  -  -  + ]:       2570 :         assert(invalid_walk_tip->pprev == m_chain.Tip());
    2990                 :            : 
    2991                 :            :         // We immediately mark the disconnected blocks as invalid.
    2992                 :            :         // This prevents a case where pruned nodes may fail to invalidateblock
    2993                 :            :         // and be left unable to start as they have no tip candidates (as there
    2994                 :            :         // are no blocks that meet the "have data and are not invalid per
    2995                 :            :         // nStatus" criteria for inclusion in setBlockIndexCandidates).
    2996                 :       1285 :         invalid_walk_tip->nStatus |= BLOCK_FAILED_VALID;
    2997         [ +  - ]:       1285 :         setDirtyBlockIndex.insert(invalid_walk_tip);
    2998         [ +  - ]:       1285 :         setBlockIndexCandidates.erase(invalid_walk_tip);
    2999         [ +  - ]:       1285 :         setBlockIndexCandidates.insert(invalid_walk_tip->pprev);
    3000   [ +  +  -  + ]:       1285 :         if (invalid_walk_tip->pprev == to_mark_failed && (to_mark_failed->nStatus & BLOCK_FAILED_VALID)) {
    3001                 :            :             // We only want to mark the last disconnected block as BLOCK_FAILED_VALID; its children
    3002                 :            :             // need to be BLOCK_FAILED_CHILD instead.
    3003                 :          0 :             to_mark_failed->nStatus = (to_mark_failed->nStatus ^ BLOCK_FAILED_VALID) | BLOCK_FAILED_CHILD;
    3004         [ #  # ]:          0 :             setDirtyBlockIndex.insert(to_mark_failed);
    3005                 :            :         }
    3006                 :            : 
    3007                 :            :         // Add any equal or more work headers to setBlockIndexCandidates
    3008         [ +  - ]:       1285 :         auto candidate_it = candidate_blocks_by_work.lower_bound(invalid_walk_tip->pprev->nChainWork);
    3009                 :       1295 :         while (candidate_it != candidate_blocks_by_work.end()) {
    3010   [ +  -  +  - ]:         10 :             if (!CBlockIndexWorkComparator()(candidate_it->second, invalid_walk_tip->pprev)) {
    3011         [ +  - ]:         10 :                 setBlockIndexCandidates.insert(candidate_it->second);
    3012                 :         10 :                 candidate_it = candidate_blocks_by_work.erase(candidate_it);
    3013                 :            :             } else {
    3014         [ +  + ]:       1295 :                 ++candidate_it;
    3015                 :            :             }
    3016                 :            :         }
    3017                 :            : 
    3018                 :            :         // Track the last disconnected block, so we can correct its BLOCK_FAILED_CHILD status in future
    3019                 :            :         // iterations, or, if it's the last one, call InvalidChainFound on it.
    3020                 :       1285 :         to_mark_failed = invalid_walk_tip;
    3021                 :            :     }
    3022                 :            : 
    3023         [ +  - ]:         73 :     CheckBlockIndex(chainparams.GetConsensus());
    3024                 :            : 
    3025                 :         73 :     {
    3026         [ +  - ]:         73 :         LOCK(cs_main);
    3027         [ -  + ]:         73 :         if (m_chain.Contains(to_mark_failed)) {
    3028                 :            :             // If the to-be-marked invalid block is in the active chain, something is interfering and we can't proceed.
    3029         [ -  - ]:         73 :             return false;
    3030                 :            :         }
    3031                 :            : 
    3032                 :            :         // Mark pindex (or the last disconnected block) as invalid, even when it never was in the main chain
    3033                 :         73 :         to_mark_failed->nStatus |= BLOCK_FAILED_VALID;
    3034         [ +  - ]:         73 :         setDirtyBlockIndex.insert(to_mark_failed);
    3035         [ +  - ]:         73 :         setBlockIndexCandidates.erase(to_mark_failed);
    3036         [ +  - ]:         73 :         m_blockman.m_failed_blocks.insert(to_mark_failed);
    3037                 :            : 
    3038                 :            :         // If any new blocks somehow arrived while we were disconnecting
    3039                 :            :         // (above), then the pre-calculation of what should go into
    3040                 :            :         // setBlockIndexCandidates may have missed entries. This would
    3041                 :            :         // technically be an inconsistency in the block index, but if we clean
    3042                 :            :         // it up here, this should be an essentially unobservable error.
    3043                 :            :         // Loop back over all block index entries and add any missing entries
    3044                 :            :         // to setBlockIndexCandidates.
    3045                 :         73 :         BlockMap::iterator it = m_blockman.m_block_index.begin();
    3046                 :      25925 :         while (it != m_blockman.m_block_index.end()) {
    3047   [ +  +  +  +  :      49864 :             if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->HaveTxsDownloaded() && !setBlockIndexCandidates.value_comp()(it->second, m_chain.Tip())) {
          +  -  +  -  +  
                -  +  + ]
    3048         [ +  - ]:         83 :                 setBlockIndexCandidates.insert(it->second);
    3049                 :            :             }
    3050         [ +  + ]:      25925 :             it++;
    3051                 :            :         }
    3052                 :            : 
    3053         [ +  - ]:         73 :         InvalidChainFound(to_mark_failed);
    3054                 :            :     }
    3055                 :            : 
    3056                 :            :     // Only notify about a new block tip if the active chain was modified.
    3057         [ +  + ]:         73 :     if (pindex_was_in_chain) {
    3058   [ +  -  +  - ]:         72 :         uiInterface.NotifyBlockTip(GetSynchronizationState(IsInitialBlockDownload()), to_mark_failed->pprev);
    3059                 :            :     }
    3060                 :            :     return true;
    3061                 :            : }
    3062                 :            : 
    3063                 :         63 : bool InvalidateBlock(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex) {
    3064                 :         63 :     return ::ChainstateActive().InvalidateBlock(state, chainparams, pindex);
    3065                 :            : }
    3066                 :            : 
    3067                 :          9 : void CChainState::ResetBlockFailureFlags(CBlockIndex *pindex) {
    3068                 :          9 :     AssertLockHeld(cs_main);
    3069                 :            : 
    3070                 :          9 :     int nHeight = pindex->nHeight;
    3071                 :            : 
    3072                 :            :     // Remove the invalidity flag from this block and all its descendants.
    3073                 :          9 :     BlockMap::iterator it = m_blockman.m_block_index.begin();
    3074                 :       1305 :     while (it != m_blockman.m_block_index.end()) {
    3075   [ +  +  +  +  :       1296 :         if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
                   +  + ]
    3076                 :        213 :             it->second->nStatus &= ~BLOCK_FAILED_MASK;
    3077                 :        213 :             setDirtyBlockIndex.insert(it->second);
    3078   [ +  -  +  -  :        426 :             if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->HaveTxsDownloaded() && setBlockIndexCandidates.value_comp()(m_chain.Tip(), it->second)) {
          +  -  +  -  +  
                      - ]
    3079                 :        213 :                 setBlockIndexCandidates.insert(it->second);
    3080                 :            :             }
    3081         [ +  + ]:        213 :             if (it->second == pindexBestInvalid) {
    3082                 :            :                 // Reset invalid block marker if it was pointing to one of those.
    3083                 :          8 :                 pindexBestInvalid = nullptr;
    3084                 :            :             }
    3085                 :        213 :             m_blockman.m_failed_blocks.erase(it->second);
    3086                 :            :         }
    3087         [ +  + ]:       1305 :         it++;
    3088                 :            :     }
    3089                 :            : 
    3090                 :            :     // Remove the invalidity flag from all ancestors too.
    3091         [ +  + ]:       1085 :     while (pindex != nullptr) {
    3092         [ +  + ]:       1076 :         if (pindex->nStatus & BLOCK_FAILED_MASK) {
    3093                 :          1 :             pindex->nStatus &= ~BLOCK_FAILED_MASK;
    3094                 :          1 :             setDirtyBlockIndex.insert(pindex);
    3095                 :          1 :             m_blockman.m_failed_blocks.erase(pindex);
    3096                 :            :         }
    3097                 :       1076 :         pindex = pindex->pprev;
    3098                 :            :     }
    3099                 :          9 : }
    3100                 :            : 
    3101                 :          9 : void ResetBlockFailureFlags(CBlockIndex *pindex) {
    3102                 :          9 :     return ::ChainstateActive().ResetBlockFailureFlags(pindex);
    3103                 :            : }
    3104                 :            : 
    3105                 :      73757 : CBlockIndex* BlockManager::AddToBlockIndex(const CBlockHeader& block)
    3106                 :            : {
    3107                 :      73757 :     AssertLockHeld(cs_main);
    3108                 :            : 
    3109                 :            :     // Check for duplicate
    3110                 :      73757 :     uint256 hash = block.GetHash();
    3111                 :      73757 :     BlockMap::iterator it = m_block_index.find(hash);
    3112         [ +  + ]:      73757 :     if (it != m_block_index.end())
    3113                 :          3 :         return it->second;
    3114                 :            : 
    3115                 :            :     // Construct new block index object
    3116                 :      73754 :     CBlockIndex* pindexNew = new CBlockIndex(block);
    3117                 :            :     // We assign the sequence id to blocks only when the full data is available,
    3118                 :            :     // to avoid miners withholding blocks but broadcasting headers, to get a
    3119                 :            :     // competitive advantage.
    3120                 :      73754 :     pindexNew->nSequenceId = 0;
    3121                 :      73754 :     BlockMap::iterator mi = m_block_index.insert(std::make_pair(hash, pindexNew)).first;
    3122                 :      73754 :     pindexNew->phashBlock = &((*mi).first);
    3123                 :      73754 :     BlockMap::iterator miPrev = m_block_index.find(block.hashPrevBlock);
    3124         [ +  + ]:      73754 :     if (miPrev != m_block_index.end())
    3125                 :            :     {
    3126                 :      73420 :         pindexNew->pprev = (*miPrev).second;
    3127                 :      73420 :         pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
    3128                 :      73420 :         pindexNew->BuildSkip();
    3129                 :            :     }
    3130   [ +  +  +  + ]:     106601 :     pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
    3131         [ +  + ]:     221262 :     pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
    3132                 :      73754 :     pindexNew->RaiseValidity(BLOCK_VALID_TREE);
    3133   [ +  +  +  + ]:      73754 :     if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork)
    3134                 :      70155 :         pindexBestHeader = pindexNew;
    3135                 :            : 
    3136                 :      73754 :     setDirtyBlockIndex.insert(pindexNew);
    3137                 :            : 
    3138                 :      73754 :     return pindexNew;
    3139                 :            : }
    3140                 :            : 
    3141                 :            : /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
    3142                 :      71072 : void CChainState::ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos, const Consensus::Params& consensusParams)
    3143                 :            : {
    3144         [ +  + ]:      71072 :     pindexNew->nTx = block.vtx.size();
    3145                 :      71072 :     pindexNew->nChainTx = 0;
    3146                 :      71072 :     pindexNew->nFile = pos.nFile;
    3147                 :      71072 :     pindexNew->nDataPos = pos.nPos;
    3148                 :      71072 :     pindexNew->nUndoPos = 0;
    3149                 :      71072 :     pindexNew->nStatus |= BLOCK_HAVE_DATA;
    3150         [ +  + ]:      71072 :     if (IsWitnessEnabled(pindexNew->pprev, consensusParams)) {
    3151                 :      67362 :         pindexNew->nStatus |= BLOCK_OPT_WITNESS;
    3152                 :            :     }
    3153                 :      71072 :     pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
    3154                 :      71072 :     setDirtyBlockIndex.insert(pindexNew);
    3155                 :            : 
    3156   [ +  +  +  + ]:      71072 :     if (pindexNew->pprev == nullptr || pindexNew->pprev->HaveTxsDownloaded()) {
    3157                 :            :         // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
    3158                 :     141202 :         std::deque<CBlockIndex*> queue;
    3159         [ +  - ]:      70601 :         queue.push_back(pindexNew);
    3160                 :            : 
    3161                 :            :         // Recursively process any descendant blocks that now may be eligible to be connected.
    3162         [ +  + ]:     141935 :         while (!queue.empty()) {
    3163                 :      71334 :             CBlockIndex *pindex = queue.front();
    3164                 :      71334 :             queue.pop_front();
    3165         [ +  + ]:      71334 :             pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
    3166                 :      71334 :             {
    3167         [ +  - ]:      71334 :                 LOCK(cs_nBlockSequenceId);
    3168         [ +  - ]:      71334 :                 pindex->nSequenceId = nBlockSequenceId++;
    3169                 :            :             }
    3170   [ +  +  +  -  :      71334 :             if (m_chain.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, m_chain.Tip())) {
             +  -  +  + ]
    3171         [ +  - ]:      67570 :                 setBlockIndexCandidates.insert(pindex);
    3172                 :            :             }
    3173                 :      71334 :             std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = m_blockman.m_blocks_unlinked.equal_range(pindex);
    3174                 :      72067 :             while (range.first != range.second) {
    3175                 :        733 :                 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
    3176         [ +  - ]:        733 :                 queue.push_back(it->second);
    3177                 :        733 :                 range.first++;
    3178         [ +  + ]:      72800 :                 m_blockman.m_blocks_unlinked.erase(it);
    3179                 :            :             }
    3180                 :            :         }
    3181                 :            :     } else {
    3182   [ +  -  +  - ]:        471 :         if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
    3183                 :        471 :             m_blockman.m_blocks_unlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
    3184                 :            :         }
    3185                 :            :     }
    3186                 :      71072 : }
    3187                 :            : 
    3188                 :      71072 : static bool FindBlockPos(FlatFilePos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
    3189                 :            : {
    3190                 :     142144 :     LOCK(cs_LastBlockFile);
    3191                 :            : 
    3192         [ +  + ]:      71072 :     unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
    3193         [ +  + ]:      71072 :     if (vinfoBlockFile.size() <= nFile) {
    3194         [ +  - ]:         98 :         vinfoBlockFile.resize(nFile + 1);
    3195                 :            :     }
    3196                 :            : 
    3197                 :      71072 :     bool finalize_undo = false;
    3198         [ +  + ]:      71072 :     if (!fKnown) {
    3199         [ +  + ]:      69798 :         while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
    3200                 :            :             // when the undo file is keeping up with the block file, we want to flush it explicitly
    3201                 :            :             // when it is lagging behind (more blocks arrive than are being connected), we let the
    3202                 :            :             // undo block write case handle it
    3203   [ +  -  +  - ]:         48 :             finalize_undo = (vinfoBlockFile[nFile].nHeightLast == (unsigned int)ChainActive().Tip()->nHeight);
    3204                 :         48 :             nFile++;
    3205         [ -  + ]:         48 :             if (vinfoBlockFile.size() <= nFile) {
    3206         [ +  - ]:         48 :                 vinfoBlockFile.resize(nFile + 1);
    3207                 :            :             }
    3208                 :            :         }
    3209                 :      69750 :         pos.nFile = nFile;
    3210                 :      69750 :         pos.nPos = vinfoBlockFile[nFile].nSize;
    3211                 :            :     }
    3212                 :            : 
    3213         [ +  + ]:      71072 :     if ((int)nFile != nLastBlockFile) {
    3214         [ +  - ]:         48 :         if (!fKnown) {
    3215   [ +  -  +  - ]:         48 :             LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
    3216                 :            :         }
    3217         [ +  - ]:         48 :         FlushBlockFile(!fKnown, finalize_undo);
    3218                 :         48 :         nLastBlockFile = nFile;
    3219                 :            :     }
    3220                 :            : 
    3221                 :      71072 :     vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
    3222         [ +  + ]:      71072 :     if (fKnown)
    3223         [ -  + ]:       1322 :         vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
    3224                 :            :     else
    3225                 :      69750 :         vinfoBlockFile[nFile].nSize += nAddSize;
    3226                 :            : 
    3227         [ +  + ]:      71072 :     if (!fKnown) {
    3228                 :      69750 :         bool out_of_space;
    3229   [ +  -  +  - ]:      69750 :         size_t bytes_allocated = BlockFileSeq().Allocate(pos, nAddSize, out_of_space);
    3230         [ -  + ]:      69750 :         if (out_of_space) {
    3231   [ -  -  -  -  :      71072 :             return AbortNode("Disk space is too low!", _("Disk space is too low!"));
             -  -  +  - ]
    3232                 :            :         }
    3233   [ +  +  +  + ]:      69750 :         if (bytes_allocated != 0 && fPruneMode) {
    3234                 :        126 :             fCheckForPruning = true;
    3235                 :            :         }
    3236                 :            :     }
    3237                 :            : 
    3238         [ +  - ]:      71072 :     setDirtyFileInfo.insert(nFile);
    3239                 :            :     return true;
    3240                 :            : }
    3241                 :            : 
    3242                 :      67919 : static bool FindUndoPos(BlockValidationState &state, int nFile, FlatFilePos &pos, unsigned int nAddSize)
    3243                 :            : {
    3244                 :      67919 :     pos.nFile = nFile;
    3245                 :            : 
    3246                 :     135838 :     LOCK(cs_LastBlockFile);
    3247                 :            : 
    3248         [ +  - ]:      67919 :     pos.nPos = vinfoBlockFile[nFile].nUndoSize;
    3249                 :      67919 :     vinfoBlockFile[nFile].nUndoSize += nAddSize;
    3250         [ +  - ]:      67919 :     setDirtyFileInfo.insert(nFile);
    3251                 :            : 
    3252                 :      67919 :     bool out_of_space;
    3253   [ +  -  +  - ]:      67919 :     size_t bytes_allocated = UndoFileSeq().Allocate(pos, nAddSize, out_of_space);
    3254         [ -  + ]:      67919 :     if (out_of_space) {
    3255   [ -  -  -  -  :      67919 :         return AbortNode(state, "Disk space is too low!", _("Disk space is too low!"));
             -  -  +  - ]
    3256                 :            :     }
    3257   [ +  +  +  + ]:      67919 :     if (bytes_allocated != 0 && fPruneMode) {
    3258                 :         17 :         fCheckForPruning = true;
    3259                 :            :     }
    3260                 :            : 
    3261                 :            :     return true;
    3262                 :            : }
    3263                 :            : 
    3264                 :     210277 : static bool CheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
    3265                 :            : {
    3266                 :            :     // Check proof of work matches claimed amount
    3267   [ +  +  +  + ]:     210277 :     if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
    3268   [ +  -  +  - ]:     210278 :         return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "high-hash", "proof of work failed");
    3269                 :            : 
    3270                 :            :     return true;
    3271                 :            : }
    3272                 :            : 
    3273                 :     305234 : bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
    3274                 :            : {
    3275                 :            :     // These are checks that are independent of context.
    3276                 :            : 
    3277         [ +  + ]:     305234 :     if (block.fChecked)
    3278                 :            :         return true;
    3279                 :            : 
    3280                 :            :     // Check that the header is valid (particularly PoW).  This is mostly
    3281                 :            :     // redundant with the call in AcceptBlockHeader.
    3282         [ +  + ]:     136835 :     if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
    3283                 :            :         return false;
    3284                 :            : 
    3285                 :            :     // Signet only: check block solution
    3286   [ +  +  +  +  :     136834 :     if (consensusParams.signet_blocks && fCheckPOW && !CheckSignetBlockSolution(block, consensusParams)) {
                   +  + ]
    3287   [ +  -  +  - ]:          1 :         return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-signet-blksig", "signet block signature validation failure");
    3288                 :            :     }
    3289                 :            : 
    3290                 :            :     // Check the merkle root.
    3291         [ +  + ]:     136833 :     if (fCheckMerkleRoot) {
    3292                 :      83341 :         bool mutated;
    3293                 :      83341 :         uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
    3294         [ +  + ]:      83341 :         if (block.hashMerkleRoot != hashMerkleRoot2)
    3295   [ +  -  +  - ]:         11 :             return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-txnmrklroot", "hashMerkleRoot mismatch");
    3296                 :            : 
    3297                 :            :         // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
    3298                 :            :         // of transactions in a block without affecting the merkle root of a block,
    3299                 :            :         // while still invalidating it.
    3300         [ +  + ]:      83330 :         if (mutated)
    3301   [ +  -  +  - ]:         65 :             return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-txns-duplicate", "duplicate transaction");
    3302                 :            :     }
    3303                 :            : 
    3304                 :            :     // All potential-corruption validation must be done before we do any
    3305                 :            :     // transaction validation, as otherwise we may mark the header as invalid
    3306                 :            :     // because we receive the wrong transactions for it.
    3307                 :            :     // Note that witness malleability is checked in ContextualCheckBlock, so no
    3308                 :            :     // checks that use witness data may be performed here.
    3309                 :            : 
    3310                 :            :     // Size limits
    3311   [ +  +  +  -  :     136757 :     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)
                   +  + ]
    3312   [ +  -  +  - ]:          2 :         return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-length", "size limits failed");
    3313                 :            : 
    3314                 :            :     // First transaction must be coinbase, the rest must not be
    3315   [ +  -  +  + ]:     136755 :     if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
    3316   [ +  -  +  - ]:          2 :         return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-missing", "first tx is not coinbase");
    3317         [ +  + ]:     631128 :     for (unsigned int i = 1; i < block.vtx.size(); i++)
    3318         [ +  + ]:     494377 :         if (block.vtx[i]->IsCoinBase())
    3319   [ +  -  +  - ]:     305236 :             return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-multiple", "more than one coinbase");
    3320                 :            : 
    3321                 :            :     // Check transactions
    3322                 :            :     // Must check for duplicate inputs (see CVE-2018-17144)
    3323         [ +  + ]:     767745 :     for (const auto& tx : block.vtx) {
    3324         [ +  - ]:    1262118 :         TxValidationState tx_state;
    3325   [ +  -  +  + ]:     631124 :         if (!CheckTransaction(*tx, tx_state)) {
    3326                 :            :             // CheckBlock() does context-free validation checks. The only
    3327                 :            :             // possible failures are consensus failures.
    3328         [ -  + ]:        130 :             assert(tx_state.GetResult() == TxValidationResult::TX_CONSENSUS);
    3329   [ +  -  +  - ]:        260 :             return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, tx_state.GetRejectReason(),
    3330   [ +  -  +  - ]:        260 :                                  strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), tx_state.GetDebugMessage()));
    3331                 :            :         }
    3332                 :            :     }
    3333                 :     136621 :     unsigned int nSigOps = 0;
    3334         [ +  + ]:     767419 :     for (const auto& tx : block.vtx)
    3335                 :            :     {
    3336                 :     630798 :         nSigOps += GetLegacySigOpCount(*tx);
    3337                 :            :     }
    3338         [ +  + ]:     136621 :     if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
    3339   [ +  -  +  - ]:     305242 :         return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-sigops", "out-of-bounds SigOpCount");
    3340                 :            : 
    3341         [ +  + ]:     136613 :     if (fCheckPOW && fCheckMerkleRoot)
    3342                 :      83120 :         block.fChecked = true;
    3343                 :            : 
    3344                 :            :     return true;
    3345                 :            : }
    3346                 :            : 
    3347                 :     711265 : bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
    3348                 :            : {
    3349         [ +  + ]:     711265 :     int height = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
    3350                 :     711265 :     return (height >= params.SegwitHeight);
    3351                 :            : }
    3352                 :            : 
    3353                 :      35538 : void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
    3354                 :            : {
    3355                 :      35538 :     int commitpos = GetWitnessCommitmentIndex(block);
    3356   [ +  +  +  -  :      35538 :     static const std::vector<unsigned char> nonce(32, 0x00);
                   +  - ]
    3357   [ +  +  +  +  :      35538 :     if (commitpos != NO_WITNESS_COMMITMENT && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
                   +  + ]
    3358                 :      26170 :         CMutableTransaction tx(*block.vtx[0]);
    3359         [ +  - ]:      26170 :         tx.vin[0].scriptWitness.stack.resize(1);
    3360         [ +  - ]:      26170 :         tx.vin[0].scriptWitness.stack[0] = nonce;
    3361   [ +  -  -  + ]:      52340 :         block.vtx[0] = MakeTransactionRef(std::move(tx));
    3362                 :            :     }
    3363                 :      35538 : }
    3364                 :            : 
    3365                 :      29951 : std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
    3366                 :            : {
    3367                 :      29951 :     std::vector<unsigned char> commitment;
    3368                 :      29951 :     int commitpos = GetWitnessCommitmentIndex(block);
    3369         [ +  - ]:      29951 :     std::vector<unsigned char> ret(32, 0x00);
    3370         [ +  + ]:      29951 :     if (consensusParams.SegwitHeight != std::numeric_limits<int>::max()) {
    3371         [ +  - ]:      29950 :         if (commitpos == NO_WITNESS_COMMITMENT) {
    3372         [ +  - ]:      29950 :             uint256 witnessroot = BlockWitnessMerkleRoot(block, nullptr);
    3373   [ +  -  +  -  :      29950 :             CHash256().Write(witnessroot).Write(ret).Finalize(witnessroot);
             +  -  +  - ]
    3374                 :      29950 :             CTxOut out;
    3375                 :      29950 :             out.nValue = 0;
    3376                 :      29950 :             out.scriptPubKey.resize(MINIMUM_WITNESS_COMMITMENT);
    3377         [ +  - ]:      29950 :             out.scriptPubKey[0] = OP_RETURN;
    3378         [ +  - ]:      29950 :             out.scriptPubKey[1] = 0x24;
    3379         [ +  - ]:      29950 :             out.scriptPubKey[2] = 0xaa;
    3380         [ +  - ]:      29950 :             out.scriptPubKey[3] = 0x21;
    3381         [ +  - ]:      29950 :             out.scriptPubKey[4] = 0xa9;
    3382         [ +  - ]:      29950 :             out.scriptPubKey[5] = 0xed;
    3383   [ +  -  +  - ]:      59900 :             memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
    3384   [ +  -  +  -  :      89850 :             commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
                   +  - ]
    3385         [ +  - ]:      59900 :             CMutableTransaction tx(*block.vtx[0]);
    3386         [ +  - ]:      29950 :             tx.vout.push_back(out);
    3387   [ +  -  -  + ]:      59900 :             block.vtx[0] = MakeTransactionRef(std::move(tx));
    3388                 :            :         }
    3389                 :            :     }
    3390         [ +  - ]:      29951 :     UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
    3391                 :      29951 :     return commitment;
    3392                 :            : }
    3393                 :            : 
    3394                 :            : //! Returns last CBlockIndex* that is a checkpoint
    3395                 :     100057 : static CBlockIndex* GetLastCheckpoint(const CCheckpointData& data) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
    3396                 :            : {
    3397                 :     100057 :     const MapCheckpoints& checkpoints = data.mapCheckpoints;
    3398                 :            : 
    3399         [ +  + ]:     200662 :     for (const MapCheckpoints::value_type& i : reverse_iterate(checkpoints))
    3400                 :            :     {
    3401                 :     100046 :         const uint256& hash = i.second;
    3402                 :     100046 :         CBlockIndex* pindex = LookupBlockIndex(hash);
    3403         [ +  + ]:     100046 :         if (pindex) {
    3404                 :            :             return pindex;
    3405                 :            :         }
    3406                 :            :     }
    3407                 :            :     return nullptr;
    3408                 :            : }
    3409                 :            : 
    3410                 :            : /** Context-dependent validity checks.
    3411                 :            :  *  By "context", we mean only the previous block headers, but not the UTXO
    3412                 :            :  *  set; UTXO-related validity checks are done in ConnectBlock().
    3413                 :            :  *  NOTE: This function is not currently invoked by ConnectBlock(), so we
    3414                 :            :  *  should consider upgrade issues if we change which consensus rules are
    3415                 :            :  *  enforced in this function (eg by adding a new consensus rule). See comment
    3416                 :            :  *  in ConnectBlock().
    3417                 :            :  *  Note that -reindex-chainstate skips the validation that happens here!
    3418                 :            :  */
    3419                 :     100190 : static bool ContextualCheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
    3420                 :            : {
    3421         [ -  + ]:     100190 :     assert(pindexPrev != nullptr);
    3422                 :     100190 :     const int nHeight = pindexPrev->nHeight + 1;
    3423                 :            : 
    3424                 :            :     // Check proof of work
    3425                 :     100190 :     const Consensus::Params& consensusParams = params.GetConsensus();
    3426         [ +  + ]:     100190 :     if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
    3427   [ +  -  +  - ]:          2 :         return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "bad-diffbits", "incorrect proof of work");
    3428                 :            : 
    3429                 :            :     // Check against checkpoints
    3430         [ +  + ]:     100188 :     if (fCheckpointsEnabled) {
    3431                 :            :         // Don't accept any forks from the main chain prior to last checkpoint.
    3432                 :            :         // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
    3433                 :            :         // BlockIndex().
    3434                 :     100057 :         CBlockIndex* pcheckpoint = GetLastCheckpoint(params.Checkpoints());
    3435   [ +  +  +  + ]:     100057 :         if (pcheckpoint && nHeight < pcheckpoint->nHeight) {
    3436                 :          1 :             LogPrintf("ERROR: %s: forked chain older than last checkpoint (height %d)\n", __func__, nHeight);
    3437   [ +  -  +  - ]:          1 :             return state.Invalid(BlockValidationResult::BLOCK_CHECKPOINT, "bad-fork-prior-to-checkpoint");
    3438                 :            :         }
    3439                 :            :     }
    3440                 :            : 
    3441                 :            :     // Check timestamp against prev
    3442         [ +  + ]:     100187 :     if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
    3443   [ +  -  +  - ]:     100196 :         return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "time-too-old", "block's timestamp is too early");
    3444                 :            : 
    3445                 :            :     // Check timestamp
    3446         [ +  + ]:     100181 :     if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
    3447   [ +  -  +  - ]:          4 :         return state.Invalid(BlockValidationResult::BLOCK_TIME_FUTURE, "time-too-new", "block timestamp too far in the future");
    3448                 :            : 
    3449                 :            :     // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
    3450                 :            :     // check for version 2, 3 and 4 upgrades
    3451   [ +  +  +  +  :     100177 :     if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
                   +  + ]
    3452   [ +  +  +  + ]:     100176 :        (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
    3453         [ +  + ]:       1929 :        (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
    3454   [ +  -  +  - ]:          3 :             return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, strprintf("bad-version(0x%08x)", block.nVersion),
    3455                 :     100193 :                                  strprintf("rejected nVersion=0x%08x block", block.nVersion));
    3456                 :            : 
    3457                 :            :     return true;
    3458                 :            : }
    3459                 :            : 
    3460                 :            : /** NOTE: This function is not currently invoked by ConnectBlock(), so we
    3461                 :            :  *  should consider upgrade issues if we change which consensus rules are
    3462                 :            :  *  enforced in this function (eg by adding a new consensus rule). See comment
    3463                 :            :  *  in ConnectBlock().
    3464                 :            :  *  Note that -reindex-chainstate skips the validation that happens here!
    3465                 :            :  */
    3466                 :      97511 : static bool ContextualCheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
    3467                 :            : {
    3468         [ +  + ]:      97511 :     const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
    3469                 :            : 
    3470                 :            :     // Start enforcing BIP113 (Median Time Past).
    3471                 :      97511 :     int nLockTimeFlags = 0;
    3472         [ +  + ]:      97511 :     if (nHeight >= consensusParams.CSVHeight) {
    3473         [ -  + ]:      31255 :         assert(pindexPrev != nullptr);
    3474                 :            :         nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
    3475                 :            :     }
    3476                 :            : 
    3477                 :      97511 :     int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
    3478         [ +  + ]:      97511 :                               ? pindexPrev->GetMedianTimePast()
    3479                 :      66256 :                               : block.GetBlockTime();
    3480                 :            : 
    3481                 :            :     // Check that all transactions are finalized
    3482         [ +  + ]:     514712 :     for (const auto& tx : block.vtx) {
    3483         [ +  + ]:     417208 :         if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
    3484   [ +  -  +  - ]:          7 :             return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-nonfinal", "non-final transaction");
    3485                 :            :         }
    3486                 :            :     }
    3487                 :            : 
    3488                 :            :     // Enforce rule that the coinbase starts with serialized block height
    3489         [ +  + ]:      97504 :     if (nHeight >= consensusParams.BIP34Height)
    3490                 :            :     {
    3491         [ +  - ]:      28812 :         CScript expect = CScript() << nHeight;
    3492   [ -  +  -  +  :      57623 :         if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
             +  +  -  + ]
    3493   [ +  -  -  + ]:      57622 :             !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
    3494   [ +  -  +  -  :          1 :             return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-height", "block height mismatch in coinbase");
                   +  - ]
    3495                 :            :         }
    3496                 :            :     }
    3497                 :            : 
    3498                 :            :     // Validation for witness commitments.
    3499                 :            :     // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
    3500                 :            :     //   coinbase (where 0x0000....0000 is used instead).
    3501                 :            :     // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness reserved value (unconstrained).
    3502                 :            :     // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
    3503                 :            :     // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
    3504                 :            :     //   {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness reserved value). In case there are
    3505                 :            :     //   multiple, the last one is used.
    3506                 :      97503 :     bool fHaveWitness = false;
    3507         [ +  + ]:      97503 :     if (nHeight >= consensusParams.SegwitHeight) {
    3508                 :      92439 :         int commitpos = GetWitnessCommitmentIndex(block);
    3509         [ +  + ]:      92439 :         if (commitpos != NO_WITNESS_COMMITMENT) {
    3510                 :      80153 :             bool malleated = false;
    3511                 :      80153 :             uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
    3512                 :            :             // The malleation check is ignored; as the transaction tree itself
    3513                 :            :             // already does not permit it, it is impossible to trigger in the
    3514                 :            :             // witness tree.
    3515   [ +  +  +  - ]:      80153 :             if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
    3516   [ +  -  +  - ]:          2 :                 return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-witness-nonce-size", strprintf("%s : invalid witness reserved value size", __func__));
    3517                 :            :             }
    3518                 :      80151 :             CHash256().Write(hashWitness).Write(block.vtx[0]->vin[0].scriptWitness.stack[0]).Finalize(hashWitness);
    3519   [ -  +  +  + ]:     160302 :             if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
    3520   [ +  -  +  - ]:          3 :                 return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-witness-merkle-match", strprintf("%s : witness merkle commitment mismatch", __func__));
    3521                 :            :             }
    3522                 :            :             fHaveWitness = true;
    3523                 :            :         }
    3524                 :            :     }
    3525                 :            : 
    3526                 :            :     // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
    3527                 :            :     if (!fHaveWitness) {
    3528         [ +  + ]:      56824 :       for (const auto& tx : block.vtx) {
    3529         [ +  + ]:      39479 :             if (tx->HasWitness()) {
    3530   [ +  -  +  - ]:          5 :                 return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "unexpected-witness", strprintf("%s : unexpected witness data found", __func__));
    3531                 :            :             }
    3532                 :            :         }
    3533                 :            :     }
    3534                 :            : 
    3535                 :            :     // After the coinbase witness reserved value and commitment are verified,
    3536                 :            :     // we can check if the block weight passes (before we've checked the
    3537                 :            :     // coinbase witness, it would be possible for the weight to be too
    3538                 :            :     // large by filling up the coinbase witness, which doesn't change
    3539                 :            :     // the block hash, so we couldn't mark the block as permanently
    3540                 :            :     // failed).
    3541         [ +  + ]:      97493 :     if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
    3542   [ +  -  +  - ]:      97512 :         return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-weight", strprintf("%s : weight limit failed", __func__));
    3543                 :            :     }
    3544                 :            : 
    3545                 :            :     return true;
    3546                 :            : }
    3547                 :            : 
    3548                 :     131127 : bool BlockManager::AcceptBlockHeader(const CBlockHeader& block, BlockValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
    3549                 :            : {
    3550                 :     131127 :     AssertLockHeld(cs_main);
    3551                 :            :     // Check for duplicate
    3552                 :     131127 :     uint256 hash = block.GetHash();
    3553                 :     131127 :     BlockMap::iterator miSelf = m_block_index.find(hash);
    3554                 :     131127 :     CBlockIndex *pindex = nullptr;
    3555         [ +  + ]:     131127 :     if (hash != chainparams.GetConsensus().hashGenesisBlock) {
    3556         [ +  + ]:     131116 :         if (miSelf != m_block_index.end()) {
    3557                 :            :             // Block header is already known.
    3558         [ +  - ]:      57674 :             pindex = miSelf->second;
    3559         [ +  - ]:      57674 :             if (ppindex)
    3560                 :      57674 :                 *ppindex = pindex;
    3561         [ +  + ]:      57674 :             if (pindex->nStatus & BLOCK_FAILED_MASK) {
    3562         [ +  - ]:        354 :                 LogPrintf("ERROR: %s: block %s is marked invalid\n", __func__, hash.ToString());
    3563   [ +  -  +  - ]:        354 :                 return state.Invalid(BlockValidationResult::BLOCK_CACHED_INVALID, "duplicate");
    3564                 :            :             }
    3565                 :            :             return true;
    3566                 :            :         }
    3567                 :            : 
    3568         [ -  + ]:      73442 :         if (!CheckBlockHeader(block, state, chainparams.GetConsensus())) {
    3569   [ #  #  #  #  :          0 :             LogPrint(BCLog::VALIDATION, "%s: Consensus::CheckBlockHeader: %s, %s\n", __func__, hash.ToString(), state.ToString());
                   #  # ]
    3570                 :          0 :             return false;
    3571                 :            :         }
    3572                 :            : 
    3573                 :            :         // Get prev block index
    3574                 :      73442 :         CBlockIndex* pindexPrev = nullptr;
    3575                 :      73442 :         BlockMap::iterator mi = m_block_index.find(block.hashPrevBlock);
    3576         [ +  + ]:      73442 :         if (mi == m_block_index.end()) {
    3577                 :          3 :             LogPrintf("ERROR: %s: prev block not found\n", __func__);
    3578   [ +  -  +  - ]:          3 :             return state.Invalid(BlockValidationResult::BLOCK_MISSING_PREV, "prev-blk-not-found");
    3579                 :            :         }
    3580         [ +  + ]:      73439 :         pindexPrev = (*mi).second;
    3581         [ +  + ]:      73439 :         if (pindexPrev->nStatus & BLOCK_FAILED_MASK) {
    3582                 :          4 :             LogPrintf("ERROR: %s: prev block invalid\n", __func__);
    3583   [ +  -  +  - ]:          4 :             return state.Invalid(BlockValidationResult::BLOCK_INVALID_PREV, "bad-prevblk");
    3584                 :            :         }
    3585         [ +  + ]:      73435 :         if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
    3586   [ +  -  +  - ]:     131140 :             return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), state.ToString());
    3587                 :            : 
    3588                 :            :         /* Determine if this block descends from any block which has been found
    3589                 :            :          * invalid (m_failed_blocks), then mark pindexPrev and any blocks between
    3590                 :            :          * them as failed. For example:
    3591                 :            :          *
    3592                 :            :          *                D3
    3593                 :            :          *              /
    3594                 :            :          *      B2 - C2
    3595                 :            :          *    /         \
    3596                 :            :          *  A             D2 - E2 - F2
    3597                 :            :          *    \
    3598                 :            :          *      B1 - C1 - D1 - E1
    3599                 :            :          *
    3600                 :            :          * In the case that we attempted to reorg from E1 to F2, only to find
    3601                 :            :          * C2 to be invalid, we would mark D2, E2, and F2 as BLOCK_FAILED_CHILD
    3602                 :            :          * but NOT D3 (it was not in any of our candidate sets at the time).
    3603                 :            :          *
    3604                 :            :          * In any case D3 will also be marked as BLOCK_FAILED_CHILD at restart
    3605                 :            :          * in LoadBlockIndex.
    3606                 :            :          */
    3607   [ +  -  +  + ]:      73422 :         if (!pindexPrev->IsValid(BLOCK_VALID_SCRIPTS)) {
    3608                 :            :             // The above does not mean "invalid": it checks if the previous block
    3609                 :            :             // hasn't been validated up to BLOCK_VALID_SCRIPTS. This is a performance
    3610                 :            :             // optimization, in the common case of adding a new block to the tip,
    3611                 :            :             // we don't need to iterate over the failed blocks list.
    3612         [ +  + ]:     143214 :             for (const CBlockIndex* failedit : m_failed_blocks) {
    3613         [ +  + ]:     125245 :                 if (pindexPrev->GetAncestor(failedit->nHeight) == failedit) {
    3614         [ -  + ]:          2 :                     assert(failedit->nStatus & BLOCK_FAILED_VALID);
    3615                 :          2 :                     CBlockIndex* invalid_walk = pindexPrev;
    3616         [ +  + ]:          5 :                     while (invalid_walk != failedit) {
    3617                 :          3 :                         invalid_walk->nStatus |= BLOCK_FAILED_CHILD;
    3618                 :          3 :                         setDirtyBlockIndex.insert(invalid_walk);
    3619                 :          3 :                         invalid_walk = invalid_walk->pprev;
    3620                 :            :                     }
    3621                 :          2 :                     LogPrintf("ERROR: %s: prev block invalid\n", __func__);
    3622   [ +  -  +  - ]:     131129 :                     return state.Invalid(BlockValidationResult::BLOCK_INVALID_PREV, "bad-prevblk");
    3623                 :            :                 }
    3624                 :            :             }
    3625                 :            :         }
    3626                 :            :     }
    3627                 :      73431 :     if (pindex == nullptr)
    3628                 :      73431 :         pindex = AddToBlockIndex(block);
    3629                 :            : 
    3630         [ +  - ]:      73431 :     if (ppindex)
    3631                 :      73431 :         *ppindex = pindex;
    3632                 :            : 
    3633                 :            :     return true;
    3634                 :            : }
    3635                 :            : 
    3636                 :            : // Exposed wrapper for AcceptBlockHeader
    3637                 :      34124 : bool ChainstateManager::ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, BlockValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex)
    3638                 :            : {
    3639                 :      34124 :     AssertLockNotHeld(cs_main);
    3640                 :      34124 :     {
    3641                 :      34124 :         LOCK(cs_main);
    3642         [ +  + ]:      82327 :         for (const CBlockHeader& header : headers) {
    3643                 :      48563 :             CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
    3644         [ +  - ]:      48563 :             bool accepted = m_blockman.AcceptBlockHeader(
    3645                 :            :                 header, state, chainparams, &pindex);
    3646   [ +  -  +  - ]:      48563 :             ::ChainstateActive().CheckBlockIndex(chainparams.GetConsensus());
    3647                 :            : 
    3648         [ +  + ]:      48563 :             if (!accepted) {
    3649         [ +  - ]:      34484 :                 return false;
    3650                 :            :             }
    3651         [ +  + ]:      48203 :             if (ppindex) {
    3652                 :      48126 :                 *ppindex = pindex;
    3653                 :            :             }
    3654                 :            :         }
    3655                 :            :     }
    3656         [ +  + ]:      33764 :     if (NotifyHeaderTip()) {
    3657   [ +  +  +  +  :      24600 :         if (::ChainstateActive().IsInitialBlockDownload() && ppindex && *ppindex) {
                   +  - ]
    3658                 :        373 :             LogPrintf("Synchronizing blockheaders, height: %d (~%.2f%%)\n", (*ppindex)->nHeight, 100.0/((*ppindex)->nHeight+(GetAdjustedTime() - (*ppindex)->GetBlockTime()) / Params().GetConsensus().nPowTargetSpacing) * (*ppindex)->nHeight);
    3659                 :            :         }
    3660                 :            :     }
    3661                 :            :     return true;
    3662                 :            : }
    3663                 :            : 
    3664                 :            : /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
    3665                 :      71072 : static FlatFilePos SaveBlockToDisk(const CBlock& block, int nHeight, const CChainParams& chainparams, const FlatFilePos* dbp) {
    3666                 :      71072 :     unsigned int nBlockSize = ::GetSerializeSize(block, CLIENT_VERSION);
    3667         [ +  + ]:      71072 :     FlatFilePos blockPos;
    3668         [ +  + ]:      71072 :     if (dbp != nullptr)
    3669                 :       1322 :         blockPos = *dbp;
    3670         [ -  + ]:      71072 :     if (!FindBlockPos(blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != nullptr)) {
    3671                 :          0 :         error("%s: FindBlockPos failed", __func__);
    3672                 :          0 :         return FlatFilePos();
    3673                 :            :     }
    3674         [ +  + ]:      71072 :     if (dbp == nullptr) {
    3675         [ -  + ]:      69750 :         if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) {
    3676   [ #  #  #  # ]:          0 :             AbortNode("Failed to write block");
    3677                 :          0 :             return FlatFilePos();
    3678                 :            :         }
    3679                 :            :     }
    3680                 :      71072 :     return blockPos;
    3681                 :            : }
    3682                 :            : 
    3683                 :            : /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
    3684                 :      82564 : bool CChainState::AcceptBlock(const std::shared_ptr<const CBlock>& pblock, BlockValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const FlatFilePos* dbp, bool* fNewBlock)
    3685                 :            : {
    3686         [ +  + ]:      82564 :     const CBlock& block = *pblock;
    3687                 :            : 
    3688         [ +  + ]:      82564 :     if (fNewBlock) *fNewBlock = false;
    3689         [ +  + ]:      82564 :     AssertLockHeld(cs_main);
    3690                 :            : 
    3691                 :      82564 :     CBlockIndex *pindexDummy = nullptr;
    3692         [ +  + ]:      82564 :     CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
    3693                 :            : 
    3694                 :      82564 :     bool accepted_header = m_blockman.AcceptBlockHeader(block, state, chainparams, &pindex);
    3695                 :      82564 :     CheckBlockIndex(chainparams.GetConsensus());
    3696                 :            : 
    3697         [ +  + ]:      82564 :     if (!accepted_header)
    3698                 :            :         return false;
    3699                 :            : 
    3700                 :            :     // Try to process all requested blocks that we don't have, but only
    3701                 :            :     // process an unrequested block if it's new and has enough work to
    3702                 :            :     // advance our tip, and isn't too many blocks ahead.
    3703                 :      82548 :     bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
    3704   [ +  +  +  -  :      82548 :     bool fHasMoreOrSameWork = (m_chain.Tip() ? pindex->nChainWork >= m_chain.Tip()->nChainWork : true);
                   +  + ]
    3705                 :            :     // Blocks that are too out-of-order needlessly limit the effectiveness of
    3706                 :            :     // pruning, because pruning will not delete block files that contain any
    3707                 :            :     // blocks which are too close in height to the tip.  Apply this test
    3708                 :            :     // regardless of whether pruning is enabled; it should generally be safe to
    3709                 :            :     // not process unrequested blocks.
    3710         [ +  + ]:      82548 :     bool fTooFarAhead = (pindex->nHeight > int(m_chain.Height() + MIN_BLOCKS_TO_KEEP));
    3711                 :            : 
    3712                 :            :     // TODO: Decouple this function from the block download logic by removing fRequested
    3713                 :            :     // This requires some new chain data structure to efficiently look up if a
    3714                 :            :     // block is in a chain leading to a candidate for best tip, despite not
    3715                 :            :     // being such a candidate itself.
    3716                 :            : 
    3717                 :            :     // TODO: deal better with return value and error conditions for duplicate
    3718                 :            :     // and unrequested blocks.
    3719         [ +  + ]:      82548 :     if (fAlreadyHave) return true;
    3720         [ +  + ]:      71858 :     if (!fRequested) {  // If we didn't ask for it:
    3721         [ +  - ]:       1697 :         if (pindex->nTx != 0) return true;    // This is a previously-processed block that was pruned
    3722         [ +  + ]:       1697 :         if (!fHasMoreOrSameWork) return true; // Don't process less-work chains
    3723         [ +  + ]:        605 :         if (fTooFarAhead) return true;        // Block height is too high
    3724                 :            : 
    3725                 :            :         // Protect against DoS attacks from low-work chains.
    3726                 :            :         // If our tip is behind, a peer could try to send us
    3727                 :            :         // low-work blocks on a fake chain that we would never
    3728                 :            :         // request; don't process these.
    3729         [ +  + ]:        604 :         if (pindex->nChainWork < nMinimumChainWork) return true;
    3730                 :            :     }
    3731                 :            : 
    3732   [ +  -  +  + ]:     141528 :     if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
    3733                 :      70764 :         !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
    3734   [ +  -  +  + ]:         18 :         if (state.IsInvalid() && state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
    3735                 :          8 :             pindex->nStatus |= BLOCK_FAILED_VALID;
    3736                 :          8 :             setDirtyBlockIndex.insert(pindex);
    3737                 :            :         }
    3738         [ +  - ]:      82582 :         return error("%s: %s", __func__, state.ToString());
    3739                 :            :     }
    3740                 :            : 
    3741                 :            :     // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
    3742                 :            :     // (but if it does not build on our best tip, let the SendMessages loop relay it)
    3743   [ +  +  +  -  :     136073 :     if (!IsInitialBlockDownload() && m_chain.Tip() == pindex->pprev)
                   +  + ]
    3744                 :      60451 :         GetMainSignals().NewPoWValidBlock(pindex, pblock);
    3745                 :            : 
    3746                 :            :     // Write block to history file
    3747         [ +  + ]:      70746 :     if (fNewBlock) *fNewBlock = true;
    3748                 :      70746 :     try {
    3749         [ +  - ]:      70746 :         FlatFilePos blockPos = SaveBlockToDisk(block, pindex->nHeight, chainparams, dbp);
    3750         [ -  + ]:      70746 :         if (blockPos.IsNull()) {
    3751         [ #  # ]:          0 :             state.Error(strprintf("%s: Failed to find position to write new block to disk", __func__));
    3752                 :          0 :             return false;
    3753                 :            :         }
    3754         [ +  - ]:      70746 :         ReceivedBlockTransactions(block, pindex, blockPos, chainparams.GetConsensus());
    3755         [ -  - ]:          0 :     } catch (const std::runtime_error& e) {
    3756   [ -  -  -  -  :          0 :         return AbortNode(state, std::string("System error: ") + e.what());
                   -  - ]
    3757                 :            :     }
    3758                 :            : 
    3759                 :      70746 :     FlushStateToDisk(chainparams, state, FlushStateMode::NONE);
    3760                 :            : 
    3761                 :      70746 :     CheckBlockIndex(chainparams.GetConsensus());
    3762                 :            : 
    3763                 :      70746 :     return true;
    3764                 :            : }
    3765                 :            : 
    3766                 :      81356 : bool ChainstateManager::ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool* fNewBlock)
    3767                 :            : {
    3768                 :      81356 :     AssertLockNotHeld(cs_main);
    3769                 :            : 
    3770                 :      81356 :     {
    3771                 :      81356 :         CBlockIndex *pindex = nullptr;
    3772         [ +  + ]:      81356 :         if (fNewBlock) *fNewBlock = false;
    3773         [ +  - ]:      81356 :         BlockValidationState state;
    3774                 :            : 
    3775                 :            :         // CheckBlock() does not support multi-threaded block validation because CBlock::fChecked can cause data race.
    3776                 :            :         // Therefore, the following critical section must include the CheckBlock() call as well.
    3777         [ +  - ]:     162464 :         LOCK(cs_main);
    3778                 :            : 
    3779                 :            :         // Ensure that CheckBlock() passes before calling AcceptBlock, as
    3780                 :            :         // belt-and-suspenders.
    3781         [ +  - ]:      81356 :         bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
    3782         [ +  + ]:      81356 :         if (ret) {
    3783                 :            :             // Store to disk
    3784   [ +  -  +  - ]:      81142 :             ret = ::ChainstateActive().AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, nullptr, fNewBlock);
    3785                 :            :         }
    3786         [ +  + ]:      81356 :         if (!ret) {
    3787   [ +  -  +  - ]:        248 :             GetMainSignals().BlockChecked(*pblock, state);
    3788   [ +  -  +  -  :        248 :             return error("%s: AcceptBlock FAILED (%s)", __func__, state.ToString());
                   +  - ]
    3789                 :            :         }
    3790                 :            :     }
    3791                 :            : 
    3792                 :      81108 :     NotifyHeaderTip();
    3793                 :            : 
    3794         [ +  - ]:     162464 :     BlockValidationState state; // Only used to report errors, not invalidity - ignore it
    3795   [ +  -  +  -  :     243324 :     if (!::ChainstateActive().ActivateBestChain(state, chainparams, pblock))
          +  -  +  -  +  
                      + ]
    3796   [ +  -  +  - ]:      81109 :         return error("%s: ActivateBestChain failed (%s)", __func__, state.ToString());
    3797                 :            : 
    3798                 :            :     return true;
    3799                 :            : }
    3800                 :            : 
    3801                 :      26755 : bool TestBlockValidity(BlockValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
    3802                 :            : {
    3803         [ +  - ]:      26755 :     AssertLockHeld(cs_main);
    3804   [ +  -  +  -  :      53510 :     assert(pindexPrev && pindexPrev == ::ChainActive().Tip());
                   -  + ]
    3805                 :      53510 :     CCoinsViewCache viewNew(&::ChainstateActive().CoinsTip());
    3806         [ +  - ]:      26755 :     uint256 block_hash(block.GetHash());
    3807                 :      26755 :     CBlockIndex indexDummy(block);
    3808                 :      26755 :     indexDummy.pprev = pindexPrev;
    3809                 :      26755 :     indexDummy.nHeight = pindexPrev->nHeight + 1;
    3810                 :      26755 :     indexDummy.phashBlock = &block_hash;
    3811                 :            : 
    3812                 :            :     // NOTE: CheckBlockHeader is called by CheckBlock
    3813   [ +  -  +  -  :      26755 :     if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
                   +  + ]
    3814   [ +  -  +  - ]:          3 :         return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, state.ToString());
    3815   [ +  -  +  + ]:      26752 :     if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
    3816   [ +  -  +  - ]:          5 :         return error("%s: Consensus::CheckBlock: %s", __func__, state.ToString());
    3817   [ +  -  +  + ]:      26747 :     if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
    3818   [ +  -  +  - ]:      26756 :         return error("%s: Consensus::ContextualCheckBlock: %s", __func__, state.ToString());
    3819   [ +  -  +  -  :      26746 :     if (!::ChainstateActive().ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
                   +  + ]
    3820                 :            :         return false;
    3821         [ -  + ]:      26741 :     assert(state.IsValid());
    3822                 :            : 
    3823                 :            :     return true;
    3824                 :            : }
    3825                 :            : 
    3826                 :            : /**
    3827                 :            :  * BLOCK PRUNING CODE
    3828                 :            :  */
    3829                 :            : 
    3830                 :            : /* Calculate the amount of disk space the block & undo files currently use */
    3831                 :        468 : uint64_t CalculateCurrentUsage()
    3832                 :            : {
    3833                 :        468 :     LOCK(cs_LastBlockFile);
    3834                 :            : 
    3835                 :        468 :     uint64_t retval = 0;
    3836         [ +  + ]:       1339 :     for (const CBlockFileInfo &file : vinfoBlockFile) {
    3837                 :        871 :         retval += file.nSize + file.nUndoSize;
    3838                 :            :     }
    3839         [ +  - ]:        468 :     return retval;
    3840                 :            : }
    3841                 :            : 
    3842                 :         19 : void BlockManager::PruneOneBlockFile(const int fileNumber)
    3843                 :            : {
    3844                 :         19 :     AssertLockHeld(cs_main);
    3845                 :         19 :     LOCK(cs_LastBlockFile);
    3846                 :            : 
    3847         [ +  + ]:      20973 :     for (const auto& entry : m_block_index) {
    3848                 :      20954 :         CBlockIndex* pindex = entry.second;
    3849         [ +  + ]:      20954 :         if (pindex->nFile == fileNumber) {
    3850                 :       4413 :             pindex->nStatus &= ~BLOCK_HAVE_DATA;
    3851                 :       4413 :             pindex->nStatus &= ~BLOCK_HAVE_UNDO;
    3852                 :       4413 :             pindex->nFile = 0;
    3853                 :       4413 :             pindex->nDataPos = 0;
    3854                 :       4413 :             pindex->nUndoPos = 0;
    3855         [ +  - ]:       4413 :             setDirtyBlockIndex.insert(pindex);
    3856                 :            : 
    3857                 :            :             // Prune from m_blocks_unlinked -- any block we prune would have
    3858                 :            :             // to be downloaded again in order to consider its chain, at which
    3859                 :            :             // point it would be considered as a candidate for
    3860                 :            :             // m_blocks_unlinked or setBlockIndexCandidates.
    3861                 :       4413 :             auto range = m_blocks_unlinked.equal_range(pindex->pprev);
    3862                 :       4413 :             while (range.first != range.second) {
    3863                 :          0 :                 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
    3864                 :          0 :                 range.first++;
    3865         [ #  # ]:          0 :                 if (_it->second == pindex) {
    3866         [ -  + ]:       4413 :                     m_blocks_unlinked.erase(_it);
    3867                 :            :                 }
    3868                 :            :             }
    3869                 :            :         }
    3870                 :            :     }
    3871                 :            : 
    3872         [ +  - ]:         19 :     vinfoBlockFile[fileNumber].SetNull();
    3873         [ +  - ]:         19 :     setDirtyFileInfo.insert(fileNumber);
    3874                 :         19 : }
    3875                 :            : 
    3876                 :            : 
    3877                 :         17 : void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
    3878                 :            : {
    3879         [ +  + ]:         36 :     for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
    3880                 :         19 :         FlatFilePos pos(*it, 0);
    3881         [ +  - ]:         38 :         fs::remove(BlockFileSeq().FileName(pos));
    3882         [ +  - ]:         38 :         fs::remove(UndoFileSeq().FileName(pos));
    3883                 :         19 :         LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
    3884                 :            :     }
    3885                 :         17 : }
    3886                 :            : 
    3887                 :         10 : void BlockManager::FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight, int chain_tip_height)
    3888                 :            : {
    3889   [ +  -  -  + ]:         10 :     assert(fPruneMode && nManualPruneHeight > 0);
    3890                 :            : 
    3891   [ +  -  +  - ]:         30 :     LOCK2(cs_main, cs_LastBlockFile);
    3892         [ -  + ]:         10 :     if (chain_tip_height < 0) {
    3893   [ #  #  #  # ]:          0 :         return;
    3894                 :            :     }
    3895                 :            : 
    3896                 :            :     // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
    3897         [ -  + ]:         10 :     unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chain_tip_height - MIN_BLOCKS_TO_KEEP);
    3898                 :         10 :     int count = 0;
    3899         [ +  + ]:         50 :     for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
    3900   [ +  +  +  + ]:         40 :         if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune) {
    3901                 :         32 :             continue;
    3902                 :            :         }
    3903         [ +  - ]:          8 :         PruneOneBlockFile(fileNumber);
    3904         [ +  - ]:          8 :         setFilesToPrune.insert(fileNumber);
    3905                 :          8 :         count++;
    3906                 :            :     }
    3907         [ +  - ]:         10 :     LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
    3908                 :            : }
    3909                 :            : 
    3910                 :            : /* This function is called from the RPC code for pruneblockchain */
    3911                 :         12 : void PruneBlockFilesManual(int nManualPruneHeight)
    3912                 :            : {
    3913         [ +  - ]:         12 :     BlockValidationState state;
    3914         [ +  - ]:         12 :     const CChainParams& chainparams = Params();
    3915   [ +  -  +  -  :         12 :     if (!::ChainstateActive().FlushStateToDisk(
                   -  + ]
    3916                 :            :             chainparams, state, FlushStateMode::NONE, nManualPruneHeight)) {
    3917   [ -  -  -  - ]:         12 :         LogPrintf("%s: failed to flush state (%s)\n", __func__, state.ToString());
    3918                 :            :     }
    3919                 :         12 : }
    3920                 :            : 
    3921                 :        153 : void BlockManager::FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight, int chain_tip_height, bool is_ibd)
    3922                 :            : {
    3923   [ +  -  +  - ]:        367 :     LOCK2(cs_main, cs_LastBlockFile);
    3924   [ +  +  +  - ]:        153 :     if (chain_tip_height < 0 || nPruneTarget == 0) {
    3925         [ +  - ]:         92 :         return;
    3926                 :            :     }
    3927         [ +  + ]:        150 :     if ((uint64_t)chain_tip_height <= nPruneAfterHeight) {
    3928                 :            :         return;
    3929                 :            :     }
    3930                 :            : 
    3931                 :         61 :     unsigned int nLastBlockWeCanPrune = chain_tip_height - MIN_BLOCKS_TO_KEEP;
    3932         [ +  - ]:         61 :     uint64_t nCurrentUsage = CalculateCurrentUsage();
    3933                 :            :     // We don't check to prune until after we've allocated new space for files
    3934                 :            :     // So we should leave a buffer under our target to account for another allocation
    3935                 :            :     // before the next pruning.
    3936                 :         61 :     uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
    3937                 :         61 :     uint64_t nBytesToPrune;
    3938                 :         61 :     int count = 0;
    3939                 :            : 
    3940         [ +  + ]:         61 :     if (nCurrentUsage + nBuffer >= nPruneTarget) {
    3941                 :            :         // On a prune event, the chainstate DB is flushed.
    3942                 :            :         // To avoid excessive prune events negating the benefit of high dbcache
    3943                 :            :         // values, we should not prune too rapidly.
    3944                 :            :         // So when pruning in IBD, increase the buffer a bit to avoid a re-prune too soon.
    3945         [ -  + ]:          8 :         if (is_ibd) {
    3946                 :            :             // Since this is only relevant during IBD, we use a fixed 10%
    3947                 :          0 :             nBuffer += nPruneTarget / 10;
    3948                 :            :         }
    3949                 :            : 
    3950         [ +  - ]:         29 :         for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
    3951         [ +  + ]:         29 :             nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
    3952                 :            : 
    3953         [ +  + ]:         29 :             if (vinfoBlockFile[fileNumber].nSize == 0) {
    3954                 :         13 :                 continue;
    3955                 :            :             }
    3956                 :            : 
    3957         [ +  + ]:         16 :             if (nCurrentUsage + nBuffer < nPruneTarget) { // are we below our target?
    3958                 :            :                 break;
    3959                 :            :             }
    3960                 :            : 
    3961                 :            :             // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
    3962         [ -  + ]:          8 :             if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune) {
    3963                 :          0 :                 continue;
    3964                 :            :             }
    3965                 :            : 
    3966         [ +  - ]:          8 :             PruneOneBlockFile(fileNumber);
    3967                 :            :             // Queue up the files for removal
    3968         [ +  - ]:          8 :             setFilesToPrune.insert(fileNumber);
    3969                 :          8 :             nCurrentUsage -= nBytesToPrune;
    3970                 :          8 :             count++;
    3971                 :            :         }
    3972                 :            :     }
    3973                 :            : 
    3974   [ +  -  +  -  :         61 :     LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
                   +  - ]
    3975                 :            :            nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
    3976                 :            :            ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
    3977                 :            :            nLastBlockWeCanPrune, count);
    3978                 :            : }
    3979                 :            : 
    3980                 :     270591 : static FlatFileSeq BlockFileSeq()
    3981                 :            : {
    3982         [ +  - ]:     541182 :     return FlatFileSeq(GetBlocksDir(), "blk", BLOCKFILE_CHUNK_SIZE);
    3983                 :            : }
    3984                 :            : 
    3985                 :     154196 : static FlatFileSeq UndoFileSeq()
    3986                 :            : {
    3987         [ +  - ]:     308392 :     return FlatFileSeq(GetBlocksDir(), "rev", UNDOFILE_CHUNK_SIZE);
    3988                 :            : }
    3989                 :            : 
    3990                 :     198982 : FILE* OpenBlockFile(const FlatFilePos &pos, bool fReadOnly) {
    3991         [ +  - ]:     198982 :     return BlockFileSeq().Open(pos, fReadOnly);
    3992                 :            : }
    3993                 :            : 
    3994                 :            : /** Open an undo file (rev?????.dat) */
    3995                 :      84434 : static FILE* OpenUndoFile(const FlatFilePos &pos, bool fReadOnly) {
    3996         [ +  - ]:      84434 :     return UndoFileSeq().Open(pos, fReadOnly);
    3997                 :            : }
    3998                 :            : 
    3999                 :         16 : fs::path GetBlockPosFilename(const FlatFilePos &pos)
    4000                 :            : {
    4001         [ +  - ]:         32 :     return BlockFileSeq().FileName(pos);
    4002                 :            : }
    4003                 :            : 
    4004                 :     158434 : CBlockIndex * BlockManager::InsertBlockIndex(const uint256& hash)
    4005                 :            : {
    4006                 :     158434 :     AssertLockHeld(cs_main);
    4007                 :            : 
    4008         [ +  + ]:     316868 :     if (hash.IsNull())
    4009                 :            :         return nullptr;
    4010                 :            : 
    4011                 :            :     // Return existing
    4012                 :     158045 :     BlockMap::iterator mi = m_block_index.find(hash);
    4013         [ +  + ]:     158045 :     if (mi != m_block_index.end())
    4014                 :      78828 :         return (*mi).second;
    4015                 :            : 
    4016                 :            :     // Create new
    4017                 :      79217 :     CBlockIndex* pindexNew = new CBlockIndex();
    4018                 :      79217 :     mi = m_block_index.insert(std::make_pair(hash, pindexNew)).first;
    4019                 :      79217 :     pindexNew->phashBlock = &((*mi).first);
    4020                 :            : 
    4021                 :      79217 :     return pindexNew;
    4022                 :            : }
    4023                 :            : 
    4024                 :        624 : bool BlockManager::LoadBlockIndex(
    4025                 :            :     const Consensus::Params& consensus_params,
    4026                 :            :     CBlockTreeDB& blocktree,
    4027                 :            :     std::set<CBlockIndex*, CBlockIndexWorkComparator>& block_index_candidates)
    4028                 :            : {
    4029   [ +  -  +  - ]:     159058 :     if (!blocktree.LoadBlockIndexGuts(consensus_params, [this](const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return this->InsertBlockIndex(hash); }))
    4030                 :            :         return false;
    4031                 :            : 
    4032                 :            :     // Calculate nChainWork
    4033         [ +  - ]:       1248 :     std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
    4034         [ +  - ]:        624 :     vSortedByHeight.reserve(m_block_index.size());
    4035         [ +  + ]:      79841 :     for (const std::pair<const uint256, CBlockIndex*>& item : m_block_index)
    4036                 :            :     {
    4037                 :      79217 :         CBlockIndex* pindex = item.second;
    4038         [ +  - ]:      79217 :         vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
    4039                 :            :     }
    4040                 :        624 :     sort(vSortedByHeight.begin(), vSortedByHeight.end());
    4041         [ +  + ]:      79841 :     for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
    4042                 :            :     {
    4043   [ +  -  +  - ]:      79217 :         if (ShutdownRequested()) return false;
    4044                 :      79217 :         CBlockIndex* pindex = item.second;
    4045   [ +  -  +  + ]:     237651 :         pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
    4046   [ +  +  +  + ]:     100064 :         pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
    4047                 :            :         // We can link the chain of blocks for which we've received transactions at some point.
    4048                 :            :         // Pruned nodes may have deleted the block.
    4049         [ +  + ]:      79217 :         if (pindex->nTx > 0) {
    4050         [ +  + ]:      78671 :             if (pindex->pprev) {
    4051         [ +  - ]:      78282 :                 if (pindex->pprev->HaveTxsDownloaded()) {
    4052                 :      78282 :                     pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
    4053                 :            :                 } else {
    4054                 :          0 :                     pindex->nChainTx = 0;
    4055         [ #  # ]:          0 :                     m_blocks_unlinked.insert(std::make_pair(pindex->pprev, pindex));
    4056                 :            :                 }
    4057                 :            :             } else {
    4058                 :        389 :                 pindex->nChainTx = pindex->nTx;
    4059                 :            :             }
    4060                 :            :         }
    4061   [ +  +  +  +  :      79217 :         if (!(pindex->nStatus & BLOCK_FAILED_MASK) && pindex->pprev && (pindex->pprev->nStatus & BLOCK_FAILED_MASK)) {
                   -  + ]
    4062                 :          0 :             pindex->nStatus |= BLOCK_FAILED_CHILD;
    4063         [ #  # ]:          0 :             setDirtyBlockIndex.insert(pindex);
    4064                 :            :         }
    4065   [ +  +  +  +  :      79217 :         if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->HaveTxsDownloaded() || pindex->pprev == nullptr)) {
             -  +  -  - ]
    4066         [ +  - ]:      78427 :             block_index_candidates.insert(pindex);
    4067                 :            :         }
    4068   [ +  +  +  +  :      79217 :         if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
             +  -  +  - ]
    4069                 :        244 :             pindexBestInvalid = pindex;
    4070         [ +  + ]:      79217 :         if (pindex->pprev)
    4071         [ +  - ]:      78828 :             pindex->BuildSkip();
    4072   [ +  +  +  -  :     157880 :         if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
          +  +  +  -  +  
                      + ]
    4073                 :      78663 :             pindexBestHeader = pindex;
    4074                 :            :     }
    4075                 :            : 
    4076                 :            :     return true;
    4077                 :            : }
    4078                 :            : 
    4079                 :       1510 : void BlockManager::Unload() {
    4080                 :       1510 :     m_failed_blocks.clear();
    4081                 :       1510 :     m_blocks_unlinked.clear();
    4082                 :            : 
    4083         [ +  + ]:     154486 :     for (const BlockMap::value_type& entry : m_block_index) {
    4084         [ +  - ]:     152976 :         delete entry.second;
    4085                 :            :     }
    4086                 :            : 
    4087                 :       1510 :     m_block_index.clear();
    4088                 :       1510 : }
    4089                 :            : 
    4090                 :        624 : bool static LoadBlockIndexDB(ChainstateManager& chainman, const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
    4091                 :            : {
    4092         [ +  - ]:        624 :     if (!chainman.m_blockman.LoadBlockIndex(
    4093                 :        624 :             chainparams.GetConsensus(), *pblocktree,
    4094                 :        624 :             ::ChainstateActive().setBlockIndexCandidates)) {
    4095                 :            :         return false;
    4096                 :            :     }
    4097                 :            : 
    4098                 :            :     // Load block file info
    4099                 :        624 :     pblocktree->ReadLastBlockFile(nLastBlockFile);
    4100                 :        624 :     vinfoBlockFile.resize(nLastBlockFile + 1);
    4101                 :        624 :     LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
    4102         [ +  + ]:       1286 :     for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
    4103                 :        662 :         pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
    4104                 :            :     }
    4105         [ +  - ]:        624 :     LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
    4106                 :        624 :     for (int nFile = nLastBlockFile + 1; true; nFile++) {
    4107                 :        624 :         CBlockFileInfo info;
    4108         [ -  + ]:        624 :         if (pblocktree->ReadBlockFileInfo(nFile, info)) {
    4109                 :          0 :             vinfoBlockFile.push_back(info);
    4110                 :            :         } else {
    4111                 :            :             break;
    4112                 :            :         }
    4113                 :          0 :     }
    4114                 :            : 
    4115                 :            :     // Check presence of blk files
    4116                 :        624 :     LogPrintf("Checking all blk files are present...\n");
    4117                 :       1248 :     std::set<int> setBlkDataFiles;
    4118         [ +  + ]:      79841 :     for (const std::pair<const uint256, CBlockIndex*>& item : chainman.BlockIndex()) {
    4119                 :      79217 :         CBlockIndex* pindex = item.second;
    4120         [ +  + ]:      79217 :         if (pindex->nStatus & BLOCK_HAVE_DATA) {
    4121         [ +  - ]:      75034 :             setBlkDataFiles.insert(pindex->nFile);
    4122                 :            :         }
    4123                 :            :     }
    4124         [ +  + ]:       1035 :     for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
    4125                 :            :     {
    4126         [ +  - ]:        411 :         FlatFilePos pos(*it, 0);
    4127   [ +  -  +  -  :        822 :         if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
                   +  - ]
    4128                 :            :             return false;
    4129                 :            :         }
    4130                 :            :     }
    4131                 :            : 
    4132                 :            :     // Check whether we have ever pruned block & undo files
    4133   [ +  -  +  -  :       1248 :     pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
                   +  + ]
    4134         [ +  + ]:        624 :     if (fHavePruned)
    4135         [ +  - ]:          4 :         LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
    4136                 :            : 
    4137                 :            :     // Check whether we need to continue reindexing
    4138                 :        624 :     bool fReindexing = false;
    4139         [ +  - ]:        624 :     pblocktree->ReadReindexing(fReindexing);
    4140         [ -  + ]:        624 :     if(fReindexing) fReindex = true;
    4141                 :            : 
    4142                 :            :     return true;
    4143                 :            : }
    4144                 :            : 
    4145                 :        629 : void CChainState::LoadMempool(const ArgsManager& args)
    4146                 :            : {
    4147   [ +  -  +  + ]:        629 :     if (args.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
    4148                 :        623 :         ::LoadMempool(m_mempool);
    4149                 :            :     }
    4150                 :        629 :     m_mempool.SetIsLoaded(!ShutdownRequested());
    4151                 :        629 : }
    4152                 :            : 
    4153                 :        387 : bool CChainState::LoadChainTip(const CChainParams& chainparams)
    4154                 :            : {
    4155                 :        387 :     AssertLockHeld(cs_main);
    4156                 :        387 :     const CCoinsViewCache& coins_cache = CoinsTip();
    4157         [ -  + ]:        774 :     assert(!coins_cache.GetBestBlock().IsNull()); // Never called when the coins view is empty
    4158         [ -  + ]:        387 :     const CBlockIndex* tip = m_chain.Tip();
    4159                 :            : 
    4160   [ #  #  #  # ]:          0 :     if (tip && tip->GetBlockHash() == coins_cache.GetBestBlock()) {
    4161                 :            :         return true;
    4162                 :            :     }
    4163                 :            : 
    4164                 :            :     // Load pointer to end of best chain
    4165                 :        387 :     CBlockIndex* pindex = LookupBlockIndex(coins_cache.GetBestBlock());
    4166         [ +  - ]:        387 :     if (!pindex) {
    4167                 :            :         return false;
    4168                 :            :     }
    4169                 :        387 :     m_chain.SetTip(pindex);
    4170                 :        387 :     PruneBlockIndexCandidates();
    4171                 :            : 
    4172         [ +  - ]:        387 :     tip = m_chain.Tip();
    4173         [ +  - ]:        774 :     LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
    4174         [ +  - ]:        774 :         tip->GetBlockHash().ToString(),
    4175         [ +  - ]:        387 :         m_chain.Height(),
    4176                 :        387 :         FormatISO8601DateTime(tip->GetBlockTime()),
    4177                 :        387 :         GuessVerificationProgress(chainparams.TxData(), tip));
    4178                 :        387 :     return true;
    4179                 :            : }
    4180                 :            : 
    4181                 :        389 : CVerifyDB::CVerifyDB()
    4182                 :            : {
    4183         [ +  - ]:        389 :     uiInterface.ShowProgress(_("Verifying blocks...").translated, 0, false);
    4184                 :        389 : }
    4185                 :            : 
    4186                 :        389 : CVerifyDB::~CVerifyDB()
    4187                 :            : {
    4188                 :        389 :     uiInterface.ShowProgress("", 100, false);
    4189                 :        389 : }
    4190                 :            : 
    4191                 :        389 : bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
    4192                 :            : {
    4193                 :        778 :     LOCK(cs_main);
    4194   [ +  -  +  -  :        778 :     if (::ChainActive().Tip() == nullptr || ::ChainActive().Tip()->pprev == nullptr)
          +  -  +  -  +  
                -  +  + ]
    4195                 :         58 :         return true;
    4196                 :            : 
    4197                 :            :     // Verify blocks in the best chain
    4198   [ +  +  +  -  :        331 :     if (nCheckDepth <= 0 || nCheckDepth > ::ChainActive().Height())
                   +  + ]
    4199         [ +  - ]:         16 :         nCheckDepth = ::ChainActive().Height();
    4200   [ +  +  +  - ]:        660 :     nCheckLevel = std::max(0, std::min(4, nCheckLevel));
    4201         [ +  - ]:        331 :     LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
    4202   [ +  -  +  - ]:        720 :     CCoinsViewCache coins(coinsview);
    4203                 :        331 :     CBlockIndex* pindex;
    4204                 :        331 :     CBlockIndex* pindexFailure = nullptr;
    4205                 :        331 :     int nGoodTransactions = 0;
    4206         [ +  - ]:        662 :     BlockValidationState state;
    4207                 :        331 :     int reportDone = 0;
    4208         [ +  - ]:        331 :     LogPrintf("[0%%]..."); /* Continued */
    4209   [ +  -  +  -  :       3292 :     for (pindex = ::ChainActive().Tip(); pindex && pindex->pprev; pindex = pindex->pprev) {
             +  -  +  + ]
    4210   [ +  -  +  +  :       7798 :         const int percentageDone = std::max(1, std::min(99, (int)(((double)(::ChainActive().Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
             +  +  +  + ]
    4211         [ +  + ]:       2947 :         if (reportDone < percentageDone/10) {
    4212                 :            :             // report every 10% step
    4213         [ +  - ]:       1895 :             LogPrintf("[%d%%]...", percentageDone); /* Continued */
    4214                 :       1895 :             reportDone = percentageDone/10;
    4215                 :            :         }
    4216   [ +  -  +  - ]:       2947 :         uiInterface.ShowProgress(_("Verifying blocks...").translated, percentageDone, false);
    4217   [ +  -  +  + ]:       2947 :         if (pindex->nHeight <= ::ChainActive().Height()-nCheckDepth)
    4218                 :            :             break;
    4219   [ +  +  +  + ]:       2632 :         if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
    4220                 :            :             // If pruning, only go back as far as we have data.
    4221         [ +  - ]:          1 :             LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
    4222                 :            :             break;
    4223                 :            :         }
    4224                 :       5261 :         CBlock block;
    4225                 :            :         // check level 0: read from disk
    4226   [ +  -  -  + ]:       2631 :         if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
    4227   [ #  #  #  # ]:          0 :             return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
    4228                 :            :         // check level 1: verify block validity
    4229   [ +  -  +  -  :       2631 :         if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
                   +  - ]
    4230                 :          0 :             return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
    4231   [ #  #  #  #  :          0 :                          pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
                   #  # ]
    4232                 :            :         // check level 2: verify undo validity
    4233         [ +  - ]:       2631 :         if (nCheckLevel >= 2 && pindex) {
    4234         [ +  - ]:       2631 :             CBlockUndo undo;
    4235         [ +  - ]:       2631 :             if (!pindex->GetUndoPos().IsNull()) {
    4236   [ +  -  +  + ]:       2631 :                 if (!UndoReadFromDisk(undo, pindex)) {
    4237   [ +  -  +  - ]:          1 :                     return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
    4238                 :            :                 }
    4239                 :            :             }
    4240                 :            :         }
    4241                 :            :         // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
    4242   [ +  -  +  -  :       2630 :         if (nCheckLevel >= 3 && (coins.DynamicMemoryUsage() + ::ChainstateActive().CoinsTip().DynamicMemoryUsage()) <= ::ChainstateActive().m_coinstip_cache_size_bytes) {
          +  -  +  -  +  
                -  +  + ]
    4243   [ +  -  -  + ]:       2622 :             assert(coins.GetBestBlock() == pindex->GetBlockHash());
    4244   [ +  -  +  - ]:       2622 :             DisconnectResult res = ::ChainstateActive().DisconnectBlock(block, pindex, coins);
    4245         [ -  + ]:       2622 :             if (res == DISCONNECT_FAILED) {
    4246   [ -  -  -  - ]:          1 :                 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
    4247                 :            :             }
    4248         [ -  + ]:       2622 :             if (res == DISCONNECT_UNCLEAN) {
    4249                 :          0 :                 nGoodTransactions = 0;
    4250                 :          0 :                 pindexFailure = pindex;
    4251                 :            :             } else {
    4252                 :       2622 :                 nGoodTransactions += block.vtx.size();
    4253                 :            :             }
    4254                 :            :         }
    4255   [ +  -  +  - ]:       2630 :         if (ShutdownRequested()) return true;
    4256                 :            :     }
    4257         [ -  + ]:        330 :     if (pindexFailure)
    4258   [ #  #  #  # ]:          0 :         return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", ::ChainActive().Height() - pindexFailure->nHeight + 1, nGoodTransactions);
    4259                 :            : 
    4260                 :            :     // store block count as we move pindex at check level >= 4
    4261   [ +  -  +  + ]:        330 :     int block_count = ::ChainActive().Height() - pindex->nHeight;
    4262                 :            : 
    4263                 :            :     // check level 4: try reconnecting blocks
    4264         [ +  + ]:        330 :     if (nCheckLevel >= 4) {
    4265   [ +  -  +  + ]:       1458 :         while (pindex != ::ChainActive().Tip()) {
    4266   [ +  -  +  +  :       1384 :             const int percentageDone = std::max(1, std::min(99, 100 - (int)(((double)(::ChainActive().Height() - pindex->nHeight)) / (double)nCheckDepth * 50)));
                   +  - ]
    4267         [ +  + ]:        727 :             if (reportDone < percentageDone/10) {
    4268                 :            :                 // report every 10% step
    4269         [ +  - ]:          7 :                 LogPrintf("[%d%%]...", percentageDone); /* Continued */
    4270                 :          7 :                 reportDone = percentageDone/10;
    4271                 :            :             }
    4272   [ +  -  +  - ]:        727 :             uiInterface.ShowProgress(_("Verifying blocks...").translated, percentageDone, false);
    4273         [ +  - ]:        727 :             pindex = ::ChainActive().Next(pindex);
    4274         [ +  - ]:       1456 :             CBlock block;
    4275   [ +  -  -  + ]:        727 :             if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
    4276   [ #  #  #  # ]:          0 :                 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
    4277   [ +  -  +  -  :        727 :             if (!::ChainstateActive().ConnectBlock(block, state, pindex, coins, chainparams))
                   -  + ]
    4278   [ #  #  #  #  :          0 :                 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s (%s)", pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
                   #  # ]
    4279   [ +  -  +  - ]:        727 :             if (ShutdownRequested()) return true;
    4280                 :            :         }
    4281                 :            :     }
    4282                 :            : 
    4283         [ +  - ]:        330 :     LogPrintf("[DONE].\n");
    4284         [ +  - ]:        330 :     LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", block_count, nGoodTransactions);
    4285                 :            : 
    4286                 :            :     return true;
    4287                 :            : }
    4288                 :            : 
    4289                 :            : /** Apply the effects of a block on the utxo cache, ignoring that it may already have been applied. */
    4290                 :          8 : bool CChainState::RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params)
    4291                 :            : {
    4292                 :            :     // TODO: merge with ConnectBlock
    4293                 :         16 :     CBlock block;
    4294   [ +  -  -  + ]:          8 :     if (!ReadBlockFromDisk(block, pindex, params.GetConsensus())) {
    4295   [ -  -  -  - ]:          8 :         return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
    4296                 :            :     }
    4297                 :            : 
    4298         [ +  + ]:      20016 :     for (const CTransactionRef& tx : block.vtx) {
    4299         [ +  + ]:      20008 :         if (!tx->IsCoinBase()) {
    4300         [ +  + ]:      60000 :             for (const CTxIn &txin : tx->vin) {
    4301         [ +  - ]:      40000 :                 inputs.SpendCoin(txin.prevout);
    4302                 :            :             }
    4303                 :            :         }
    4304                 :            :         // Pass check = true as every addition may be an overwrite.
    4305         [ +  - ]:      20008 :         AddCoins(inputs, *tx, pindex->nHeight, true);
    4306                 :            :     }
    4307                 :            :     return true;
    4308                 :            : }
    4309                 :            : 
    4310                 :        632 : bool CChainState::ReplayBlocks(const CChainParams& params)
    4311                 :            : {
    4312                 :       1264 :     LOCK(cs_main);
    4313                 :            : 
    4314         [ +  - ]:        632 :     CCoinsView& db = this->CoinsDB();
    4315   [ +  -  +  - ]:       1264 :     CCoinsViewCache cache(&db);
    4316                 :            : 
    4317         [ +  - ]:       1264 :     std::vector<uint256> hashHeads = db.GetHeadBlocks();
    4318         [ +  + ]:        632 :     if (hashHeads.empty()) return true; // We're already in a consistent state.
    4319   [ -  +  -  - ]:          3 :     if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
    4320                 :            : 
    4321   [ +  -  +  - ]:          3 :     uiInterface.ShowProgress(_("Replaying blocks...").translated, 0, false);
    4322         [ +  - ]:          3 :     LogPrintf("Replaying blocks\n");
    4323                 :            : 
    4324                 :          3 :     const CBlockIndex* pindexOld = nullptr;  // Old tip during the interrupted flush.
    4325                 :          3 :     const CBlockIndex* pindexNew;            // New tip during the interrupted flush.
    4326                 :          3 :     const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
    4327                 :            : 
    4328         [ -  + ]:          3 :     if (m_blockman.m_block_index.count(hashHeads[0]) == 0) {
    4329         [ #  # ]:          0 :         return error("ReplayBlocks(): reorganization to unknown block requested");
    4330                 :            :     }
    4331         [ +  - ]:          3 :     pindexNew = m_blockman.m_block_index[hashHeads[0]];
    4332                 :            : 
    4333         [ +  - ]:          6 :     if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
    4334         [ -  + ]:          3 :         if (m_blockman.m_block_index.count(hashHeads[1]) == 0) {
    4335         [ #  # ]:          0 :             return error("ReplayBlocks(): reorganization from unknown block requested");
    4336                 :            :         }
    4337         [ +  - ]:          3 :         pindexOld = m_blockman.m_block_index[hashHeads[1]];
    4338         [ +  - ]:          3 :         pindexFork = LastCommonAncestor(pindexOld, pindexNew);
    4339         [ -  + ]:          3 :         assert(pindexFork != nullptr);
    4340                 :            :     }
    4341                 :            : 
    4342                 :            :     // Rollback along the old branch.
    4343         [ -  + ]:          3 :     while (pindexOld != pindexFork) {
    4344         [ #  # ]:          0 :         if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
    4345                 :          0 :             CBlock block;
    4346   [ #  #  #  # ]:          0 :             if (!ReadBlockFromDisk(block, pindexOld, params.GetConsensus())) {
    4347   [ #  #  #  # ]:          0 :                 return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
    4348                 :            :             }
    4349   [ #  #  #  # ]:          0 :             LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
    4350         [ #  # ]:          0 :             DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
    4351         [ #  # ]:          0 :             if (res == DISCONNECT_FAILED) {
    4352   [ #  #  #  # ]:          0 :                 return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
    4353                 :            :             }
    4354                 :            :             // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
    4355                 :            :             // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
    4356                 :            :             // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
    4357                 :            :             // the result is still a version of the UTXO set with the effects of that block undone.
    4358                 :            :         }
    4359                 :          0 :         pindexOld = pindexOld->pprev;
    4360                 :            :     }
    4361                 :            : 
    4362                 :            :     // Roll forward from the forking point to the new tip.
    4363         [ +  - ]:          3 :     int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
    4364         [ +  + ]:         11 :     for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
    4365         [ +  - ]:          8 :         const CBlockIndex* pindex = pindexNew->GetAncestor(nHeight);
    4366   [ +  -  +  - ]:          8 :         LogPrintf("Rolling forward %s (%i)\n", pindex->GetBlockHash().ToString(), nHeight);
    4367   [ +  -  +  - ]:          8 :         uiInterface.ShowProgress(_("Replaying blocks...").translated, (int) ((nHeight - nForkHeight) * 100.0 / (pindexNew->nHeight - nForkHeight)) , false);
    4368   [ +  -  +  - ]:          8 :         if (!RollforwardBlock(pindex, cache, params)) return false;
    4369                 :            :     }
    4370                 :            : 
    4371         [ +  - ]:          3 :     cache.SetBestBlock(pindexNew->GetBlockHash());
    4372         [ +  - ]:          3 :     cache.Flush();
    4373   [ +  -  +  - ]:          6 :     uiInterface.ShowProgress("", 100, false);
    4374                 :          3 :     return true;
    4375                 :            : }
    4376                 :            : 
    4377                 :            : //! Helper for CChainState::RewindBlockIndex
    4378                 :        147 : void CChainState::EraseBlockData(CBlockIndex* index)
    4379                 :            : {
    4380         [ -  + ]:        147 :     AssertLockHeld(cs_main);
    4381         [ -  + ]:        147 :     assert(!m_chain.Contains(index)); // Make sure this block isn't active
    4382                 :            : 
    4383                 :            :     // Reduce validity
    4384         [ +  - ]:        147 :     index->nStatus = std::min<unsigned int>(index->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (index->nStatus & ~BLOCK_VALID_MASK);
    4385                 :            :     // Remove have-data flags.
    4386                 :        147 :     index->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
    4387                 :            :     // Remove storage location.
    4388                 :        147 :     index->nFile = 0;
    4389                 :        147 :     index->nDataPos = 0;
    4390                 :        147 :     index->nUndoPos = 0;
    4391                 :            :     // Remove various other things
    4392                 :        147 :     index->nTx = 0;
    4393                 :        147 :     index->nChainTx = 0;
    4394                 :        147 :     index->nSequenceId = 0;
    4395                 :            :     // Make sure it gets written.
    4396                 :        147 :     setDirtyBlockIndex.insert(index);
    4397                 :            :     // Update indexes
    4398                 :        147 :     setBlockIndexCandidates.erase(index);
    4399                 :        147 :     auto ret = m_blockman.m_blocks_unlinked.equal_range(index->pprev);
    4400                 :        147 :     while (ret.first != ret.second) {
    4401         [ #  # ]:          0 :         if (ret.first->second == index) {
    4402                 :          0 :             m_blockman.m_blocks_unlinked.erase(ret.first++);
    4403                 :            :         } else {
    4404         [ -  + ]:        147 :             ++ret.first;
    4405                 :            :         }
    4406                 :            :     }
    4407                 :            :     // Mark parent as eligible for main chain again
    4408   [ +  -  +  -  :        147 :     if (index->pprev && index->pprev->IsValid(BLOCK_VALID_TRANSACTIONS) && index->pprev->HaveTxsDownloaded()) {
             +  -  +  - ]
    4409                 :        147 :         setBlockIndexCandidates.insert(index->pprev);
    4410                 :            :     }
    4411                 :        147 : }
    4412                 :            : 
    4413                 :        624 : bool CChainState::RewindBlockIndex(const CChainParams& params)
    4414                 :            : {
    4415                 :            :     // Note that during -reindex-chainstate we are called with an empty m_chain!
    4416                 :            : 
    4417                 :            :     // First erase all post-segwit blocks without witness not in the main chain,
    4418                 :            :     // as this can we done without costly DisconnectTip calls. Active
    4419                 :            :     // blocks will be dealt with below (releasing cs_main in between).
    4420                 :        624 :     {
    4421                 :        624 :         LOCK(cs_main);
    4422         [ +  + ]:      80076 :         for (const auto& entry : m_blockman.m_block_index) {
    4423   [ +  +  +  +  :      79452 :             if (IsWitnessEnabled(entry.second->pprev, params.GetConsensus()) && !(entry.second->nStatus & BLOCK_OPT_WITNESS) && !m_chain.Contains(entry.second)) {
                   -  + ]
    4424         [ #  # ]:          0 :                 EraseBlockData(entry.second);
    4425                 :            :             }
    4426                 :            :         }
    4427                 :            :     }
    4428                 :            : 
    4429                 :            :     // Find what height we need to reorganize to.
    4430                 :        624 :     CBlockIndex *tip;
    4431                 :        624 :     int nHeight = 1;
    4432                 :        624 :     {
    4433                 :        624 :         LOCK(cs_main);
    4434         [ +  + ]:      78186 :         while (nHeight <= m_chain.Height()) {
    4435                 :            :             // Although SCRIPT_VERIFY_WITNESS is now generally enforced on all
    4436                 :            :             // blocks in ConnectBlock, we don't need to go back and
    4437                 :            :             // re-download/re-verify blocks from before segwit actually activated.
    4438   [ +  -  +  +  :     231708 :             if (IsWitnessEnabled(m_chain[nHeight - 1], params.GetConsensus()) && !(m_chain[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
             +  -  +  + ]
    4439                 :            :                 break;
    4440                 :            :             }
    4441                 :      77562 :             nHeight++;
    4442                 :            :         }
    4443                 :            : 
    4444   [ +  +  +  - ]:       1011 :         tip = m_chain.Tip();
    4445                 :            :     }
    4446                 :            :     // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
    4447                 :            : 
    4448                 :       1248 :     BlockValidationState state;
    4449                 :            :     // Loop until the tip is below nHeight, or we reach a pruned block.
    4450   [ +  -  +  - ]:        771 :     while (!ShutdownRequested()) {
    4451                 :        771 :         {
    4452         [ +  - ]:        771 :             LOCK(cs_main);
    4453   [ +  -  +  - ]:        918 :             LOCK(m_mempool.cs);
    4454                 :            :             // Make sure nothing changed from under us (this won't happen because RewindBlockIndex runs before importing/network are active)
    4455   [ +  +  -  + ]:       1305 :             assert(tip == m_chain.Tip());
    4456   [ +  +  +  + ]:        771 :             if (tip == nullptr || tip->nHeight < nHeight) break;
    4457   [ -  +  -  - ]:        147 :             if (fPruneMode && !(tip->nStatus & BLOCK_HAVE_DATA)) {
    4458                 :            :                 // If pruning, don't try rewinding past the HAVE_DATA point;
    4459                 :            :                 // since older blocks can't be served anyway, there's
    4460                 :            :                 // no need to walk further, and trying to DisconnectTip()
    4461                 :            :                 // will fail (and require a needless reindex/redownload
    4462                 :            :                 // of the blockchain).
    4463                 :            :                 break;
    4464                 :            :             }
    4465                 :            : 
    4466                 :            :             // Disconnect block
    4467   [ +  -  -  + ]:        147 :             if (!DisconnectTip(state, params, nullptr)) {
    4468   [ #  #  #  #  :          0 :                 return error("RewindBlockIndex: unable to disconnect block at height %i (%s)", tip->nHeight, state.ToString());
                   #  # ]
    4469                 :            :             }
    4470                 :            : 
    4471                 :            :             // Reduce validity flag and have-data flags.
    4472                 :            :             // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
    4473                 :            :             // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
    4474                 :            :             // Note: If we encounter an insufficiently validated block that
    4475                 :            :             // is on m_chain, it must be because we are a pruning node, and
    4476                 :            :             // this block or some successor doesn't HAVE_DATA, so we were unable to
    4477                 :            :             // rewind all the way.  Blocks remaining on m_chain at this point
    4478                 :            :             // must not have their validity reduced.
    4479         [ +  - ]:        147 :             EraseBlockData(tip);
    4480                 :            : 
    4481         [ +  - ]:        147 :             tip = tip->pprev;
    4482                 :            :         }
    4483                 :            :         // Make sure the queue of validation callbacks doesn't grow unboundedly.
    4484         [ +  - ]:        147 :         LimitValidationInterfaceQueue();
    4485                 :            : 
    4486                 :            :         // Occasionally flush state to disk.
    4487   [ +  -  +  - ]:        147 :         if (!FlushStateToDisk(params, state, FlushStateMode::PERIODIC)) {
    4488   [ #  #  #  # ]:          0 :             LogPrintf("RewindBlockIndex: unable to flush state to disk (%s)\n", state.ToString());
    4489                 :          0 :             return false;
    4490                 :            :         }
    4491                 :            :     }
    4492                 :            : 
    4493                 :        624 :     {
    4494         [ +  - ]:        624 :         LOCK(cs_main);
    4495   [ +  +  +  - ]:        624 :         if (m_chain.Tip() != nullptr) {
    4496                 :            :             // We can't prune block index candidates based on our tip if we have
    4497                 :            :             // no tip due to m_chain being empty!
    4498         [ +  - ]:        387 :             PruneBlockIndexCandidates();
    4499                 :            : 
    4500         [ +  - ]:        387 :             CheckBlockIndex(params.GetConsensus());
    4501                 :            : 
    4502                 :            :             // FlushStateToDisk can possibly read ::ChainActive(). Be conservative
    4503                 :            :             // and skip it here, we're about to -reindex-chainstate anyway, so
    4504                 :            :             // it'll get called a bunch real soon.
    4505   [ +  -  +  - ]:       1011 :             BlockValidationState state;
    4506   [ +  -  -  + ]:        387 :             if (!FlushStateToDisk(params, state, FlushStateMode::ALWAYS)) {
    4507   [ #  #  #  # ]:          0 :                 LogPrintf("RewindBlockIndex: unable to flush state to disk (%s)\n", state.ToString());
    4508         [ #  # ]:          0 :                 return false;
    4509                 :            :             }
    4510                 :            :         }
    4511                 :            :     }
    4512                 :            : 
    4513                 :        624 :     return true;
    4514                 :            : }
    4515                 :            : 
    4516                 :        725 : void CChainState::UnloadBlockIndex() {
    4517                 :        725 :     nBlockSequenceId = 1;
    4518                 :        725 :     setBlockIndexCandidates.clear();
    4519                 :        725 : }
    4520                 :            : 
    4521                 :            : // May NOT be used after any connections are up as much
    4522                 :            : // of the peer-processing logic assumes a consistent
    4523                 :            : // block index state
    4524                 :        722 : void UnloadBlockIndex(CTxMemPool* mempool, ChainstateManager& chainman)
    4525                 :            : {
    4526                 :        722 :     LOCK(cs_main);
    4527         [ +  - ]:        722 :     chainman.Unload();
    4528                 :        722 :     pindexBestInvalid = nullptr;
    4529                 :        722 :     pindexBestHeader = nullptr;
    4530   [ +  -  +  - ]:        722 :     if (mempool) mempool->clear();
    4531         [ +  + ]:        722 :     vinfoBlockFile.clear();
    4532                 :        722 :     nLastBlockFile = 0;
    4533                 :        722 :     setDirtyBlockIndex.clear();
    4534                 :        722 :     setDirtyFileInfo.clear();
    4535         [ +  - ]:        722 :     versionbitscache.Clear();
    4536         [ +  + ]:      21660 :     for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
    4537                 :      20938 :         warningcache[b].clear();
    4538                 :            :     }
    4539         [ +  - ]:        722 :     fHavePruned = false;
    4540                 :        722 : }
    4541                 :            : 
    4542                 :        632 : bool ChainstateManager::LoadBlockIndex(const CChainParams& chainparams)
    4543                 :            : {
    4544         [ +  + ]:        632 :     AssertLockHeld(cs_main);
    4545                 :            :     // Load block index from databases
    4546         [ +  + ]:        632 :     bool needs_init = fReindex;
    4547         [ +  + ]:        632 :     if (!fReindex) {
    4548                 :        624 :         bool ret = LoadBlockIndexDB(*this, chainparams);
    4549         [ +  - ]:        624 :         if (!ret) return false;
    4550                 :        624 :         needs_init = m_blockman.m_block_index.empty();
    4551                 :            :     }
    4552                 :            : 
    4553         [ +  + ]:        632 :     if (needs_init) {
    4554                 :            :         // Everything here is for *new* reindex/DBs. Thus, though
    4555                 :            :         // LoadBlockIndexDB may have set fReindex if we shut down
    4556                 :            :         // mid-reindex previously, we don't check fReindex and
    4557                 :            :         // instead only check it prior to LoadBlockIndexDB to set
    4558                 :            :         // needs_init.
    4559                 :            : 
    4560                 :        243 :         LogPrintf("Initializing databases...\n");
    4561                 :            :     }
    4562                 :            :     return true;
    4563                 :            : }
    4564                 :            : 
    4565                 :        723 : bool CChainState::LoadGenesisBlock(const CChainParams& chainparams)
    4566                 :            : {
    4567                 :       1446 :     LOCK(cs_main);
    4568                 :            : 
    4569                 :            :     // Check whether we're already initialized by checking for genesis in
    4570                 :            :     // m_blockman.m_block_index. Note that we can't use m_chain here, since it is
    4571                 :            :     // set based on the coins db, not the block index db, which is the only
    4572                 :            :     // thing loaded at this point.
    4573   [ +  -  +  + ]:       1446 :     if (m_blockman.m_block_index.count(chainparams.GenesisBlock().GetHash()))
    4574                 :            :         return true;
    4575                 :            : 
    4576                 :        326 :     try {
    4577         [ +  - ]:        326 :         const CBlock& block = chainparams.GenesisBlock();
    4578         [ +  - ]:        326 :         FlatFilePos blockPos = SaveBlockToDisk(block, 0, chainparams, nullptr);
    4579         [ -  + ]:        326 :         if (blockPos.IsNull())
    4580         [ #  # ]:          0 :             return error("%s: writing genesis block to disk failed", __func__);
    4581         [ +  - ]:        326 :         CBlockIndex *pindex = m_blockman.AddToBlockIndex(block);
    4582         [ +  - ]:        326 :         ReceivedBlockTransactions(block, pindex, blockPos, chainparams.GetConsensus());
    4583         [ -  - ]:          0 :     } catch (const std::runtime_error& e) {
    4584         [ -  - ]:          0 :         return error("%s: failed to write genesis block: %s", __func__, e.what());
    4585                 :            :     }
    4586                 :            : 
    4587                 :            :     return true;
    4588                 :            : }
    4589                 :            : 
    4590                 :        722 : bool LoadGenesisBlock(const CChainParams& chainparams)
    4591                 :            : {
    4592                 :        722 :     return ::ChainstateActive().LoadGenesisBlock(chainparams);
    4593                 :            : }
    4594                 :            : 
    4595                 :          9 : void LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, FlatFilePos* dbp)
    4596                 :            : {
    4597                 :            :     // Map of disk positions for blocks with unknown parent (only used for reindex)
    4598   [ +  -  +  - ]:          9 :     static std::multimap<uint256, FlatFilePos> mapBlocksUnknownParent;
    4599                 :          9 :     int64_t nStart = GetTimeMillis();
    4600                 :            : 
    4601                 :          9 :     int nLoaded = 0;
    4602                 :          9 :     try {
    4603                 :            :         // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
    4604         [ +  - ]:         18 :         CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
    4605                 :          9 :         uint64_t nRewind = blkdat.GetPos();
    4606         [ +  + ]:       1432 :         while (!blkdat.eof()) {
    4607   [ +  -  -  + ]:       1431 :             if (ShutdownRequested()) return;
    4608                 :            : 
    4609                 :       1431 :             blkdat.SetPos(nRewind);
    4610                 :       1431 :             nRewind++; // start one byte further next time, in case of failure
    4611         [ +  + ]:       1431 :             blkdat.SetLimit(); // remove former limit
    4612                 :       1431 :             unsigned int nSize = 0;
    4613                 :       1431 :             try {
    4614                 :            :                 // locate a header
    4615                 :       1431 :                 unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
    4616         [ +  + ]:       1431 :                 blkdat.FindByte(chainparams.MessageStart()[0]);
    4617         [ +  - ]:       1423 :                 nRewind = blkdat.GetPos()+1;
    4618         [ +  - ]:       1423 :                 blkdat >> buf;
    4619         [ -  + ]:       1423 :                 if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
    4620                 :          0 :                     continue;
    4621                 :            :                 // read size
    4622         [ +  - ]:       1423 :                 blkdat >> nSize;
    4623         [ -  + ]:       1423 :                 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
    4624                 :          0 :                     continue;
    4625         [ -  + ]:          8 :             } catch (const std::exception&) {
    4626                 :            :                 // no valid block header found; don't complain
    4627                 :          8 :                 break;
    4628                 :            :             }
    4629                 :       1423 :             try {
    4630                 :            :                 // read block
    4631         [ +  + ]:       1423 :                 uint64_t nBlockPos = blkdat.GetPos();
    4632         [ +  + ]:       1423 :                 if (dbp)
    4633                 :       1322 :                     dbp->nPos = nBlockPos;
    4634         [ +  - ]:       1423 :                 blkdat.SetLimit(nBlockPos + nSize);
    4635         [ +  - ]:       2855 :                 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
    4636         [ +  - ]:       1423 :                 CBlock& block = *pblock;
    4637         [ +  - ]:       1423 :                 blkdat >> block;
    4638         [ +  - ]:       1423 :                 nRewind = blkdat.GetPos();
    4639                 :            : 
    4640         [ +  - ]:       1423 :                 uint256 hash = block.GetHash();
    4641                 :       1423 :                 {
    4642         [ +  - ]:       1423 :                     LOCK(cs_main);
    4643                 :            :                     // detect out of order blocks, and store them for later
    4644   [ +  +  -  + ]:       1423 :                     if (hash != chainparams.GetConsensus().hashGenesisBlock && !LookupBlockIndex(block.hashPrevBlock)) {
    4645   [ #  #  #  #  :          0 :                         LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
          #  #  #  #  #  
                      # ]
    4646                 :            :                                 block.hashPrevBlock.ToString());
    4647         [ #  # ]:          0 :                         if (dbp)
    4648         [ #  # ]:          0 :                             mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
    4649   [ #  #  #  # ]:          0 :                         continue;
    4650                 :            :                     }
    4651                 :            : 
    4652                 :            :                     // process in case the block isn't known yet
    4653                 :       1423 :                     CBlockIndex* pindex = LookupBlockIndex(hash);
    4654   [ +  +  -  + ]:       1423 :                     if (!pindex || (pindex->nStatus & BLOCK_HAVE_DATA) == 0) {
    4655         [ +  - ]:       1422 :                       BlockValidationState state;
    4656   [ +  -  +  -  :       4266 :                       if (::ChainstateActive().AcceptBlock(pblock, state, chainparams, nullptr, true, dbp, nullptr)) {
          +  -  +  -  +  
                      - ]
    4657                 :       1422 :                           nLoaded++;
    4658                 :            :                       }
    4659         [ +  - ]:       1422 :                       if (state.IsError()) {
    4660                 :            :                           break;
    4661                 :            :                       }
    4662   [ -  +  -  - ]:          1 :                     } else if (hash != chainparams.GetConsensus().hashGenesisBlock && pindex->nHeight % 1000 == 0) {
    4663   [ -  -  -  -  :       1423 :                       LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), pindex->nHeight);
          -  -  -  -  +  
                      - ]
    4664                 :            :                     }
    4665                 :            :                 }
    4666                 :            : 
    4667                 :            :                 // Activate the genesis block so normal node progress can continue
    4668         [ +  + ]:       1423 :                 if (hash == chainparams.GetConsensus().hashGenesisBlock) {
    4669         [ +  - ]:          9 :                     BlockValidationState state;
    4670   [ +  -  -  +  :          9 :                     if (!ActivateBestChain(state, chainparams, nullptr)) {
                   +  - ]
    4671                 :            :                         break;
    4672                 :            :                     }
    4673                 :            :                 }
    4674                 :            : 
    4675         [ +  - ]:       1423 :                 NotifyHeaderTip();
    4676                 :            : 
    4677                 :            :                 // Recursively process earlier encountered successors of this block
    4678   [ +  -  +  - ]:       2846 :                 std::deque<uint256> queue;
    4679         [ +  - ]:       1423 :                 queue.push_back(hash);
    4680         [ +  + ]:       2846 :                 while (!queue.empty()) {
    4681                 :       1423 :                     uint256 head = queue.front();
    4682                 :       1423 :                     queue.pop_front();
    4683                 :       1423 :                     std::pair<std::multimap<uint256, FlatFilePos>::iterator, std::multimap<uint256, FlatFilePos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
    4684                 :       1423 :                     while (range.first != range.second) {
    4685                 :          0 :                         std::multimap<uint256, FlatFilePos>::iterator it = range.first;
    4686   [ +  -  -  - ]:       1423 :                         std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
    4687   [ #  #  #  # ]:          0 :                         if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
    4688                 :            :                         {
    4689   [ #  #  #  #  :          0 :                             LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
          #  #  #  #  #  
                #  #  # ]
    4690                 :            :                                     head.ToString());
    4691         [ #  # ]:          0 :                             LOCK(cs_main);
    4692   [ #  #  #  # ]:          0 :                             BlockValidationState dummy;
    4693   [ #  #  #  #  :          0 :                             if (::ChainstateActive().AcceptBlock(pblockrecursive, dummy, chainparams, nullptr, true, &it->second, nullptr))
          #  #  #  #  #  
                      # ]
    4694                 :            :                             {
    4695                 :          0 :                                 nLoaded++;
    4696         [ #  # ]:          0 :                                 queue.push_back(pblockrecursive->GetHash());
    4697                 :            :                             }
    4698                 :            :                         }
    4699                 :          0 :                         range.first++;
    4700                 :          0 :                         mapBlocksUnknownParent.erase(it);
    4701         [ #  # ]:          0 :                         NotifyHeaderTip();
    4702                 :            :                     }
    4703                 :            :                 }
    4704         [ -  - ]:          0 :             } catch (const std::exception& e) {
    4705         [ -  - ]:          0 :                 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
    4706                 :            :             }
    4707                 :            :         }
    4708         [ -  - ]:          0 :     } catch (const std::runtime_error& e) {
    4709   [ -  -  -  -  :          0 :         AbortNode(std::string("System error: ") + e.what());
                   -  - ]
    4710                 :            :     }
    4711                 :          9 :     LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
    4712                 :            : }
    4713                 :            : 
    4714                 :     265417 : void CChainState::CheckBlockIndex(const Consensus::Params& consensusParams)
    4715                 :            : {
    4716         [ +  + ]:     265417 :     if (!fCheckBlockIndex) {
    4717                 :            :         return;
    4718                 :            :     }
    4719                 :            : 
    4720                 :     264826 :     LOCK(cs_main);
    4721                 :            : 
    4722                 :            :     // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
    4723                 :            :     // so we have the genesis block in m_blockman.m_block_index but no active chain. (A few of the
    4724                 :            :     // tests when iterating the block tree require that m_chain has been initialized.)
    4725         [ +  + ]:     264826 :     if (m_chain.Height() < 0) {
    4726         [ -  + ]:         16 :         assert(m_blockman.m_block_index.size() <= 1);
    4727         [ +  - ]:     265433 :         return;
    4728                 :            :     }
    4729                 :            : 
    4730                 :            :     // Build forward-pointing map of the entire block tree.
    4731         [ +  - ]:     529620 :     std::multimap<CBlockIndex*,CBlockIndex*> forward;
    4732         [ +  + ]:  162009770 :     for (const std::pair<const uint256, CBlockIndex*>& entry : m_blockman.m_block_index) {
    4733         [ +  - ]:  161744960 :         forward.insert(std::make_pair(entry.second->pprev, entry.second));
    4734                 :            :     }
    4735                 :            : 
    4736         [ -  + ]:     264810 :     assert(forward.size() == m_blockman.m_block_index.size());
    4737                 :            : 
    4738                 :     264810 :     std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
    4739                 :     264810 :     CBlockIndex *pindex = rangeGenesis.first->second;
    4740                 :     264810 :     rangeGenesis.first++;
    4741         [ -  + ]:     264810 :     assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent nullptr.
    4742                 :            : 
    4743                 :            :     // Iterate over the entire block tree, using depth-first search.
    4744                 :            :     // Along the way, remember whether there are blocks on the path from genesis
    4745                 :            :     // block being explored which are the first to have certain properties.
    4746                 :            :     size_t nNodes = 0;
    4747                 :            :     int nHeight = 0;
    4748                 :            :     CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
    4749                 :            :     CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
    4750                 :            :     CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
    4751                 :            :     CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
    4752                 :            :     CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
    4753                 :            :     CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
    4754                 :            :     CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
    4755         [ +  + ]:  162009770 :     while (pindex != nullptr) {
    4756                 :  161744960 :         nNodes++;
    4757   [ +  +  +  + ]:  161744960 :         if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
    4758   [ +  +  +  + ]:  161744960 :         if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
    4759   [ +  +  +  + ]:  161744960 :         if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
    4760   [ +  +  +  -  :  161744960 :         if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
                   -  + ]
    4761   [ +  +  +  +  :  161744960 :         if (pindex->pprev != nullptr && pindexFirstNotTransactionsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
                   +  + ]
    4762   [ +  +  +  +  :  161744960 :         if (pindex->pprev != nullptr && pindexFirstNotChainValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
                   +  + ]
    4763   [ +  +  +  +  :  161744960 :         if (pindex->pprev != nullptr && pindexFirstNotScriptsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
                   +  + ]
    4764                 :            : 
    4765                 :            :         // Begin: actual consistency checks.
    4766         [ +  + ]:  161744960 :         if (pindex->pprev == nullptr) {
    4767                 :            :             // Genesis block checks.
    4768         [ -  + ]:     264810 :             assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
    4769   [ +  -  -  + ]:     529620 :             assert(pindex == m_chain.Genesis()); // The current active chain's genesis block must be this block.
    4770                 :            :         }
    4771   [ +  +  -  + ]:  161744960 :         if (!pindex->HaveTxsDownloaded()) assert(pindex->nSequenceId <= 0); // nSequenceId can't be set positive for blocks that aren't linked (negative is used for preciousblock)
    4772                 :            :         // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
    4773                 :            :         // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
    4774         [ +  + ]:  161744960 :         if (!fHavePruned) {
    4775                 :            :             // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
    4776         [ -  + ]:  148598874 :             assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
    4777         [ -  + ]:  148598874 :             assert(pindexFirstMissing == pindexFirstNeverProcessed);
    4778                 :            :         } else {
    4779                 :            :             // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
    4780   [ +  +  -  + ]:   13146086 :             if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
    4781                 :            :         }
    4782   [ +  +  -  + ]:  161744960 :         if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
    4783         [ -  + ]:  161744960 :         assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
    4784                 :            :         // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to HaveTxsDownloaded().
    4785         [ -  + ]:  161744960 :         assert((pindexFirstNeverProcessed == nullptr) == pindex->HaveTxsDownloaded());
    4786         [ -  + ]:  161744960 :         assert((pindexFirstNotTransactionsValid == nullptr) == pindex->HaveTxsDownloaded());
    4787         [ -  + ]:  161744960 :         assert(pindex->nHeight == nHeight); // nHeight must be consistent.
    4788   [ +  +  +  -  :  161744960 :         assert(pindex->pprev == nullptr || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
                   -  + ]
    4789   [ +  +  +  -  :  161744960 :         assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
                   -  + ]
    4790         [ -  + ]:  161744960 :         assert(pindexFirstNotTreeValid == nullptr); // All m_blockman.m_block_index entries must at least be TREE valid
    4791                 :  161744960 :         if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
    4792   [ +  +  -  + ]:  161744960 :         if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
    4793   [ +  +  -  + ]:  161744960 :         if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
    4794         [ +  + ]:  161744960 :         if (pindexFirstInvalid == nullptr) {
    4795                 :            :             // Checks for not-invalid blocks.
    4796         [ -  + ]:  148192383 :             assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
    4797                 :            :         }
    4798   [ +  -  +  -  :  323489920 :         if (!CBlockIndexWorkComparator()(pindex, m_chain.Tip()) && pindexFirstNeverProcessed == nullptr) {
             +  +  +  + ]
    4799         [ +  + ]:    1199357 :             if (pindexFirstInvalid == nullptr) {
    4800                 :            :                 // If this block sorts at least as good as the current tip and
    4801                 :            :                 // is valid and we have all data for its parents, it must be in
    4802                 :            :                 // setBlockIndexCandidates.  m_chain.Tip() must also be there
    4803                 :            :                 // even if some data has been pruned.
    4804   [ +  +  +  -  :     638238 :                 if (pindexFirstMissing == nullptr || pindex == m_chain.Tip()) {
                   +  + ]
    4805   [ +  -  -  + ]:     621635 :                     assert(setBlockIndexCandidates.count(pindex));
    4806                 :            :                 }
    4807                 :            :                 // If some parent is missing, then it could be that this block was in
    4808                 :            :                 // setBlockIndexCandidates but had to be removed because of the missing data.
    4809                 :            :                 // In this case it must be in m_blocks_unlinked -- see test below.
    4810                 :            :             }
    4811                 :            :         } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
    4812   [ +  -  -  + ]:  160545603 :             assert(setBlockIndexCandidates.count(pindex) == 0);
    4813                 :            :         }
    4814                 :            :         // Check whether this block is in m_blocks_unlinked.
    4815                 :  161744960 :         std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = m_blockman.m_blocks_unlinked.equal_range(pindex->pprev);
    4816                 :  161744960 :         bool foundInUnlinked = false;
    4817         [ +  + ]:  161746273 :         while (rangeUnlinked.first != rangeUnlinked.second) {
    4818         [ -  + ]:     398967 :             assert(rangeUnlinked.first->first == pindex->pprev);
    4819         [ +  + ]:     398967 :             if (rangeUnlinked.first->second == pindex) {
    4820                 :            :                 foundInUnlinked = true;
    4821                 :            :                 break;
    4822                 :            :             }
    4823                 :       1313 :             rangeUnlinked.first++;
    4824                 :            :         }
    4825   [ +  +  +  +  :  161744960 :         if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
                   +  + ]
    4826                 :            :             // If this block has block data available, some parent was never received, and has no invalid parents, it must be in m_blocks_unlinked.
    4827         [ -  + ]:     126294 :             assert(foundInUnlinked);
    4828                 :            :         }
    4829   [ +  +  -  + ]:  161744960 :         if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in m_blocks_unlinked if we don't HAVE_DATA
    4830   [ +  +  -  + ]:  161744960 :         if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in m_blocks_unlinked.
    4831   [ +  +  +  +  :  161744960 :         if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
                   +  + ]
    4832                 :            :             // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
    4833         [ -  + ]:    5647813 :             assert(fHavePruned); // We must have pruned.
    4834                 :            :             // This block may have entered m_blocks_unlinked if:
    4835                 :            :             //  - it has a descendant that at some point had more work than the
    4836                 :            :             //    tip, and
    4837                 :            :             //  - we tried switching to that descendant but were missing
    4838                 :            :             //    data for some intermediate block between m_chain and the
    4839                 :            :             //    tip.
    4840                 :            :             // So if this block is itself better than m_chain.Tip() and it wasn't in
    4841                 :            :             // setBlockIndexCandidates, then it must be in m_blocks_unlinked.
    4842   [ +  -  +  -  :   11295626 :             if (!CBlockIndexWorkComparator()(pindex, m_chain.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
          +  +  +  -  +  
                      + ]
    4843         [ +  + ]:     322889 :                 if (pindexFirstInvalid == nullptr) {
    4844         [ -  + ]:       2048 :                     assert(foundInUnlinked);
    4845                 :            :                 }
    4846                 :            :             }
    4847                 :            :         }
    4848                 :            :         // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
    4849                 :            :         // End: actual consistency checks.
    4850                 :            : 
    4851                 :            :         // Try descending into the first subnode.
    4852                 :  161744960 :         std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
    4853         [ +  + ]:  161744960 :         if (range.first != range.second) {
    4854                 :            :             // A subnode was found.
    4855                 :  143195038 :             pindex = range.first->second;
    4856                 :  143195038 :             nHeight++;
    4857                 :  143195038 :             continue;
    4858                 :            :         }
    4859                 :            :         // This is a leaf node.
    4860                 :            :         // Move upwards until we reach a node of which we have not yet visited the last child.
    4861         [ +  + ]:  162009770 :         while (pindex) {
    4862                 :            :             // We are going to either move to a parent or a sibling of pindex.
    4863                 :            :             // If pindex was the first with a certain property, unset the corresponding variable.
    4864         [ +  + ]:  161744960 :             if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
    4865         [ +  + ]:  161744960 :             if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
    4866         [ +  + ]:  161744960 :             if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
    4867         [ -  + ]:  161744960 :             if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
    4868         [ +  + ]:  161744960 :             if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
    4869         [ +  + ]:  161744960 :             if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
    4870         [ +  + ]:  161744960 :             if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
    4871                 :            :             // Find our parent.
    4872                 :  161744960 :             CBlockIndex* pindexPar = pindex->pprev;
    4873                 :            :             // Find which child we just visited.
    4874                 :  161744960 :             std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
    4875         [ +  + ]:  187512690 :             while (rangePar.first->second != pindex) {
    4876         [ -  + ]:   25767730 :                 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
    4877                 :   25767730 :                 rangePar.first++;
    4878                 :            :             }
    4879                 :            :             // Proceed to the next one.
    4880                 :  161744960 :             rangePar.first++;
    4881         [ +  + ]:  161744960 :             if (rangePar.first != rangePar.second) {
    4882                 :            :                 // Move to the sibling.
    4883                 :   18285112 :                 pindex = rangePar.first->second;
    4884                 :   18285112 :                 break;
    4885                 :            :             } else {
    4886                 :            :                 // Move up further.
    4887                 :  143459848 :                 pindex = pindexPar;
    4888                 :  143459848 :                 nHeight--;
    4889                 :  143459848 :                 continue;
    4890                 :            :             }
    4891                 :            :         }
    4892                 :            :     }
    4893                 :            : 
    4894                 :            :     // Check that we actually traversed the entire map.
    4895         [ -  + ]:     264810 :     assert(nNodes == forward.size());
    4896                 :            : }
    4897                 :            : 
    4898                 :        737 : std::string CChainState::ToString()
    4899                 :            : {
    4900         [ -  + ]:        737 :     CBlockIndex* tip = m_chain.Tip();
    4901                 :          0 :     return strprintf("Chainstate [%s] @ height %d (%s)",
    4902         [ +  + ]:        737 :         m_from_snapshot_blockhash.IsNull() ? "ibd" : "snapshot",
    4903   [ -  -  -  +  :       2211 :         tip ? tip->nHeight : -1, tip ? tip->GetBlockHash().ToString() : "null");
                   +  - ]
    4904                 :            : }
    4905                 :            : 
    4906                 :          5 : bool CChainState::ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
    4907                 :            : {
    4908         [ -  + ]:          5 :     if (coinstip_size == m_coinstip_cache_size_bytes &&
    4909         [ #  # ]:          0 :             coinsdb_size == m_coinsdb_cache_size_bytes) {
    4910                 :            :         // Cache sizes are unchanged, no need to continue.
    4911                 :            :         return true;
    4912                 :            :     }
    4913                 :          5 :     size_t old_coinstip_size = m_coinstip_cache_size_bytes;
    4914                 :          5 :     m_coinstip_cache_size_bytes = coinstip_size;
    4915                 :          5 :     m_coinsdb_cache_size_bytes = coinsdb_size;
    4916                 :          5 :     CoinsDB().ResizeCache(coinsdb_size);
    4917                 :            : 
    4918         [ +  - ]:          5 :     LogPrintf("[%s] resized coinsdb cache to %.1f MiB\n",
    4919                 :          5 :         this->ToString(), coinsdb_size * (1.0 / 1024 / 1024));
    4920         [ +  - ]:          5 :     LogPrintf("[%s] resized coinstip cache to %.1f MiB\n",
    4921                 :          5 :         this->ToString(), coinstip_size * (1.0 / 1024 / 1024));
    4922                 :            : 
    4923         [ +  - ]:         10 :     BlockValidationState state;
    4924         [ +  - ]:          5 :     const CChainParams& chainparams = Params();
    4925                 :            : 
    4926                 :          5 :     bool ret;
    4927                 :            : 
    4928         [ +  + ]:          5 :     if (coinstip_size > old_coinstip_size) {
    4929                 :            :         // Likely no need to flush if cache sizes have grown.
    4930         [ +  - ]:          1 :         ret = FlushStateToDisk(chainparams, state, FlushStateMode::IF_NEEDED);
    4931                 :            :     } else {
    4932                 :            :         // Otherwise, flush state to disk and deallocate the in-memory coins map.
    4933         [ +  - ]:          4 :         ret = FlushStateToDisk(chainparams, state, FlushStateMode::ALWAYS);
    4934         [ +  - ]:          4 :         CoinsTip().ReallocateCache();
    4935                 :            :     }
    4936                 :          5 :     return ret;
    4937                 :            : }
    4938                 :            : 
    4939                 :        672 : std::string CBlockFileInfo::ToString() const
    4940                 :            : {
    4941   [ +  -  +  - ]:       1344 :     return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, FormatISO8601Date(nTimeFirst), FormatISO8601Date(nTimeLast));
    4942                 :            : }
    4943                 :            : 
    4944                 :          2 : CBlockFileInfo* GetBlockFileInfo(size_t n)
    4945                 :            : {
    4946                 :          2 :     LOCK(cs_LastBlockFile);
    4947                 :            : 
    4948   [ +  -  +  - ]:          4 :     return &vinfoBlockFile.at(n);
    4949                 :            : }
    4950                 :            : 
    4951                 :        814 : ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
    4952                 :            : {
    4953                 :        814 :     LOCK(cs_main);
    4954   [ +  -  +  -  :       2442 :     return VersionBitsState(::ChainActive().Tip(), params, pos, versionbitscache);
             +  -  +  - ]
    4955                 :            : }
    4956                 :            : 
    4957                 :        314 : BIP9Stats VersionBitsTipStatistics(const Consensus::Params& params, Consensus::DeploymentPos pos)
    4958                 :            : {
    4959                 :        314 :     LOCK(cs_main);
    4960   [ +  -  +  -  :        942 :     return VersionBitsStatistics(::ChainActive().Tip(), params, pos);
                   +  - ]
    4961                 :            : }
    4962                 :            : 
    4963                 :        814 : int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos)
    4964                 :            : {
    4965                 :        814 :     LOCK(cs_main);
    4966   [ +  -  +  -  :       2442 :     return VersionBitsStateSinceHeight(::ChainActive().Tip(), params, pos, versionbitscache);
             +  -  +  - ]
    4967                 :            : }
    4968                 :            : 
    4969                 :            : static const uint64_t MEMPOOL_DUMP_VERSION = 1;
    4970                 :            : 
    4971                 :        623 : bool LoadMempool(CTxMemPool& pool)
    4972                 :            : {
    4973                 :        623 :     const CChainParams& chainparams = Params();
    4974         [ +  - ]:        623 :     int64_t nExpiryTimeout = gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
    4975   [ +  -  +  -  :        623 :     FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
                   +  - ]
    4976         [ +  + ]:       1246 :     CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
    4977         [ +  + ]:        623 :     if (file.IsNull()) {
    4978         [ +  - ]:        375 :         LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
    4979                 :            :         return false;
    4980                 :            :     }
    4981                 :            : 
    4982                 :        248 :     int64_t count = 0;
    4983                 :        248 :     int64_t expired = 0;
    4984                 :        248 :     int64_t failed = 0;
    4985                 :        248 :     int64_t already_there = 0;
    4986                 :        248 :     int64_t unbroadcast = 0;
    4987         [ +  - ]:        248 :     int64_t nNow = GetTime();
    4988                 :            : 
    4989                 :        248 :     try {
    4990                 :        248 :         uint64_t version;
    4991         [ +  - ]:        248 :         file >> version;
    4992         [ +  - ]:        248 :         if (version != MEMPOOL_DUMP_VERSION) {
    4993                 :            :             return false;
    4994                 :            :         }
    4995                 :        248 :         uint64_t num;
    4996         [ +  - ]:        248 :         file >> num;
    4997                 :        368 :         while (num--) {
    4998         [ +  + ]:        368 :             CTransactionRef tx;
    4999                 :        120 :             int64_t nTime;
    5000                 :        120 :             int64_t nFeeDelta;
    5001         [ +  - ]:        120 :             file >> tx;
    5002         [ +  - ]:        120 :             file >> nTime;
    5003         [ +  - ]:        120 :             file >> nFeeDelta;
    5004                 :            : 
    5005                 :        120 :             CAmount amountdelta = nFeeDelta;
    5006         [ +  + ]:        120 :             if (amountdelta) {
    5007         [ +  - ]:          4 :                 pool.PrioritiseTransaction(tx->GetHash(), amountdelta);
    5008                 :            :             }
    5009   [ +  -  +  - ]:        240 :             TxValidationState state;
    5010         [ +  - ]:        120 :             if (nTime > nNow - nExpiryTimeout) {
    5011         [ +  - ]:        120 :                 LOCK(cs_main);
    5012         [ +  - ]:        120 :                 AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, nTime,
    5013                 :            :                                            nullptr /* plTxnReplaced */, false /* bypass_limits */,
    5014                 :            :                                            false /* test_accept */);
    5015         [ +  + ]:        120 :                 if (state.IsValid()) {
    5016                 :         39 :                     ++count;
    5017                 :            :                 } else {
    5018                 :            :                     // mempool may contain the transaction already, e.g. from
    5019                 :            :                     // wallet(s) having loaded it while we were processing
    5020                 :            :                     // mempool transactions; consider these as valid, instead of
    5021                 :            :                     // failed, but mark them as 'already there'
    5022   [ +  -  +  + ]:         81 :                     if (pool.exists(tx->GetHash())) {
    5023                 :         69 :                         ++already_there;
    5024                 :            :                     } else {
    5025                 :         12 :                         ++failed;
    5026                 :            :                     }
    5027                 :            :                 }
    5028                 :            :             } else {
    5029                 :          0 :                 ++expired;
    5030                 :            :             }
    5031   [ +  -  -  + ]:        120 :             if (ShutdownRequested())
    5032         [ #  # ]:          0 :                 return false;
    5033                 :            :         }
    5034         [ +  - ]:        248 :         std::map<uint256, CAmount> mapDeltas;
    5035         [ +  - ]:        248 :         file >> mapDeltas;
    5036                 :            : 
    5037         [ -  + ]:        248 :         for (const auto& i : mapDeltas) {
    5038         [ #  # ]:          0 :             pool.PrioritiseTransaction(i.first, i.second);
    5039                 :            :         }
    5040                 :            : 
    5041                 :            :         // TODO: remove this try except in v0.22
    5042         [ +  - ]:        496 :         std::set<uint256> unbroadcast_txids;
    5043                 :        248 :         try {
    5044         [ +  - ]:        248 :           file >> unbroadcast_txids;
    5045                 :        248 :           unbroadcast = unbroadcast_txids.size();
    5046         [ -  - ]:          0 :         } catch (const std::exception&) {
    5047                 :            :           // mempool.dat files created prior to v0.21 will not have an
    5048                 :            :           // unbroadcast set. No need to log a failure if parsing fails here.
    5049                 :            :         }
    5050         [ +  + ]:        305 :         for (const auto& txid : unbroadcast_txids) {
    5051                 :            :             // Ensure transactions were accepted to mempool then add to
    5052                 :            :             // unbroadcast set.
    5053   [ +