LCOV - code coverage report
Current view: top level - src/node - miner.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 96.8 % 278 269
Test Date: 2025-06-01 05:54:06 Functions: 100.0 % 23 23
Branches: 59.8 % 366 219

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2                 :             : // Copyright (c) 2009-2022 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 <node/miner.h>
       7                 :             : 
       8                 :             : #include <chain.h>
       9                 :             : #include <chainparams.h>
      10                 :             : #include <coins.h>
      11                 :             : #include <common/args.h>
      12                 :             : #include <consensus/amount.h>
      13                 :             : #include <consensus/consensus.h>
      14                 :             : #include <consensus/merkle.h>
      15                 :             : #include <consensus/tx_verify.h>
      16                 :             : #include <consensus/validation.h>
      17                 :             : #include <deploymentstatus.h>
      18                 :             : #include <logging.h>
      19                 :             : #include <node/context.h>
      20                 :             : #include <node/kernel_notifications.h>
      21                 :             : #include <policy/feerate.h>
      22                 :             : #include <policy/policy.h>
      23                 :             : #include <pow.h>
      24                 :             : #include <primitives/transaction.h>
      25                 :             : #include <util/moneystr.h>
      26                 :             : #include <util/signalinterrupt.h>
      27                 :             : #include <util/time.h>
      28                 :             : #include <validation.h>
      29                 :             : 
      30                 :             : #include <algorithm>
      31                 :             : #include <utility>
      32                 :             : 
      33                 :             : namespace node {
      34                 :             : 
      35                 :        7173 : int64_t GetMinimumTime(const CBlockIndex* pindexPrev, const int64_t difficulty_adjustment_interval)
      36                 :             : {
      37                 :        7173 :     int64_t min_time{pindexPrev->GetMedianTimePast() + 1};
      38                 :             :     // Height of block to be mined.
      39                 :        7173 :     const int height{pindexPrev->nHeight + 1};
      40                 :             :     // Account for BIP94 timewarp rule on all networks. This makes future
      41                 :             :     // activation safer.
      42         [ +  + ]:        7173 :     if (height % difficulty_adjustment_interval == 0) {
      43         [ +  - ]:          12 :         min_time = std::max<int64_t>(min_time, pindexPrev->GetBlockTime() - MAX_TIMEWARP);
      44                 :             :     }
      45                 :        7173 :     return min_time;
      46                 :             : }
      47                 :             : 
      48                 :        7173 : int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
      49                 :             : {
      50                 :        7173 :     int64_t nOldTime = pblock->nTime;
      51         [ +  + ]:        7173 :     int64_t nNewTime{std::max<int64_t>(GetMinimumTime(pindexPrev, consensusParams.DifficultyAdjustmentInterval()),
      52                 :        7173 :                                        TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()))};
      53                 :             : 
      54         [ +  + ]:        7173 :     if (nOldTime < nNewTime) {
      55                 :          20 :         pblock->nTime = nNewTime;
      56                 :             :     }
      57                 :             : 
      58                 :             :     // Updating time can change work required on testnet:
      59         [ +  + ]:        7173 :     if (consensusParams.fPowAllowMinDifficultyBlocks) {
      60                 :        7043 :         pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
      61                 :             :     }
      62                 :             : 
      63                 :        7173 :     return nNewTime - nOldTime;
      64                 :             : }
      65                 :             : 
      66                 :        6207 : void RegenerateCommitments(CBlock& block, ChainstateManager& chainman)
      67                 :             : {
      68                 :        6207 :     CMutableTransaction tx{*block.vtx.at(0)};
      69                 :        6207 :     tx.vout.erase(tx.vout.begin() + GetWitnessCommitmentIndex(block));
      70   [ +  -  +  -  :       12414 :     block.vtx.at(0) = MakeTransactionRef(tx);
                   -  + ]
      71                 :             : 
      72   [ +  -  +  -  :       18621 :     const CBlockIndex* prev_block = WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock));
                   +  - ]
      73         [ +  - ]:        6207 :     chainman.GenerateCoinbaseCommitment(block, prev_block);
      74                 :             : 
      75         [ +  - ]:        6207 :     block.hashMerkleRoot = BlockMerkleRoot(block);
      76                 :        6207 : }
      77                 :             : 
      78                 :        7173 : static BlockAssembler::Options ClampOptions(BlockAssembler::Options options)
      79                 :             : {
      80                 :        7173 :     Assert(options.block_reserved_weight <= MAX_BLOCK_WEIGHT);
      81                 :        7173 :     Assert(options.block_reserved_weight >= MINIMUM_BLOCK_RESERVED_WEIGHT);
      82                 :        7173 :     Assert(options.coinbase_output_max_additional_sigops <= MAX_BLOCK_SIGOPS_COST);
      83                 :             :     // Limit weight to between block_reserved_weight and MAX_BLOCK_WEIGHT for sanity:
      84                 :             :     // block_reserved_weight can safely exceed -blockmaxweight, but the rest of the block template will be empty.
      85         [ +  - ]:        7173 :     options.nBlockMaxWeight = std::clamp<size_t>(options.nBlockMaxWeight, options.block_reserved_weight, MAX_BLOCK_WEIGHT);
      86                 :        7173 :     return options;
      87                 :             : }
      88                 :             : 
      89                 :        7173 : BlockAssembler::BlockAssembler(Chainstate& chainstate, const CTxMemPool* mempool, const Options& options)
      90                 :        7173 :     : chainparams{chainstate.m_chainman.GetParams()},
      91         [ -  + ]:        7173 :       m_mempool{options.use_mempool ? mempool : nullptr},
      92                 :        7173 :       m_chainstate{chainstate},
      93   [ +  -  -  +  :        7173 :       m_options{ClampOptions(options)}
                   +  - ]
      94                 :             : {
      95                 :        7173 : }
      96                 :             : 
      97                 :          73 : void ApplyArgsManOptions(const ArgsManager& args, BlockAssembler::Options& options)
      98                 :             : {
      99                 :             :     // Block resource limits
     100         [ +  - ]:          73 :     options.nBlockMaxWeight = args.GetIntArg("-blockmaxweight", options.nBlockMaxWeight);
     101   [ +  -  -  + ]:         146 :     if (const auto blockmintxfee{args.GetArg("-blockmintxfee")}) {
     102   [ #  #  #  # ]:           0 :         if (const auto parsed{ParseMoney(*blockmintxfee)}) options.blockMinFeeRate = CFeeRate{*parsed};
     103                 :           0 :     }
     104         [ +  - ]:          73 :     options.print_modified_fee = args.GetBoolArg("-printpriority", options.print_modified_fee);
     105         [ +  - ]:          73 :     options.block_reserved_weight = args.GetIntArg("-blockreservedweight", options.block_reserved_weight);
     106                 :          73 : }
     107                 :             : 
     108                 :        7173 : void BlockAssembler::resetBlock()
     109                 :             : {
     110                 :        7173 :     inBlock.clear();
     111                 :             : 
     112                 :             :     // Reserve space for fixed-size block header, txs count, and coinbase tx.
     113                 :        7173 :     nBlockWeight = m_options.block_reserved_weight;
     114                 :        7173 :     nBlockSigOpsCost = m_options.coinbase_output_max_additional_sigops;
     115                 :             : 
     116                 :             :     // These counters do not include coinbase tx
     117                 :        7173 :     nBlockTx = 0;
     118                 :        7173 :     nFees = 0;
     119                 :        7173 : }
     120                 :             : 
     121                 :        7173 : std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock()
     122                 :             : {
     123                 :        7173 :     const auto time_start{SteadyClock::now()};
     124                 :             : 
     125                 :        7173 :     resetBlock();
     126                 :             : 
     127         [ -  + ]:        7173 :     pblocktemplate.reset(new CBlockTemplate());
     128                 :        7173 :     CBlock* const pblock = &pblocktemplate->block; // pointer for convenience
     129                 :             : 
     130                 :             :     // Add dummy coinbase tx as first transaction. It is skipped by the
     131                 :             :     // getblocktemplate RPC and mining interface consumers must not use it.
     132                 :        7173 :     pblock->vtx.emplace_back();
     133                 :             : 
     134                 :        7173 :     LOCK(::cs_main);
     135         [ +  - ]:        7173 :     CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip();
     136         [ -  + ]:        7173 :     assert(pindexPrev != nullptr);
     137                 :        7173 :     nHeight = pindexPrev->nHeight + 1;
     138                 :             : 
     139         [ +  - ]:        7173 :     pblock->nVersion = m_chainstate.m_chainman.m_versionbitscache.ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
     140                 :             :     // -regtest only: allow overriding block.nVersion with
     141                 :             :     // -blockversion=N to test forking scenarios
     142         [ +  + ]:        7173 :     if (chainparams.MineBlocksOnDemand()) {
     143   [ +  -  +  - ]:        7039 :         pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion);
     144                 :             :     }
     145                 :             : 
     146                 :        7173 :     pblock->nTime = TicksSinceEpoch<std::chrono::seconds>(NodeClock::now());
     147                 :        7173 :     m_lock_time_cutoff = pindexPrev->GetMedianTimePast();
     148                 :             : 
     149                 :        7173 :     int nPackagesSelected = 0;
     150                 :        7173 :     int nDescendantsUpdated = 0;
     151         [ +  + ]:        7173 :     if (m_mempool) {
     152         [ +  - ]:         964 :         addPackageTxs(nPackagesSelected, nDescendantsUpdated);
     153                 :             :     }
     154                 :             : 
     155                 :        7173 :     const auto time_1{SteadyClock::now()};
     156                 :             : 
     157         [ +  + ]:        7173 :     m_last_block_num_txs = nBlockTx;
     158         [ +  + ]:        7173 :     m_last_block_weight = nBlockWeight;
     159                 :             : 
     160                 :             :     // Create coinbase transaction.
     161         [ +  - ]:        7173 :     CMutableTransaction coinbaseTx;
     162         [ +  - ]:        7173 :     coinbaseTx.vin.resize(1);
     163                 :        7173 :     coinbaseTx.vin[0].prevout.SetNull();
     164         [ +  - ]:        7173 :     coinbaseTx.vin[0].nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; // Make sure timelock is enforced.
     165         [ +  - ]:        7173 :     coinbaseTx.vout.resize(1);
     166                 :        7173 :     coinbaseTx.vout[0].scriptPubKey = m_options.coinbase_output_script;
     167   [ +  -  +  - ]:        7173 :     coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
     168   [ +  -  +  - ]:        7173 :     coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
     169         [ +  - ]:        7173 :     Assert(nHeight > 0);
     170                 :        7173 :     coinbaseTx.nLockTime = static_cast<uint32_t>(nHeight - 1);
     171   [ +  -  -  + ]:       14346 :     pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
     172         [ +  - ]:        7173 :     pblocktemplate->vchCoinbaseCommitment = m_chainstate.m_chainman.GenerateCoinbaseCommitment(*pblock, pindexPrev);
     173                 :             : 
     174         [ +  - ]:        7173 :     LogPrintf("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
     175                 :             : 
     176                 :             :     // Fill in header
     177                 :        7173 :     pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
     178         [ +  - ]:        7173 :     UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
     179         [ +  - ]:        7173 :     pblock->nBits          = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
     180                 :        7173 :     pblock->nNonce         = 0;
     181                 :             : 
     182         [ +  - ]:        7173 :     BlockValidationState state;
     183   [ +  -  +  -  :        7173 :     if (m_options.test_block_validity && !TestBlockValidity(state, chainparams, m_chainstate, *pblock, pindexPrev,
                   +  + ]
     184                 :             :                                                             /*fCheckPOW=*/false, /*fCheckMerkleRoot=*/false)) {
     185   [ +  -  +  -  :          10 :         throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, state.ToString()));
                   +  - ]
     186                 :             :     }
     187                 :        7168 :     const auto time_2{SteadyClock::now()};
     188                 :             : 
     189   [ +  -  +  -  :        7168 :     LogDebug(BCLog::BENCH, "CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n",
                   +  - ]
     190                 :             :              Ticks<MillisecondsDouble>(time_1 - time_start), nPackagesSelected, nDescendantsUpdated,
     191                 :             :              Ticks<MillisecondsDouble>(time_2 - time_1),
     192                 :             :              Ticks<MillisecondsDouble>(time_2 - time_start));
     193                 :             : 
     194                 :        7168 :     return std::move(pblocktemplate);
     195         [ +  - ]:       21514 : }
     196                 :             : 
     197                 :          58 : void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet)
     198                 :             : {
     199         [ +  + ]:       15718 :     for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
     200                 :             :         // Only test txs not already in the block
     201   [ +  -  +  -  :       46980 :         if (inBlock.count((*iit)->GetSharedTx()->GetHash())) {
             +  -  +  + ]
     202                 :       13570 :             testSet.erase(iit++);
     203                 :             :         } else {
     204                 :        2090 :             iit++;
     205                 :             :         }
     206                 :             :     }
     207                 :          58 : }
     208                 :             : 
     209                 :         112 : bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
     210                 :             : {
     211                 :             :     // TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
     212         [ +  + ]:         112 :     if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= m_options.nBlockMaxWeight) {
     213                 :             :         return false;
     214                 :             :     }
     215         [ +  + ]:          74 :     if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST) {
     216                 :          16 :         return false;
     217                 :             :     }
     218                 :             :     return true;
     219                 :             : }
     220                 :             : 
     221                 :             : // Perform transaction-level checks before adding to block:
     222                 :             : // - transaction finality (locktime)
     223                 :          58 : bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package) const
     224                 :             : {
     225         [ +  + ]:        2204 :     for (CTxMemPool::txiter it : package) {
     226         [ +  + ]:        2148 :         if (!IsFinalTx(it->GetTx(), nHeight, m_lock_time_cutoff)) {
     227                 :             :             return false;
     228                 :             :         }
     229                 :             :     }
     230                 :             :     return true;
     231                 :             : }
     232                 :             : 
     233                 :        2146 : void BlockAssembler::AddToBlock(CTxMemPool::txiter iter)
     234                 :             : {
     235   [ +  -  +  - ]:        4292 :     pblocktemplate->block.vtx.emplace_back(iter->GetSharedTx());
     236                 :        2146 :     pblocktemplate->vTxFees.push_back(iter->GetFee());
     237                 :        2146 :     pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
     238         [ +  - ]:        2146 :     nBlockWeight += iter->GetTxWeight();
     239                 :        2146 :     ++nBlockTx;
     240         [ +  - ]:        2146 :     nBlockSigOpsCost += iter->GetSigOpCost();
     241                 :        2146 :     nFees += iter->GetFee();
     242   [ +  -  +  -  :        4292 :     inBlock.insert(iter->GetSharedTx()->GetHash());
                   +  - ]
     243                 :             : 
     244         [ -  + ]:        2146 :     if (m_options.print_modified_fee) {
     245   [ #  #  #  #  :           0 :         LogPrintf("fee rate %s txid %s\n",
             #  #  #  # ]
     246                 :             :                   CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
     247                 :             :                   iter->GetTx().GetHash().ToString());
     248                 :             :     }
     249                 :        2146 : }
     250                 :             : 
     251                 :             : /** Add descendants of given transactions to mapModifiedTx with ancestor
     252                 :             :  * state updated assuming given transactions are inBlock. Returns number
     253                 :             :  * of updated descendants. */
     254                 :          56 : static int UpdatePackagesForAdded(const CTxMemPool& mempool,
     255                 :             :                                   const CTxMemPool::setEntries& alreadyAdded,
     256                 :             :                                   indexed_modified_transaction_set& mapModifiedTx) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs)
     257                 :             : {
     258                 :          56 :     AssertLockHeld(mempool.cs);
     259                 :             : 
     260                 :          56 :     int nDescendantsUpdated = 0;
     261         [ +  + ]:        2202 :     for (CTxMemPool::txiter it : alreadyAdded) {
     262         [ +  - ]:        2146 :         CTxMemPool::setEntries descendants;
     263         [ +  - ]:        2146 :         mempool.CalculateDescendants(it, descendants);
     264                 :             :         // Insert all descendants (not yet in block) into the modified set
     265         [ +  + ]:     1013179 :         for (CTxMemPool::txiter desc : descendants) {
     266         [ +  + ]:     1011033 :             if (alreadyAdded.count(desc)) {
     267                 :      449934 :                 continue;
     268                 :             :             }
     269                 :      561099 :             ++nDescendantsUpdated;
     270                 :      561099 :             modtxiter mit = mapModifiedTx.find(desc);
     271         [ +  + ]:      561099 :             if (mit == mapModifiedTx.end()) {
     272         [ +  - ]:         896 :                 CTxMemPoolModifiedEntry modEntry(desc);
     273         [ +  - ]:         896 :                 mit = mapModifiedTx.insert(modEntry).first;
     274                 :             :             }
     275         [ +  - ]:     1572132 :             mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
     276                 :             :         }
     277                 :        2146 :     }
     278                 :          56 :     return nDescendantsUpdated;
     279                 :             : }
     280                 :             : 
     281                 :          56 : void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, std::vector<CTxMemPool::txiter>& sortedEntries)
     282                 :             : {
     283                 :             :     // Sort package by ancestor count
     284                 :             :     // If a transaction A depends on transaction B, then A's ancestor count
     285                 :             :     // must be greater than B's.  So this is sufficient to validly order the
     286                 :             :     // transactions for block inclusion.
     287         [ -  + ]:          56 :     sortedEntries.clear();
     288                 :          56 :     sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
     289                 :          56 :     std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
     290                 :          56 : }
     291                 :             : 
     292                 :             : // This transaction selection algorithm orders the mempool based
     293                 :             : // on feerate of a transaction including all unconfirmed ancestors.
     294                 :             : // Since we don't remove transactions from the mempool as we select them
     295                 :             : // for block inclusion, we need an alternate method of updating the feerate
     296                 :             : // of a transaction with its not-yet-selected ancestors as we go.
     297                 :             : // This is accomplished by walking the in-mempool descendants of selected
     298                 :             : // transactions and storing a temporary modified state in mapModifiedTxs.
     299                 :             : // Each time through the loop, we compare the best transaction in
     300                 :             : // mapModifiedTxs with the next transaction in the mempool to decide what
     301                 :             : // transaction package to work on next.
     302                 :         964 : void BlockAssembler::addPackageTxs(int& nPackagesSelected, int& nDescendantsUpdated)
     303                 :             : {
     304                 :         964 :     const auto& mempool{*Assert(m_mempool)};
     305                 :         964 :     LOCK(mempool.cs);
     306                 :             : 
     307                 :             :     // mapModifiedTx will store sorted packages after they are modified
     308                 :             :     // because some of their txs are already in the block
     309         [ +  - ]:         964 :     indexed_modified_transaction_set mapModifiedTx;
     310                 :             :     // Keep track of entries that failed inclusion, to avoid duplicate work
     311                 :         964 :     std::set<Txid> failedTx;
     312                 :             : 
     313                 :         964 :     CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin();
     314                 :         964 :     CTxMemPool::txiter iter;
     315                 :             : 
     316                 :             :     // Limit the number of attempts to add transactions to the block when it is
     317                 :             :     // close to full; this is just a simple heuristic to finish quickly if the
     318                 :             :     // mempool has a lot of entries.
     319                 :         964 :     const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
     320                 :         964 :     constexpr int32_t BLOCK_FULL_ENOUGH_WEIGHT_DELTA = 4000;
     321                 :         964 :     int64_t nConsecutiveFailed = 0;
     322                 :             : 
     323   [ +  +  +  + ]:        3223 :     while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty()) {
     324                 :             :         // First try to find a new transaction in mapTx to evaluate.
     325                 :             :         //
     326                 :             :         // Skip entries in mapTx that are already in a block or are present
     327                 :             :         // in mapModifiedTx (which implies that the mapTx ancestor state is
     328                 :             :         // stale due to ancestor inclusion in the block)
     329                 :             :         // Also skip transactions that we've already failed to add. This can happen if
     330                 :             :         // we consider a transaction in mapModifiedTx and it fails: we can then
     331                 :             :         // potentially consider it again while walking mapTx.  It's currently
     332                 :             :         // guaranteed to fail again, but as a belt-and-suspenders check we put it in
     333                 :             :         // failedTx and avoid re-evaluation, since the re-evaluation would be using
     334                 :             :         // cached size/sigops/fee values that are not actually correct.
     335                 :             :         /** Return true if given transaction from mapTx has already been evaluated,
     336                 :             :          * or if the transaction's cached data in mapTx is incorrect. */
     337         [ +  + ]:        2262 :         if (mi != mempool.mapTx.get<ancestor_score>().end()) {
     338         [ -  + ]:        2184 :             auto it = mempool.mapTx.project<0>(mi);
     339         [ -  + ]:        2184 :             assert(it != mempool.mapTx.end());
     340   [ +  +  +  -  :        4884 :             if (mapModifiedTx.count(it) || inBlock.count(it->GetSharedTx()->GetHash()) || failedTx.count(it->GetSharedTx()->GetHash())) {
          +  -  +  +  +  
          -  +  -  +  +  
                   +  + ]
     341                 :        2147 :                 ++mi;
     342                 :        2147 :                 continue;
     343                 :             :             }
     344                 :             :         }
     345                 :             : 
     346                 :             :         // Now that mi is not stale, determine which transaction to evaluate:
     347                 :             :         // the next entry from mapTx, or the best from mapModifiedTx?
     348                 :         115 :         bool fUsingModified = false;
     349                 :             : 
     350                 :         115 :         modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
     351         [ +  + ]:         115 :         if (mi == mempool.mapTx.get<ancestor_score>().end()) {
     352                 :             :             // We're out of entries in mapTx; use the entry from mapModifiedTx
     353                 :          78 :             iter = modit->iter;
     354                 :          78 :             fUsingModified = true;
     355                 :             :         } else {
     356                 :             :             // Try to compare the mapTx entry to the mapModifiedTx entry
     357         [ +  + ]:          37 :             iter = mempool.mapTx.project<0>(mi);
     358   [ +  +  +  + ]:          47 :             if (modit != mapModifiedTx.get<ancestor_score>().end() &&
     359         [ +  - ]:          10 :                     CompareTxMemPoolEntryByAncestorFee()(*modit, CTxMemPoolModifiedEntry(iter))) {
     360                 :             :                 // The best entry in mapModifiedTx has higher score
     361                 :             :                 // than the one from mapTx.
     362                 :             :                 // Switch which transaction (package) to consider
     363                 :           3 :                 iter = modit->iter;
     364                 :           3 :                 fUsingModified = true;
     365                 :             :             } else {
     366                 :             :                 // Either no entry in mapModifiedTx, or it's worse than mapTx.
     367                 :             :                 // Increment mi for the next loop iteration.
     368                 :          34 :                 ++mi;
     369                 :             :             }
     370                 :             :         }
     371                 :             : 
     372                 :             :         // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
     373                 :             :         // contain anything that is inBlock.
     374   [ +  -  +  -  :         230 :         assert(!inBlock.count(iter->GetSharedTx()->GetHash()));
                   -  + ]
     375                 :             : 
     376         [ +  + ]:         115 :         uint64_t packageSize = iter->GetSizeWithAncestors();
     377         [ +  + ]:         115 :         CAmount packageFees = iter->GetModFeesWithAncestors();
     378         [ +  + ]:         115 :         int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
     379         [ +  + ]:         115 :         if (fUsingModified) {
     380                 :          81 :             packageSize = modit->nSizeWithAncestors;
     381                 :          81 :             packageFees = modit->nModFeesWithAncestors;
     382                 :          81 :             packageSigOpsCost = modit->nSigOpCostWithAncestors;
     383                 :             :         }
     384                 :             : 
     385   [ +  -  +  + ]:         115 :         if (packageFees < m_options.blockMinFeeRate.GetFee(packageSize)) {
     386                 :             :             // Everything else we might consider has a lower fee rate
     387                 :           3 :             return;
     388                 :             :         }
     389                 :             : 
     390   [ +  -  +  + ]:         112 :         if (!TestPackage(packageSize, packageSigOpsCost)) {
     391         [ +  - ]:          54 :             if (fUsingModified) {
     392                 :             :                 // Since we always look at the best entry in mapModifiedTx,
     393                 :             :                 // we must erase failed entries so that we can consider the
     394                 :             :                 // next best entry on the next loop iteration
     395                 :          54 :                 mapModifiedTx.get<ancestor_score>().erase(modit);
     396   [ +  -  +  - ]:         162 :                 failedTx.insert(iter->GetSharedTx()->GetHash());
     397                 :             :             }
     398                 :             : 
     399                 :          54 :             ++nConsecutiveFailed;
     400                 :             : 
     401         [ -  + ]:          54 :             if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight >
     402         [ #  # ]:           0 :                     m_options.nBlockMaxWeight - BLOCK_FULL_ENOUGH_WEIGHT_DELTA) {
     403                 :             :                 // Give up if we're close to full and haven't succeeded in a while
     404                 :             :                 break;
     405                 :             :             }
     406                 :          54 :             continue;
     407                 :             :         }
     408                 :             : 
     409         [ +  - ]:          58 :         auto ancestors{mempool.AssumeCalculateMemPoolAncestors(__func__, *iter, CTxMemPool::Limits::NoLimits(), /*fSearchForParents=*/false)};
     410                 :             : 
     411         [ +  - ]:          58 :         onlyUnconfirmed(ancestors);
     412         [ +  - ]:          58 :         ancestors.insert(iter);
     413                 :             : 
     414                 :             :         // Test if all tx's are Final
     415   [ +  -  +  + ]:          58 :         if (!TestPackageTransactions(ancestors)) {
     416         [ -  + ]:           2 :             if (fUsingModified) {
     417                 :           0 :                 mapModifiedTx.get<ancestor_score>().erase(modit);
     418   [ #  #  #  # ]:           0 :                 failedTx.insert(iter->GetSharedTx()->GetHash());
     419                 :             :             }
     420                 :           2 :             continue;
     421                 :             :         }
     422                 :             : 
     423                 :             :         // This transaction will make it in; reset the failed counter.
     424                 :          56 :         nConsecutiveFailed = 0;
     425                 :             : 
     426                 :             :         // Package can be added. Sort the entries in a valid order.
     427                 :          56 :         std::vector<CTxMemPool::txiter> sortedEntries;
     428         [ +  - ]:          56 :         SortForBlock(ancestors, sortedEntries);
     429                 :             : 
     430         [ +  + ]:        2202 :         for (size_t i = 0; i < sortedEntries.size(); ++i) {
     431         [ +  - ]:        2146 :             AddToBlock(sortedEntries[i]);
     432                 :             :             // Erase from the modified set, if present
     433                 :        2146 :             mapModifiedTx.erase(sortedEntries[i]);
     434                 :             :         }
     435                 :             : 
     436                 :          56 :         ++nPackagesSelected;
     437         [ +  - ]:          56 :         pblocktemplate->m_package_feerates.emplace_back(packageFees, static_cast<int32_t>(packageSize));
     438                 :             : 
     439                 :             :         // Update transactions that depend on each of these
     440         [ +  - ]:          56 :         nDescendantsUpdated += UpdatePackagesForAdded(mempool, ancestors, mapModifiedTx);
     441                 :          58 :     }
     442   [ +  -  +  - ]:        1928 : }
     443                 :             : 
     444                 :          55 : void AddMerkleRootAndCoinbase(CBlock& block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce)
     445                 :             : {
     446         [ -  + ]:          55 :     if (block.vtx.size() == 0) {
     447                 :           0 :         block.vtx.emplace_back(coinbase);
     448                 :             :     } else {
     449                 :          55 :         block.vtx[0] = coinbase;
     450                 :             :     }
     451                 :          55 :     block.nVersion = version;
     452                 :          55 :     block.nTime = timestamp;
     453                 :          55 :     block.nNonce = nonce;
     454                 :          55 :     block.hashMerkleRoot = BlockMerkleRoot(block);
     455                 :          55 : }
     456                 :             : 
     457                 :          60 : std::unique_ptr<CBlockTemplate> WaitAndCreateNewBlock(ChainstateManager& chainman,
     458                 :             :                                                       KernelNotifications& kernel_notifications,
     459                 :             :                                                       CTxMemPool* mempool,
     460                 :             :                                                       const std::unique_ptr<CBlockTemplate>& block_template,
     461                 :             :                                                       const BlockWaitOptions& options,
     462                 :             :                                                       const BlockAssembler::Options& assemble_options)
     463                 :             : {
     464                 :             :     // Delay calculating the current template fees, just in case a new block
     465                 :             :     // comes in before the next tick.
     466                 :          60 :     CAmount current_fees = -1;
     467                 :             : 
     468                 :             :     // Alternate waiting for a new tip and checking if fees have risen.
     469                 :             :     // The latter check is expensive so we only run it once per second.
     470                 :          60 :     auto now{NodeClock::now()};
     471                 :          60 :     const auto deadline = now + options.timeout;
     472                 :          60 :     const MillisecondsDouble tick{1000};
     473                 :          60 :     const bool allow_min_difficulty{chainman.GetParams().GetConsensus().fPowAllowMinDifficultyBlocks};
     474                 :             : 
     475                 :          60 :     do {
     476                 :          60 :         bool tip_changed{false};
     477                 :          60 :         {
     478                 :          60 :             WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
     479                 :             :             // Note that wait_until() checks the predicate before waiting
     480         [ +  - ]:          60 :             kernel_notifications.m_tip_block_cv.wait_until(lock, std::min(now + tick, deadline), [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
     481                 :          65 :                 AssertLockHeld(kernel_notifications.m_tip_block_mutex);
     482                 :          65 :                 const auto tip_block{kernel_notifications.TipBlock()};
     483                 :             :                 // We assume tip_block is set, because this is an instance
     484                 :             :                 // method on BlockTemplate and no template could have been
     485                 :             :                 // generated before a tip exists.
     486   [ +  -  +  + ]:          65 :                 tip_changed = Assume(tip_block) && tip_block != block_template->block.hashPrevBlock;
     487   [ +  +  -  + ]:          65 :                 return tip_changed || chainman.m_interrupt;
     488                 :             :             });
     489                 :           0 :         }
     490                 :             : 
     491         [ -  + ]:          60 :         if (chainman.m_interrupt) return nullptr;
     492                 :             :         // At this point the tip changed, a full tick went by or we reached
     493                 :             :         // the deadline.
     494                 :             : 
     495                 :             :         // Must release m_tip_block_mutex before locking cs_main, to avoid deadlocks.
     496                 :          60 :         LOCK(::cs_main);
     497                 :             : 
     498                 :             :         // On test networks return a minimum difficulty block after 20 minutes
     499   [ +  +  +  + ]:          60 :         if (!tip_changed && allow_min_difficulty) {
     500   [ +  -  +  - ]:           6 :             const NodeClock::time_point tip_time{std::chrono::seconds{chainman.ActiveChain().Tip()->GetBlockTime()}};
     501         [ +  + ]:           3 :             if (now > tip_time + 20min) {
     502                 :           1 :                 tip_changed = true;
     503                 :             :             }
     504                 :             :         }
     505                 :             : 
     506                 :             :         /**
     507                 :             :          * We determine if fees increased compared to the previous template by generating
     508                 :             :          * a fresh template. There may be more efficient ways to determine how much
     509                 :             :          * (approximate) fees for the next block increased, perhaps more so after
     510                 :             :          * Cluster Mempool.
     511                 :             :          *
     512                 :             :          * We'll also create a new template if the tip changed during this iteration.
     513                 :             :          */
     514   [ +  +  +  - ]:          60 :         if (options.fee_threshold < MAX_MONEY || tip_changed) {
     515                 :          60 :             auto new_tmpl{BlockAssembler{
     516                 :             :                 chainman.ActiveChainstate(),
     517                 :             :                 mempool,
     518   [ +  -  +  - ]:          60 :                 assemble_options}
     519         [ +  - ]:          60 :                               .CreateNewBlock()};
     520                 :             : 
     521                 :             :             // If the tip changed, return the new template regardless of its fees.
     522         [ +  + ]:          60 :             if (tip_changed) return new_tmpl;
     523                 :             : 
     524                 :             :             // Calculate the original template total fees if we haven't already
     525         [ +  - ]:           4 :             if (current_fees == -1) {
     526                 :           4 :                 current_fees = 0;
     527         [ +  + ]:          10 :                 for (CAmount fee : block_template->vTxFees) {
     528                 :           6 :                     current_fees += fee;
     529                 :             :                 }
     530                 :             :             }
     531                 :             : 
     532                 :           4 :             CAmount new_fees = 0;
     533         [ +  + ]:          11 :             for (CAmount fee : new_tmpl->vTxFees) {
     534                 :           8 :                 new_fees += fee;
     535                 :           8 :                 Assume(options.fee_threshold != MAX_MONEY);
     536         [ +  + ]:           8 :                 if (new_fees >= current_fees + options.fee_threshold) return new_tmpl;
     537                 :             :             }
     538         [ +  - ]:          60 :         }
     539                 :             : 
     540         [ +  - ]:           3 :         now = NodeClock::now();
     541         [ -  + ]:          60 :     } while (now < deadline);
     542                 :             : 
     543                 :           3 :     return nullptr;
     544                 :             : }
     545                 :             : 
     546                 :         238 : std::optional<BlockRef> GetTip(ChainstateManager& chainman)
     547                 :             : {
     548                 :         238 :     LOCK(::cs_main);
     549   [ +  -  +  - ]:         238 :     CBlockIndex* tip{chainman.ActiveChain().Tip()};
     550         [ -  + ]:         238 :     if (!tip) return {};
     551                 :         238 :     return BlockRef{tip->GetBlockHash(), tip->nHeight};
     552                 :         238 : }
     553                 :             : 
     554                 :         128 : std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const uint256& current_tip, MillisecondsDouble& timeout)
     555                 :             : {
     556                 :         128 :     Assume(timeout >= 0ms); // No internal callers should use a negative timeout
     557         [ -  + ]:         128 :     if (timeout < 0ms) timeout = 0ms;
     558         [ +  - ]:         128 :     if (timeout > std::chrono::years{100}) timeout = std::chrono::years{100}; // Upper bound to avoid UB in std::chrono
     559                 :         128 :     auto deadline{std::chrono::steady_clock::now() + timeout};
     560                 :         128 :     {
     561                 :         128 :         WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
     562                 :             :         // For callers convenience, wait longer than the provided timeout
     563                 :             :         // during startup for the tip to be non-null. That way this function
     564                 :             :         // always returns valid tip information when possible and only
     565                 :             :         // returns null when shutting down, not when timing out.
     566         [ +  - ]:         128 :         kernel_notifications.m_tip_block_cv.wait(lock, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
     567   [ -  +  -  - ]:         128 :             return kernel_notifications.TipBlock() || chainman.m_interrupt;
     568                 :             :         });
     569   [ +  -  -  +  :         128 :         if (chainman.m_interrupt) return {};
                   -  - ]
     570                 :             :         // At this point TipBlock is set, so continue to wait until it is
     571                 :             :         // different then `current_tip` provided by caller.
     572         [ +  - ]:         128 :         kernel_notifications.m_tip_block_cv.wait_until(lock, deadline, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
     573   [ -  +  -  - ]:         128 :             return Assume(kernel_notifications.TipBlock()) != current_tip || chainman.m_interrupt;
     574                 :             :         });
     575                 :           0 :     }
     576         [ -  + ]:         128 :     if (chainman.m_interrupt) return {};
     577                 :             : 
     578                 :             :     // Must release m_tip_block_mutex before getTip() locks cs_main, to
     579                 :             :     // avoid deadlocks.
     580                 :         128 :     return GetTip(chainman);
     581                 :             : }
     582                 :             : } // namespace node
        

Generated by: LCOV version 2.0-1