miner.cpp raw

   1  // Copyright (c) 2009-2010 Satoshi Nakamoto
   2  // Copyright (c) 2009-2022 The Limenka 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/params.h>
  16  #include <consensus/tx_verify.h>
  17  #include <consensus/validation.h>
  18  #include <consensus/delay.h>
  19  #include <deploymentstatus.h>
  20  #include <logging.h>
  21  #include <node/context.h>
  22  #include <policy/feerate.h>
  23  #include <policy/policy.h>
  24  #include <pow.h>
  25  #include <pow_fork.h>
  26  #include <primitives/block.h>
  27  #include <primitives/transaction.h>
  28  #include <util/moneystr.h>
  29  #include <util/time.h>
  30  #include <validation.h>
  31  #include <validationinterface.h>
  32  
  33  #include <algorithm>
  34  #include <utility>
  35  
  36  namespace node {
  37  
  38  int64_t GetMinimumTime(const CBlockIndex* pindexPrev, const int64_t difficulty_adjustment_interval)
  39  {
  40      int64_t min_time{pindexPrev->GetMedianTimePast() + 1};
  41      // Height of block to be mined.
  42      const int height{pindexPrev->nHeight + 1};
  43      // Account for BIP94 timewarp rule on all networks. This makes future
  44      // activation safer.
  45      if (height % difficulty_adjustment_interval == 0) {
  46          min_time = std::max<int64_t>(min_time, pindexPrev->GetBlockTime() - MAX_TIMEWARP);
  47      }
  48      return min_time;
  49  }
  50  
  51  int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
  52  {
  53      int64_t nOldTime = pblock->nTime;
  54      int64_t nNewTime{std::max<int64_t>(GetMinimumTime(pindexPrev, consensusParams.DifficultyAdjustmentInterval()),
  55                                         TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()))};
  56  
  57      if (nOldTime < nNewTime) {
  58          pblock->nTime = nNewTime;
  59      }
  60  
  61      // Updating time can change work required on testnet:
  62      if (consensusParams.fPowAllowMinDifficultyBlocks) {
  63          pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
  64      }
  65  
  66      return nNewTime - nOldTime;
  67  }
  68  
  69  void RegenerateCommitments(CBlock& block, ChainstateManager& chainman)
  70  {
  71      CMutableTransaction tx{*block.vtx.at(0)};
  72      tx.vout.erase(tx.vout.begin() + GetWitnessCommitmentIndex(block));
  73      block.vtx.at(0) = MakeTransactionRef(tx);
  74  
  75      const CBlockIndex* prev_block = WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock));
  76      chainman.GenerateCoinbaseCommitment(block, prev_block);
  77  
  78      block.hashMerkleRoot = BlockMerkleRoot(block);
  79  }
  80  
  81  BlockCreateOptions BlockCreateOptions::Clamped() const
  82  {
  83      BlockAssembler::Options options = *this;
  84      CHECK_NONFATAL(options.block_reserved_size <= MAX_BLOCK_SERIALIZED_SIZE);
  85      CHECK_NONFATAL(options.block_reserved_weight <= MAX_BLOCK_WEIGHT);
  86      CHECK_NONFATAL(options.block_reserved_weight >= MINIMUM_BLOCK_RESERVED_WEIGHT);
  87      CHECK_NONFATAL(options.coinbase_output_max_additional_sigops <= MAX_BLOCK_SIGOPS_COST);
  88      // Limit size to between block_reserved_size and MAX_BLOCK_SERIALIZED_SIZE-1K for sanity:
  89      options.nBlockMaxSize = std::clamp<size_t>(options.nBlockMaxSize, options.block_reserved_size, MAX_BLOCK_SERIALIZED_SIZE);
  90      // Limit weight to between block_reserved_weight and MAX_BLOCK_WEIGHT for sanity:
  91      // block_reserved_weight can safely exceed -blockmaxweight, but the rest of the block template will be empty.
  92      options.nBlockMaxWeight = std::clamp<size_t>(options.nBlockMaxWeight, options.block_reserved_weight, MAX_BLOCK_WEIGHT);
  93      return options;
  94  }
  95  
  96  BlockAssembler::BlockAssembler(Chainstate& chainstate, const CTxMemPool* mempool, const Options& options, const NodeContext& node)
  97      : chainparams{chainstate.m_chainman.GetParams()},
  98        m_mempool{options.use_mempool ? mempool : nullptr},
  99        m_chainstate{chainstate},
 100        m_node{node},
 101        m_options{options.Clamped()}
 102  {
 103      // Whether we need to account for byte usage (in addition to weight usage)
 104      fNeedSizeAccounting = (options.nBlockMaxSize < MAX_BLOCK_SERIALIZED_SIZE);
 105  }
 106  
 107  void ApplyArgsManOptions(const ArgsManager& args, BlockAssembler::Options& options)
 108  {
 109      // Block resource limits
 110      // If neither -blockmaxsize or -blockmaxweight is given, limit to DEFAULT_BLOCK_MAX_*
 111      // If only one is given, only restrict the specified resource.
 112      // If both are given, restrict both.
 113      bool fWeightSet = false;
 114      if (args.IsArgSet("-blockmaxweight")) {
 115          options.nBlockMaxWeight = args.GetIntArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
 116          options.nBlockMaxSize = MAX_BLOCK_SERIALIZED_SIZE;
 117          fWeightSet = true;
 118      }
 119      if (args.IsArgSet("-blockmaxsize")) {
 120          options.nBlockMaxSize = args.GetIntArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
 121          if (!fWeightSet) {
 122              options.nBlockMaxWeight = MAX_BLOCK_WEIGHT;
 123          }
 124      }
 125      if (const auto blockmintxfee{args.GetArg("-blockmintxfee")}) {
 126          if (const auto parsed{ParseMoney(*blockmintxfee)}) options.blockMinFeeRate = CFeeRate{*parsed};
 127      }
 128      options.print_modified_fee = args.GetBoolArg("-printpriority", options.print_modified_fee);
 129      options.block_reserved_weight = args.GetIntArg("-blockreservedweight", options.block_reserved_weight);
 130  }
 131  
 132  void BlockAssembler::resetBlock()
 133  {
 134      inBlock.clear();
 135  
 136      // Reserve space for fixed-size block header, txs count, and coinbase tx.
 137      nBlockSize = m_options.block_reserved_size;
 138      nBlockWeight = m_options.block_reserved_weight;
 139      nBlockSigOpsCost = m_options.coinbase_output_max_additional_sigops;
 140  
 141      // These counters do not include coinbase tx
 142      nBlockTx = 0;
 143      nFees = 0;
 144  
 145      lastFewTxs = 0;
 146      blockFinished = false;
 147  }
 148  
 149  std::shared_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock()
 150  {
 151      const auto time_start{SteadyClock::now()};
 152  
 153      resetBlock();
 154  
 155      pblocktemplate.reset(new CBlockTemplate());
 156      CBlock* const pblock = &pblocktemplate->block; // pointer for convenience
 157  
 158      // Add dummy coinbase tx as first transaction
 159      pblock->vtx.emplace_back();
 160      pblocktemplate->vTxFees.push_back(-1); // updated at end
 161      pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end
 162      if (m_options.print_modified_fee) {
 163          pblocktemplate->vTxPriorities.push_back(-1);  // n/a
 164      }
 165  
 166      LOCK(::cs_main);
 167      CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip();
 168      assert(pindexPrev != nullptr);
 169      nHeight = pindexPrev->nHeight + 1;
 170  
 171      pblock->nVersion = m_chainstate.m_chainman.m_versionbitscache.ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
 172      // -regtest only: allow overriding block.nVersion with
 173      // -blockversion=N to test forking scenarios
 174      if (chainparams.MineBlocksOnDemand()) {
 175          pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion);
 176      }
 177  
 178      // Fork chain: 10-minute blocks, single lane.  Block weight is bounded
 179      // by the time-proportional payload limit enforced in
 180      // ContextualCheckBlock.  The assembler target mirrors that limit:
 181      // payload = S_max * e / 600 (header+coinbase excluded).
 182      const bool is_fork{IsForkActive(pindexPrev, chainparams.GetConsensus())};
 183      if (is_fork) {
 184          const auto& cp = chainparams.GetConsensus();
 185          int64_t e_assemble = pindexPrev->nForkLastBlockTime != 0
 186              ? int64_t{TicksSinceEpoch<std::chrono::seconds>(NodeClock::now())} - pindexPrev->nForkLastBlockTime
 187              : cp.nForkIntervalTarget;
 188          if (e_assemble < 1) e_assemble = 1;
 189          m_options.nBlockMaxWeight = size_t{GetForkPayloadWeightLimit(e_assemble, MAX_BLOCK_WEIGHT)} + MAX_BLOCK_WEIGHT / 10;
 190      }
 191  
 192      pblock->nTime = TicksSinceEpoch<std::chrono::seconds>(NodeClock::now());
 193      m_lock_time_cutoff = pindexPrev->GetMedianTimePast();
 194  
 195      int nPackagesSelected = 0;
 196      int nDescendantsUpdated = 0;
 197      if (m_mempool) {
 198          LOCK(m_mempool->cs);
 199          addPriorityTxs(*m_mempool, nPackagesSelected);
 200          addPackageTxs(*m_mempool, nPackagesSelected, nDescendantsUpdated);
 201      }
 202  
 203      const auto time_1{SteadyClock::now()};
 204  
 205      m_last_block_num_txs = nBlockTx;
 206      m_last_block_weight = nBlockWeight;
 207      if (fNeedSizeAccounting) {
 208          m_last_block_size = nBlockSize;
 209      } else {
 210          m_last_block_size = std::nullopt;
 211      }
 212  
 213      // Create coinbase transaction.
 214      CMutableTransaction coinbaseTx;
 215      coinbaseTx.vin.resize(1);
 216      coinbaseTx.vin[0].prevout.SetNull();
 217      coinbaseTx.vout.resize(1);
 218      coinbaseTx.vout[0].scriptPubKey = m_options.coinbase_output_script;
 219  
 220      // Fork chain: time-proportional reward R(e) = R_full * e / 600 and
 221      // the sequential delay commitment.
 222      if (is_fork) {
 223          const auto& cp = chainparams.GetConsensus();
 224          int64_t e = pindexPrev->nForkLastBlockTime != 0
 225              ? (int64_t)pblock->nTime - pindexPrev->nForkLastBlockTime
 226              : (int64_t)pblock->nTime - pindexPrev->GetBlockTime();  // first block: actual interval
 227          if (e < 1) e = 1;
 228          // At the activation boundary (prev is a parent-chain block),
 229          // seed the aggregate-seconds epoch from the chain height so the
 230          // fork continues the parent's halving schedule.
 231          int64_t agg_base = IsForkActive(pindexPrev->pprev, cp)
 232              ? pindexPrev->nForkAggregateSeconds
 233              : int64_t(nHeight) * 600;
 234          CAmount fork_reward = GetForkBlockSubsidy(
 235              e, agg_base,
 236              cp.nSubsidyHalvingInterval);
 237          coinbaseTx.vout[0].nValue = fork_reward + nFees;
 238  
 239          coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
 240  
 241          // Delay commitment: OP_RETURN <"LD"> <8-byte LE remainder>.
 242          // The sequential long division binds prev_hash; recomputation
 243          // by validators (~60s) is the verification.
 244          uint64_t delay_value = ComputeDelay(pindexPrev->GetBlockHash(), cp.nForkDelaySteps);
 245          CTxOut delay_out;
 246          delay_out.nValue = 0;
 247          std::vector<uint8_t> delay_magic = {DELAY_MAGIC_BYTE0, DELAY_MAGIC_BYTE1};
 248          std::vector<uint8_t> delay_bytes(8);
 249          for (int i = 0; i < 8; i++) delay_bytes[i] = (uint8_t)(delay_value >> (8 * i));
 250          delay_out.scriptPubKey << OP_RETURN << delay_magic << delay_bytes;
 251          coinbaseTx.vout.push_back(delay_out);
 252      } else {
 253          coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
 254          coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
 255      }
 256  
 257      // Witness reserved value (BIP141): a single 32-byte stack item, hashed
 258      // into the witness commitment by GenerateCoinbaseCommitment below.
 259      // Only when segwit rules are expected (blocks without a witness
 260      // commitment must not carry any witness data).
 261      const bool segwit_expected =
 262          DeploymentActiveAfter(pindexPrev, m_chainstate.m_chainman, Consensus::DEPLOYMENT_SEGWIT) ||
 263          (pindexPrev && IsForkActive(pindexPrev, chainparams.GetConsensus()));
 264      if (segwit_expected) {
 265          coinbaseTx.vin[0].scriptWitness.stack.resize(1);
 266          coinbaseTx.vin[0].scriptWitness.stack[0].resize(32);
 267      }
 268  
 269      pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
 270      pblocktemplate->vchCoinbaseCommitment = m_chainstate.m_chainman.GenerateCoinbaseCommitment(*pblock, pindexPrev);
 271      pblocktemplate->vTxFees[0] = -nFees;
 272  
 273      uint64_t nSerializeSize = GetSerializeSize(TX_WITH_WITNESS(*pblock));
 274      LogPrintf("CreateNewBlock(): total size: %u block weight: %u txs: %u fees: %ld sigops %d\n", nSerializeSize, GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
 275  
 276      // Fill in header
 277      pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
 278      UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
 279      pblock->nBits          = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
 280      pblock->nNonce         = 0;
 281      pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]);
 282  
 283      BlockValidationState state;
 284      if (m_options.test_block_validity && !TestBlockValidity(state, chainparams, m_chainstate, *pblock, pindexPrev,
 285                                                              /*fCheckPOW=*/false, /*fCheckMerkleRoot=*/false)) {
 286          throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, state.ToString()));
 287      }
 288      const auto time_2{SteadyClock::now()};
 289  
 290      LogDebug(BCLog::BENCH, "CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n",
 291               Ticks<MillisecondsDouble>(time_1 - time_start), nPackagesSelected, nDescendantsUpdated,
 292               Ticks<MillisecondsDouble>(time_2 - time_1),
 293               Ticks<MillisecondsDouble>(time_2 - time_start));
 294  
 295      if (m_node.validation_signals) m_node.validation_signals->NewBlockTemplate(pblocktemplate);
 296  
 297      return std::move(pblocktemplate);
 298  }
 299  
 300  void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet)
 301  {
 302      for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
 303          // Only test txs not already in the block
 304          if (inBlock.count(*iit)) {
 305              testSet.erase(iit++);
 306          } else {
 307              iit++;
 308          }
 309      }
 310  }
 311  
 312  bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
 313  {
 314      // TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
 315      if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= m_options.nBlockMaxWeight) {
 316          return false;
 317      }
 318      if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST) {
 319          return false;
 320      }
 321      return true;
 322  }
 323  
 324  // Perform transaction-level checks before adding to block:
 325  // - transaction finality (locktime)
 326  // - serialized size (in case -blockmaxsize is in use)
 327  bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package) const
 328  {
 329      uint64_t nPotentialBlockSize = nBlockSize; // only used with fNeedSizeAccounting
 330      for (CTxMemPool::txiter it : package) {
 331          if (!IsFinalTx(it->GetTx(), nHeight, m_lock_time_cutoff)) {
 332              return false;
 333          }
 334          if (fNeedSizeAccounting) {
 335              uint64_t nTxSize = ::GetSerializeSize(TX_WITH_WITNESS(it->GetTx()));
 336              if (nPotentialBlockSize + nTxSize >= m_options.nBlockMaxSize) {
 337                  return false;
 338              }
 339              nPotentialBlockSize += nTxSize;
 340          }
 341      }
 342      return true;
 343  }
 344  
 345  void BlockAssembler::AddToBlock(const CTxMemPool& mempool, CTxMemPool::txiter iter)
 346  {
 347      pblocktemplate->block.vtx.emplace_back(iter->GetSharedTx());
 348      pblocktemplate->vTxFees.push_back(iter->GetFee());
 349      pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
 350      if (fNeedSizeAccounting) {
 351          nBlockSize += ::GetSerializeSize(TX_WITH_WITNESS(iter->GetTx()));
 352      }
 353      nBlockWeight += iter->GetTxWeight();
 354      ++nBlockTx;
 355      nBlockSigOpsCost += iter->GetSigOpCost();
 356      nFees += iter->GetFee();
 357      inBlock.insert(iter);
 358  
 359      if (m_options.print_modified_fee) {
 360          double dPriority = iter->GetPriority(nHeight);
 361          CAmount dummy;
 362          mempool.ApplyDeltas(iter->GetTx().GetHash(), dPriority, dummy);
 363          LogPrintf("priority %.1f fee rate %s txid %s\n",
 364                    dPriority,
 365                    CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
 366                    iter->GetTx().GetHash().ToString());
 367          pblocktemplate->vTxPriorities.push_back(dPriority);
 368      }
 369  }
 370  
 371  /** Add descendants of given transactions to mapModifiedTx with ancestor
 372   * state updated assuming given transactions are inBlock. Returns number
 373   * of updated descendants. */
 374  static int UpdatePackagesForAdded(const CTxMemPool& mempool,
 375                                    const CTxMemPool::setEntries& alreadyAdded,
 376                                    indexed_modified_transaction_set& mapModifiedTx) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs)
 377  {
 378      AssertLockHeld(mempool.cs);
 379  
 380      int nDescendantsUpdated = 0;
 381      for (CTxMemPool::txiter it : alreadyAdded) {
 382          CTxMemPool::setEntries descendants;
 383          mempool.CalculateDescendants(it, descendants);
 384          // Insert all descendants (not yet in block) into the modified set
 385          for (CTxMemPool::txiter desc : descendants) {
 386              if (alreadyAdded.count(desc)) {
 387                  continue;
 388              }
 389              ++nDescendantsUpdated;
 390              modtxiter mit = mapModifiedTx.find(desc);
 391              if (mit == mapModifiedTx.end()) {
 392                  CTxMemPoolModifiedEntry modEntry(desc);
 393                  mit = mapModifiedTx.insert(modEntry).first;
 394              }
 395              mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
 396          }
 397      }
 398      return nDescendantsUpdated;
 399  }
 400  
 401  void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, std::vector<CTxMemPool::txiter>& sortedEntries)
 402  {
 403      // Sort package by ancestor count
 404      // If a transaction A depends on transaction B, then A's ancestor count
 405      // must be greater than B's.  So this is sufficient to validly order the
 406      // transactions for block inclusion.
 407      sortedEntries.clear();
 408      sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
 409      std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
 410  }
 411  
 412  // This transaction selection algorithm orders the mempool based
 413  // on feerate of a transaction including all unconfirmed ancestors.
 414  // Since we don't remove transactions from the mempool as we select them
 415  // for block inclusion, we need an alternate method of updating the feerate
 416  // of a transaction with its not-yet-selected ancestors as we go.
 417  // This is accomplished by walking the in-mempool descendants of selected
 418  // transactions and storing a temporary modified state in mapModifiedTxs.
 419  // Each time through the loop, we compare the best transaction in
 420  // mapModifiedTxs with the next transaction in the mempool to decide what
 421  // transaction package to work on next.
 422  void BlockAssembler::addPackageTxs(const CTxMemPool& mempool, int& nPackagesSelected, int& nDescendantsUpdated)
 423  {
 424      AssertLockHeld(mempool.cs);
 425  
 426      // mapModifiedTx will store sorted packages after they are modified
 427      // because some of their txs are already in the block
 428      indexed_modified_transaction_set mapModifiedTx;
 429      // Keep track of entries that failed inclusion, to avoid duplicate work
 430      CTxMemPool::setEntries failedTx;
 431  
 432      // Start by adding all descendants of previously added txs to mapModifiedTx
 433      // and modifying them for their already included ancestors
 434      nDescendantsUpdated += UpdatePackagesForAdded(mempool, inBlock, mapModifiedTx);
 435      CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin();
 436      CTxMemPool::txiter iter;
 437  
 438      // Limit the number of attempts to add transactions to the block when it is
 439      // close to full; this is just a simple heuristic to finish quickly if the
 440      // mempool has a lot of entries.
 441      const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
 442      constexpr int32_t BLOCK_FULL_ENOUGH_SIZE_DELTA = 1000;
 443      constexpr int32_t BLOCK_FULL_ENOUGH_WEIGHT_DELTA = 4000;
 444      int64_t nConsecutiveFailed = 0;
 445  
 446      while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty()) {
 447          // First try to find a new transaction in mapTx to evaluate.
 448          //
 449          // Skip entries in mapTx that are already in a block or are present
 450          // in mapModifiedTx (which implies that the mapTx ancestor state is
 451          // stale due to ancestor inclusion in the block)
 452          // Also skip transactions that we've already failed to add. This can happen if
 453          // we consider a transaction in mapModifiedTx and it fails: we can then
 454          // potentially consider it again while walking mapTx.  It's currently
 455          // guaranteed to fail again, but as a belt-and-suspenders check we put it in
 456          // failedTx and avoid re-evaluation, since the re-evaluation would be using
 457          // cached size/sigops/fee values that are not actually correct.
 458          /** Return true if given transaction from mapTx has already been evaluated,
 459           * or if the transaction's cached data in mapTx is incorrect. */
 460          if (mi != mempool.mapTx.get<ancestor_score>().end()) {
 461              auto it = mempool.mapTx.project<0>(mi);
 462              assert(it != mempool.mapTx.end());
 463              if (mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it)) {
 464                  ++mi;
 465                  continue;
 466              }
 467          }
 468  
 469          // Now that mi is not stale, determine which transaction to evaluate:
 470          // the next entry from mapTx, or the best from mapModifiedTx?
 471          bool fUsingModified = false;
 472  
 473          modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
 474          if (mi == mempool.mapTx.get<ancestor_score>().end()) {
 475              // We're out of entries in mapTx; use the entry from mapModifiedTx
 476              iter = modit->iter;
 477              fUsingModified = true;
 478          } else {
 479              // Try to compare the mapTx entry to the mapModifiedTx entry
 480              iter = mempool.mapTx.project<0>(mi);
 481              if (modit != mapModifiedTx.get<ancestor_score>().end() &&
 482                      CompareTxMemPoolEntryByAncestorFee()(*modit, CTxMemPoolModifiedEntry(iter))) {
 483                  // The best entry in mapModifiedTx has higher score
 484                  // than the one from mapTx.
 485                  // Switch which transaction (package) to consider
 486                  iter = modit->iter;
 487                  fUsingModified = true;
 488              } else {
 489                  // Either no entry in mapModifiedTx, or it's worse than mapTx.
 490                  // Increment mi for the next loop iteration.
 491                  ++mi;
 492              }
 493          }
 494  
 495          // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
 496          // contain anything that is inBlock.
 497          assert(!inBlock.count(iter));
 498  
 499          uint64_t packageSize = iter->GetSizeWithAncestors();
 500          CAmount packageFees = iter->GetModFeesWithAncestors();
 501          int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
 502          if (fUsingModified) {
 503              packageSize = modit->nSizeWithAncestors;
 504              packageFees = modit->nModFeesWithAncestors;
 505              packageSigOpsCost = modit->nSigOpCostWithAncestors;
 506          }
 507  
 508          if (packageFees < m_options.blockMinFeeRate.GetFee(packageSize)) {
 509              // Everything else we might consider has a lower fee rate
 510              return;
 511          }
 512  
 513          if (!TestPackage(packageSize, packageSigOpsCost)) {
 514              if (fUsingModified) {
 515                  // Since we always look at the best entry in mapModifiedTx,
 516                  // we must erase failed entries so that we can consider the
 517                  // next best entry on the next loop iteration
 518                  mapModifiedTx.get<ancestor_score>().erase(modit);
 519                  failedTx.insert(iter);
 520              }
 521  
 522              ++nConsecutiveFailed;
 523  
 524              if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight +
 525                      BLOCK_FULL_ENOUGH_WEIGHT_DELTA > m_options.nBlockMaxWeight) {
 526                  // Give up if we're close to full and haven't succeeded in a while
 527                  break;
 528              }
 529              continue;
 530          }
 531  
 532          auto ancestors{mempool.AssumeCalculateMemPoolAncestors(__func__, *iter, CTxMemPool::Limits::NoLimits(), /*fSearchForParents=*/false)};
 533  
 534          onlyUnconfirmed(ancestors);
 535          ancestors.insert(iter);
 536  
 537          // Test if all tx's are Final
 538          if (!TestPackageTransactions(ancestors)) {
 539              if (fUsingModified) {
 540                  mapModifiedTx.get<ancestor_score>().erase(modit);
 541                  failedTx.insert(iter);
 542              }
 543  
 544              if (fNeedSizeAccounting) {
 545                  ++nConsecutiveFailed;
 546  
 547                  if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockSize > m_options.nBlockMaxSize - BLOCK_FULL_ENOUGH_SIZE_DELTA) {
 548                      // Give up if we're close to full and haven't succeeded in a while
 549                      break;
 550                  }
 551              }
 552              continue;
 553          }
 554  
 555          // This transaction will make it in; reset the failed counter.
 556          nConsecutiveFailed = 0;
 557  
 558          // Package can be added. Sort the entries in a valid order.
 559          std::vector<CTxMemPool::txiter> sortedEntries;
 560          SortForBlock(ancestors, sortedEntries);
 561  
 562          for (size_t i = 0; i < sortedEntries.size(); ++i) {
 563              AddToBlock(mempool, sortedEntries[i]);
 564              // Erase from the modified set, if present
 565              mapModifiedTx.erase(sortedEntries[i]);
 566          }
 567  
 568          ++nPackagesSelected;
 569          pblocktemplate->m_package_feerates.emplace_back(packageFees, static_cast<int32_t>(packageSize));
 570  
 571          // Update transactions that depend on each of these
 572          nDescendantsUpdated += UpdatePackagesForAdded(mempool, ancestors, mapModifiedTx);
 573      }
 574  }
 575  } // namespace node
 576