LCOV - code coverage report
Current view: top level - src - miner.cpp (source / functions) Hit Total Coverage
Test: coverage.lcov Lines: 258 266 97.0 %
Date: 2021-06-29 14:35:33 Functions: 17 17 100.0 %
Legend: Modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed

Not modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed
Branches: 79 90 87.8 %

           Branch data     Line data    Source code
#       1                 :            : // Copyright (c) 2009-2010 Satoshi Nakamoto
#       2                 :            : // Copyright (c) 2009-2020 The Bitcoin Core developers
#       3                 :            : // Distributed under the MIT software license, see the accompanying
#       4                 :            : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
#       5                 :            : 
#       6                 :            : #include <miner.h>
#       7                 :            : 
#       8                 :            : #include <amount.h>
#       9                 :            : #include <chain.h>
#      10                 :            : #include <chainparams.h>
#      11                 :            : #include <coins.h>
#      12                 :            : #include <consensus/consensus.h>
#      13                 :            : #include <consensus/merkle.h>
#      14                 :            : #include <consensus/tx_verify.h>
#      15                 :            : #include <consensus/validation.h>
#      16                 :            : #include <policy/feerate.h>
#      17                 :            : #include <policy/policy.h>
#      18                 :            : #include <pow.h>
#      19                 :            : #include <primitives/transaction.h>
#      20                 :            : #include <timedata.h>
#      21                 :            : #include <util/moneystr.h>
#      22                 :            : #include <util/system.h>
#      23                 :            : 
#      24                 :            : #include <algorithm>
#      25                 :            : #include <utility>
#      26                 :            : 
#      27                 :            : int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
#      28                 :      30013 : {
#      29                 :      30013 :     int64_t nOldTime = pblock->nTime;
#      30                 :      30013 :     int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
#      31                 :            : 
#      32         [ +  + ]:      30013 :     if (nOldTime < nNewTime)
#      33                 :      23876 :         pblock->nTime = nNewTime;
#      34                 :            : 
#      35                 :            :     // Updating time can change work required on testnet:
#      36         [ +  + ]:      30013 :     if (consensusParams.fPowAllowMinDifficultyBlocks)
#      37                 :      29974 :         pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
#      38                 :            : 
#      39                 :      30013 :     return nNewTime - nOldTime;
#      40                 :      30013 : }
#      41                 :            : 
#      42                 :            : void RegenerateCommitments(CBlock& block, CBlockIndex* prev_block)
#      43                 :       4004 : {
#      44                 :       4004 :     CMutableTransaction tx{*block.vtx.at(0)};
#      45                 :       4004 :     tx.vout.erase(tx.vout.begin() + GetWitnessCommitmentIndex(block));
#      46                 :       4004 :     block.vtx.at(0) = MakeTransactionRef(tx);
#      47                 :            : 
#      48                 :       4004 :     WITH_LOCK(::cs_main, assert(g_chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock) == prev_block));
#      49                 :       4004 :     GenerateCoinbaseCommitment(block, prev_block, Params().GetConsensus());
#      50                 :            : 
#      51                 :       4004 :     block.hashMerkleRoot = BlockMerkleRoot(block);
#      52                 :       4004 : }
#      53                 :            : 
#      54                 :      29962 : BlockAssembler::Options::Options() {
#      55                 :      29962 :     blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
#      56                 :      29962 :     nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT;
#      57                 :      29962 : }
#      58                 :            : 
#      59                 :            : BlockAssembler::BlockAssembler(CChainState& chainstate, const CTxMemPool& mempool, const CChainParams& params, const Options& options)
#      60                 :            :     : chainparams(params),
#      61                 :            :       m_mempool(mempool),
#      62                 :            :       m_chainstate(chainstate)
#      63                 :      29962 : {
#      64                 :      29962 :     blockMinFeeRate = options.blockMinFeeRate;
#      65                 :            :     // Limit weight to between 4K and MAX_BLOCK_WEIGHT-4K for sanity:
#      66                 :      29962 :     nBlockMaxWeight = std::max<size_t>(4000, std::min<size_t>(MAX_BLOCK_WEIGHT - 4000, options.nBlockMaxWeight));
#      67                 :      29962 : }
#      68                 :            : 
#      69                 :            : static BlockAssembler::Options DefaultOptions()
#      70                 :      29924 : {
#      71                 :            :     // Block resource limits
#      72                 :            :     // If -blockmaxweight is not given, limit to DEFAULT_BLOCK_MAX_WEIGHT
#      73                 :      29924 :     BlockAssembler::Options options;
#      74                 :      29924 :     options.nBlockMaxWeight = gArgs.GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
#      75                 :      29924 :     CAmount n = 0;
#      76 [ -  + ][ -  + ]:      29924 :     if (gArgs.IsArgSet("-blockmintxfee") && ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n)) {
#                 [ #  # ]
#      77                 :          0 :         options.blockMinFeeRate = CFeeRate(n);
#      78                 :      29924 :     } else {
#      79                 :      29924 :         options.blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
#      80                 :      29924 :     }
#      81                 :      29924 :     return options;
#      82                 :      29924 : }
#      83                 :            : 
#      84                 :            : BlockAssembler::BlockAssembler(CChainState& chainstate, const CTxMemPool& mempool, const CChainParams& params)
#      85                 :      29924 :     : BlockAssembler(chainstate, mempool, params, DefaultOptions()) {}
#      86                 :            : 
#      87                 :            : void BlockAssembler::resetBlock()
#      88                 :      29962 : {
#      89                 :      29962 :     inBlock.clear();
#      90                 :            : 
#      91                 :            :     // Reserve space for coinbase tx
#      92                 :      29962 :     nBlockWeight = 4000;
#      93                 :      29962 :     nBlockSigOpsCost = 400;
#      94                 :      29962 :     fIncludeWitness = false;
#      95                 :            : 
#      96                 :            :     // These counters do not include coinbase tx
#      97                 :      29962 :     nBlockTx = 0;
#      98                 :      29962 :     nFees = 0;
#      99                 :      29962 : }
#     100                 :            : 
#     101                 :            : std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn)
#     102                 :      29962 : {
#     103                 :      29962 :     int64_t nTimeStart = GetTimeMicros();
#     104                 :            : 
#     105                 :      29962 :     resetBlock();
#     106                 :            : 
#     107                 :      29962 :     pblocktemplate.reset(new CBlockTemplate());
#     108                 :            : 
#     109         [ -  + ]:      29962 :     if(!pblocktemplate.get())
#     110                 :          0 :         return nullptr;
#     111                 :      29962 :     CBlock* const pblock = &pblocktemplate->block; // pointer for convenience
#     112                 :            : 
#     113                 :            :     // Add dummy coinbase tx as first transaction
#     114                 :      29962 :     pblock->vtx.emplace_back();
#     115                 :      29962 :     pblocktemplate->vTxFees.push_back(-1); // updated at end
#     116                 :      29962 :     pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end
#     117                 :            : 
#     118                 :      29962 :     LOCK2(cs_main, m_mempool.cs);
#     119                 :      29962 :     assert(std::addressof(*::ChainActive().Tip()) == std::addressof(*m_chainstate.m_chain.Tip()));
#     120                 :      29962 :     CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip();
#     121                 :      29962 :     assert(pindexPrev != nullptr);
#     122                 :      29962 :     nHeight = pindexPrev->nHeight + 1;
#     123                 :            : 
#     124                 :      29962 :     pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
#     125                 :            :     // -regtest only: allow overriding block.nVersion with
#     126                 :            :     // -blockversion=N to test forking scenarios
#     127         [ +  + ]:      29962 :     if (chainparams.MineBlocksOnDemand())
#     128                 :      29923 :         pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion);
#     129                 :            : 
#     130                 :      29962 :     pblock->nTime = GetAdjustedTime();
#     131                 :      29962 :     const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
#     132                 :            : 
#     133                 :      29962 :     nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
#     134                 :      29962 :                        ? nMedianTimePast
#     135                 :      29962 :                        : pblock->GetBlockTime();
#     136                 :            : 
#     137                 :            :     // Decide whether to include witness transactions
#     138                 :            :     // This is only needed in case the witness softfork activation is reverted
#     139                 :            :     // (which would require a very deep reorganization).
#     140                 :            :     // Note that the mempool would accept transactions with witness data before
#     141                 :            :     // IsWitnessEnabled, but we would only ever mine blocks after IsWitnessEnabled
#     142                 :            :     // unless there is a massive block reorganization with the witness softfork
#     143                 :            :     // not activated.
#     144                 :            :     // TODO: replace this with a call to main to assess validity of a mempool
#     145                 :            :     // transaction (which in most cases can be a no-op).
#     146                 :      29962 :     fIncludeWitness = IsWitnessEnabled(pindexPrev, chainparams.GetConsensus());
#     147                 :            : 
#     148                 :      29962 :     int nPackagesSelected = 0;
#     149                 :      29962 :     int nDescendantsUpdated = 0;
#     150                 :      29962 :     addPackageTxs(nPackagesSelected, nDescendantsUpdated);
#     151                 :            : 
#     152                 :      29962 :     int64_t nTime1 = GetTimeMicros();
#     153                 :            : 
#     154                 :      29962 :     m_last_block_num_txs = nBlockTx;
#     155                 :      29962 :     m_last_block_weight = nBlockWeight;
#     156                 :            : 
#     157                 :            :     // Create coinbase transaction.
#     158                 :      29962 :     CMutableTransaction coinbaseTx;
#     159                 :      29962 :     coinbaseTx.vin.resize(1);
#     160                 :      29962 :     coinbaseTx.vin[0].prevout.SetNull();
#     161                 :      29962 :     coinbaseTx.vout.resize(1);
#     162                 :      29962 :     coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
#     163                 :      29962 :     coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
#     164                 :      29962 :     coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
#     165                 :      29962 :     pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
#     166                 :      29962 :     pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus());
#     167                 :      29962 :     pblocktemplate->vTxFees[0] = -nFees;
#     168                 :            : 
#     169                 :      29962 :     LogPrintf("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
#     170                 :            : 
#     171                 :            :     // Fill in header
#     172                 :      29962 :     pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
#     173                 :      29962 :     UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
#     174                 :      29962 :     pblock->nBits          = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
#     175                 :      29962 :     pblock->nNonce         = 0;
#     176                 :      29962 :     pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]);
#     177                 :            : 
#     178                 :      29962 :     BlockValidationState state;
#     179                 :      29962 :     assert(std::addressof(::ChainstateActive()) == std::addressof(m_chainstate));
#     180         [ +  + ]:      29962 :     if (!TestBlockValidity(state, chainparams, m_chainstate, *pblock, pindexPrev, false, false)) {
#     181                 :         10 :         throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, state.ToString()));
#     182                 :         10 :     }
#     183                 :      29952 :     int64_t nTime2 = GetTimeMicros();
#     184                 :            : 
#     185         [ +  - ]:      29952 :     LogPrint(BCLog::BENCH, "CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n", 0.001 * (nTime1 - nTimeStart), nPackagesSelected, nDescendantsUpdated, 0.001 * (nTime2 - nTime1), 0.001 * (nTime2 - nTimeStart));
#     186                 :            : 
#     187                 :      29952 :     return std::move(pblocktemplate);
#     188                 :      29952 : }
#     189                 :            : 
#     190                 :            : void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet)
#     191                 :       8842 : {
#     192         [ +  + ]:      33129 :     for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
#     193                 :            :         // Only test txs not already in the block
#     194         [ +  + ]:      24287 :         if (inBlock.count(*iit)) {
#     195                 :      19637 :             testSet.erase(iit++);
#     196                 :      19637 :         }
#     197                 :       4650 :         else {
#     198                 :       4650 :             iit++;
#     199                 :       4650 :         }
#     200                 :      24287 :     }
#     201                 :       8842 : }
#     202                 :            : 
#     203                 :            : bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
#     204                 :      20172 : {
#     205                 :            :     // TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
#     206         [ +  + ]:      20172 :     if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= nBlockMaxWeight)
#     207                 :      11304 :         return false;
#     208         [ +  + ]:       8868 :     if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST)
#     209                 :         26 :         return false;
#     210                 :       8842 :     return true;
#     211                 :       8842 : }
#     212                 :            : 
#     213                 :            : // Perform transaction-level checks before adding to block:
#     214                 :            : // - transaction finality (locktime)
#     215                 :            : // - premature witness (in case segwit transactions are added to mempool before
#     216                 :            : //   segwit activation)
#     217                 :            : bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package) const
#     218                 :       8842 : {
#     219         [ +  + ]:      13492 :     for (CTxMemPool::txiter it : package) {
#     220         [ +  + ]:      13492 :         if (!IsFinalTx(it->GetTx(), nHeight, nLockTimeCutoff))
#     221                 :          4 :             return false;
#     222 [ +  + ][ +  + ]:      13488 :         if (!fIncludeWitness && it->GetTx().HasWitness())
#     223                 :         26 :             return false;
#     224                 :      13488 :     }
#     225                 :       8842 :     return true;
#     226                 :       8842 : }
#     227                 :            : 
#     228                 :            : void BlockAssembler::AddToBlock(CTxMemPool::txiter iter)
#     229                 :      13462 : {
#     230                 :      13462 :     pblocktemplate->block.vtx.emplace_back(iter->GetSharedTx());
#     231                 :      13462 :     pblocktemplate->vTxFees.push_back(iter->GetFee());
#     232                 :      13462 :     pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
#     233                 :      13462 :     nBlockWeight += iter->GetTxWeight();
#     234                 :      13462 :     ++nBlockTx;
#     235                 :      13462 :     nBlockSigOpsCost += iter->GetSigOpCost();
#     236                 :      13462 :     nFees += iter->GetFee();
#     237                 :      13462 :     inBlock.insert(iter);
#     238                 :            : 
#     239                 :      13462 :     bool fPrintPriority = gArgs.GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
#     240         [ +  + ]:      13462 :     if (fPrintPriority) {
#     241                 :        129 :         LogPrintf("fee %s txid %s\n",
#     242                 :        129 :                   CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
#     243                 :        129 :                   iter->GetTx().GetHash().ToString());
#     244                 :        129 :     }
#     245                 :      13462 : }
#     246                 :            : 
#     247                 :            : int BlockAssembler::UpdatePackagesForAdded(const CTxMemPool::setEntries& alreadyAdded,
#     248                 :            :         indexed_modified_transaction_set &mapModifiedTx)
#     249                 :      38774 : {
#     250                 :      38774 :     int nDescendantsUpdated = 0;
#     251         [ +  + ]:      38774 :     for (CTxMemPool::txiter it : alreadyAdded) {
#     252                 :      13462 :         CTxMemPool::setEntries descendants;
#     253                 :      13462 :         m_mempool.CalculateDescendants(it, descendants);
#     254                 :            :         // Insert all descendants (not yet in block) into the modified set
#     255         [ +  + ]:    2035981 :         for (CTxMemPool::txiter desc : descendants) {
#     256         [ +  + ]:    2035981 :             if (alreadyAdded.count(desc))
#     257                 :     472061 :                 continue;
#     258                 :    1563920 :             ++nDescendantsUpdated;
#     259                 :    1563920 :             modtxiter mit = mapModifiedTx.find(desc);
#     260         [ +  + ]:    1563920 :             if (mit == mapModifiedTx.end()) {
#     261                 :       4786 :                 CTxMemPoolModifiedEntry modEntry(desc);
#     262                 :       4786 :                 modEntry.nSizeWithAncestors -= it->GetTxSize();
#     263                 :       4786 :                 modEntry.nModFeesWithAncestors -= it->GetModifiedFee();
#     264                 :       4786 :                 modEntry.nSigOpCostWithAncestors -= it->GetSigOpCost();
#     265                 :       4786 :                 mapModifiedTx.insert(modEntry);
#     266                 :    1559134 :             } else {
#     267                 :    1559134 :                 mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
#     268                 :    1559134 :             }
#     269                 :    1563920 :         }
#     270                 :      13462 :     }
#     271                 :      38774 :     return nDescendantsUpdated;
#     272                 :      38774 : }
#     273                 :            : 
#     274                 :            : // Skip entries in mapTx that are already in a block or are present
#     275                 :            : // in mapModifiedTx (which implies that the mapTx ancestor state is
#     276                 :            : // stale due to ancestor inclusion in the block)
#     277                 :            : // Also skip transactions that we've already failed to add. This can happen if
#     278                 :            : // we consider a transaction in mapModifiedTx and it fails: we can then
#     279                 :            : // potentially consider it again while walking mapTx.  It's currently
#     280                 :            : // guaranteed to fail again, but as a belt-and-suspenders check we put it in
#     281                 :            : // failedTx and avoid re-evaluation, since the re-evaluation would be using
#     282                 :            : // cached size/sigops/fee values that are not actually correct.
#     283                 :            : bool BlockAssembler::SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx)
#     284                 :      24978 : {
#     285                 :      24978 :     assert(it != m_mempool.mapTx.end());
#     286 [ +  + ][ +  + ]:      24978 :     return mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it);
#                 [ -  + ]
#     287                 :      24978 : }
#     288                 :            : 
#     289                 :            : void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, std::vector<CTxMemPool::txiter>& sortedEntries)
#     290                 :       8812 : {
#     291                 :            :     // Sort package by ancestor count
#     292                 :            :     // If a transaction A depends on transaction B, then A's ancestor count
#     293                 :            :     // must be greater than B's.  So this is sufficient to validly order the
#     294                 :            :     // transactions for block inclusion.
#     295                 :       8812 :     sortedEntries.clear();
#     296                 :       8812 :     sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
#     297                 :       8812 :     std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
#     298                 :       8812 : }
#     299                 :            : 
#     300                 :            : // This transaction selection algorithm orders the mempool based
#     301                 :            : // on feerate of a transaction including all unconfirmed ancestors.
#     302                 :            : // Since we don't remove transactions from the mempool as we select them
#     303                 :            : // for block inclusion, we need an alternate method of updating the feerate
#     304                 :            : // of a transaction with its not-yet-selected ancestors as we go.
#     305                 :            : // This is accomplished by walking the in-mempool descendants of selected
#     306                 :            : // transactions and storing a temporary modified state in mapModifiedTxs.
#     307                 :            : // Each time through the loop, we compare the best transaction in
#     308                 :            : // mapModifiedTxs with the next transaction in the mempool to decide what
#     309                 :            : // transaction package to work on next.
#     310                 :            : void BlockAssembler::addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated)
#     311                 :      29962 : {
#     312                 :            :     // mapModifiedTx will store sorted packages after they are modified
#     313                 :            :     // because some of their txs are already in the block
#     314                 :      29962 :     indexed_modified_transaction_set mapModifiedTx;
#     315                 :            :     // Keep track of entries that failed inclusion, to avoid duplicate work
#     316                 :      29962 :     CTxMemPool::setEntries failedTx;
#     317                 :            : 
#     318                 :            :     // Start by adding all descendants of previously added txs to mapModifiedTx
#     319                 :            :     // and modifying them for their already included ancestors
#     320                 :      29962 :     UpdatePackagesForAdded(inBlock, mapModifiedTx);
#     321                 :            : 
#     322                 :      29962 :     CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = m_mempool.mapTx.get<ancestor_score>().begin();
#     323                 :      29962 :     CTxMemPool::txiter iter;
#     324                 :            : 
#     325                 :            :     // Limit the number of attempts to add transactions to the block when it is
#     326                 :            :     // close to full; this is just a simple heuristic to finish quickly if the
#     327                 :            :     // mempool has a lot of entries.
#     328                 :      29962 :     const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
#     329                 :      29962 :     int64_t nConsecutiveFailed = 0;
#     330                 :            : 
#     331 [ +  + ][ +  + ]:      55438 :     while (mi != m_mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty()) {
#                 [ +  + ]
#     332                 :            :         // First try to find a new transaction in mapTx to evaluate.
#     333 [ +  + ][ +  + ]:      25491 :         if (mi != m_mempool.mapTx.get<ancestor_score>().end() &&
#     334         [ +  + ]:      25491 :             SkipMapTxEntry(m_mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) {
#     335                 :       5304 :             ++mi;
#     336                 :       5304 :             continue;
#     337                 :       5304 :         }
#     338                 :            : 
#     339                 :            :         // Now that mi is not stale, determine which transaction to evaluate:
#     340                 :            :         // the next entry from mapTx, or the best from mapModifiedTx?
#     341                 :      20187 :         bool fUsingModified = false;
#     342                 :            : 
#     343                 :      20187 :         modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
#     344         [ +  + ]:      20187 :         if (mi == m_mempool.mapTx.get<ancestor_score>().end()) {
#     345                 :            :             // We're out of entries in mapTx; use the entry from mapModifiedTx
#     346                 :        513 :             iter = modit->iter;
#     347                 :        513 :             fUsingModified = true;
#     348                 :      19674 :         } else {
#     349                 :            :             // Try to compare the mapTx entry to the mapModifiedTx entry
#     350                 :      19674 :             iter = m_mempool.mapTx.project<0>(mi);
#     351 [ +  + ][ +  + ]:      19674 :             if (modit != mapModifiedTx.get<ancestor_score>().end() &&
#     352         [ +  + ]:      19674 :                     CompareTxMemPoolEntryByAncestorFee()(*modit, CTxMemPoolModifiedEntry(iter))) {
#     353                 :            :                 // The best entry in mapModifiedTx has higher score
#     354                 :            :                 // than the one from mapTx.
#     355                 :            :                 // Switch which transaction (package) to consider
#     356                 :        153 :                 iter = modit->iter;
#     357                 :        153 :                 fUsingModified = true;
#     358                 :      19521 :             } else {
#     359                 :            :                 // Either no entry in mapModifiedTx, or it's worse than mapTx.
#     360                 :            :                 // Increment mi for the next loop iteration.
#     361                 :      19521 :                 ++mi;
#     362                 :      19521 :             }
#     363                 :      19674 :         }
#     364                 :            : 
#     365                 :            :         // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
#     366                 :            :         // contain anything that is inBlock.
#     367                 :      20187 :         assert(!inBlock.count(iter));
#     368                 :            : 
#     369                 :      20187 :         uint64_t packageSize = iter->GetSizeWithAncestors();
#     370                 :      20187 :         CAmount packageFees = iter->GetModFeesWithAncestors();
#     371                 :      20187 :         int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
#     372         [ +  + ]:      20187 :         if (fUsingModified) {
#     373                 :        666 :             packageSize = modit->nSizeWithAncestors;
#     374                 :        666 :             packageFees = modit->nModFeesWithAncestors;
#     375                 :        666 :             packageSigOpsCost = modit->nSigOpCostWithAncestors;
#     376                 :        666 :         }
#     377                 :            : 
#     378         [ +  + ]:      20187 :         if (packageFees < blockMinFeeRate.GetFee(packageSize)) {
#     379                 :            :             // Everything else we might consider has a lower fee rate
#     380                 :         15 :             return;
#     381                 :         15 :         }
#     382                 :            : 
#     383         [ +  + ]:      20172 :         if (!TestPackage(packageSize, packageSigOpsCost)) {
#     384         [ +  + ]:      11330 :             if (fUsingModified) {
#     385                 :            :                 // Since we always look at the best entry in mapModifiedTx,
#     386                 :            :                 // we must erase failed entries so that we can consider the
#     387                 :            :                 // next best entry on the next loop iteration
#     388                 :         72 :                 mapModifiedTx.get<ancestor_score>().erase(modit);
#     389                 :         72 :                 failedTx.insert(iter);
#     390                 :         72 :             }
#     391                 :            : 
#     392                 :      11330 :             ++nConsecutiveFailed;
#     393                 :            : 
#     394 [ -  + ][ #  # ]:      11330 :             if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight >
#     395                 :          0 :                     nBlockMaxWeight - 4000) {
#     396                 :            :                 // Give up if we're close to full and haven't succeeded in a while
#     397                 :          0 :                 break;
#     398                 :          0 :             }
#     399                 :      11330 :             continue;
#     400                 :      11330 :         }
#     401                 :            : 
#     402                 :       8842 :         CTxMemPool::setEntries ancestors;
#     403                 :       8842 :         uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
#     404                 :       8842 :         std::string dummy;
#     405                 :       8842 :         m_mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
#     406                 :            : 
#     407                 :       8842 :         onlyUnconfirmed(ancestors);
#     408                 :       8842 :         ancestors.insert(iter);
#     409                 :            : 
#     410                 :            :         // Test if all tx's are Final
#     411         [ +  + ]:       8842 :         if (!TestPackageTransactions(ancestors)) {
#     412         [ -  + ]:         30 :             if (fUsingModified) {
#     413                 :          0 :                 mapModifiedTx.get<ancestor_score>().erase(modit);
#     414                 :          0 :                 failedTx.insert(iter);
#     415                 :          0 :             }
#     416                 :         30 :             continue;
#     417                 :         30 :         }
#     418                 :            : 
#     419                 :            :         // This transaction will make it in; reset the failed counter.
#     420                 :       8812 :         nConsecutiveFailed = 0;
#     421                 :            : 
#     422                 :            :         // Package can be added. Sort the entries in a valid order.
#     423                 :       8812 :         std::vector<CTxMemPool::txiter> sortedEntries;
#     424                 :       8812 :         SortForBlock(ancestors, sortedEntries);
#     425                 :            : 
#     426         [ +  + ]:      22274 :         for (size_t i=0; i<sortedEntries.size(); ++i) {
#     427                 :      13462 :             AddToBlock(sortedEntries[i]);
#     428                 :            :             // Erase from the modified set, if present
#     429                 :      13462 :             mapModifiedTx.erase(sortedEntries[i]);
#     430                 :      13462 :         }
#     431                 :            : 
#     432                 :       8812 :         ++nPackagesSelected;
#     433                 :            : 
#     434                 :            :         // Update transactions that depend on each of these
#     435                 :       8812 :         nDescendantsUpdated += UpdatePackagesForAdded(ancestors, mapModifiedTx);
#     436                 :       8812 :     }
#     437                 :      29962 : }
#     438                 :            : 
#     439                 :            : void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
#     440                 :      25063 : {
#     441                 :            :     // Update nExtraNonce
#     442                 :      25063 :     static uint256 hashPrevBlock;
#     443         [ +  + ]:      25063 :     if (hashPrevBlock != pblock->hashPrevBlock)
#     444                 :      25061 :     {
#     445                 :      25061 :         nExtraNonce = 0;
#     446                 :      25061 :         hashPrevBlock = pblock->hashPrevBlock;
#     447                 :      25061 :     }
#     448                 :      25063 :     ++nExtraNonce;
#     449                 :      25063 :     unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
#     450                 :      25063 :     CMutableTransaction txCoinbase(*pblock->vtx[0]);
#     451                 :      25063 :     txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce));
#     452                 :      25063 :     assert(txCoinbase.vin[0].scriptSig.size() <= 100);
#     453                 :            : 
#     454                 :      25063 :     pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
#     455                 :      25063 :     pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
#     456                 :      25063 : }

Generated by: LCOV version 1.14