LCOV - code coverage report
Current view: top level - src - validation.cpp (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 1916 2206 86.9 %
Date: 2000-01-01 12:00:00 Functions: 134 139 96.4 %
Branches: 1837 3282 56.0 %

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

Generated by: LCOV version 1.13