LCOV - code coverage report
Current view: top level - src/node - miner.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 94.9 % 235 223
Test Date: 2026-01-16 05:29:45 Functions: 95.2 % 21 20
Branches: 62.6 % 310 194

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2                 :             : // Copyright (c) 2009-present 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                 :             : #include <numeric>
      33                 :             : 
      34                 :             : namespace node {
      35                 :             : 
      36                 :       52310 : int64_t GetMinimumTime(const CBlockIndex* pindexPrev, const int64_t difficulty_adjustment_interval)
      37                 :             : {
      38                 :       52310 :     int64_t min_time{pindexPrev->GetMedianTimePast() + 1};
      39                 :             :     // Height of block to be mined.
      40                 :       52310 :     const int height{pindexPrev->nHeight + 1};
      41                 :             :     // Account for BIP94 timewarp rule on all networks. This makes future
      42                 :             :     // activation safer.
      43         [ +  + ]:       52310 :     if (height % difficulty_adjustment_interval == 0) {
      44         [ +  + ]:         472 :         min_time = std::max<int64_t>(min_time, pindexPrev->GetBlockTime() - MAX_TIMEWARP);
      45                 :             :     }
      46                 :       52310 :     return min_time;
      47                 :             : }
      48                 :             : 
      49                 :       50231 : int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
      50                 :             : {
      51                 :       50231 :     int64_t nOldTime = pblock->nTime;
      52         [ +  + ]:       50231 :     int64_t nNewTime{std::max<int64_t>(GetMinimumTime(pindexPrev, consensusParams.DifficultyAdjustmentInterval()),
      53                 :       50231 :                                        TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()))};
      54                 :             : 
      55         [ +  + ]:       50231 :     if (nOldTime < nNewTime) {
      56                 :       38588 :         pblock->nTime = nNewTime;
      57                 :             :     }
      58                 :             : 
      59                 :             :     // Updating time can change work required on testnet:
      60         [ +  + ]:       50231 :     if (consensusParams.fPowAllowMinDifficultyBlocks) {
      61                 :       50078 :         pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
      62                 :             :     }
      63                 :             : 
      64                 :       50231 :     return nNewTime - nOldTime;
      65                 :             : }
      66                 :             : 
      67                 :        6958 : void RegenerateCommitments(CBlock& block, ChainstateManager& chainman)
      68                 :             : {
      69                 :        6958 :     CMutableTransaction tx{*block.vtx.at(0)};
      70                 :        6958 :     tx.vout.erase(tx.vout.begin() + GetWitnessCommitmentIndex(block));
      71   [ +  -  +  -  :       13916 :     block.vtx.at(0) = MakeTransactionRef(tx);
                   -  + ]
      72                 :             : 
      73   [ +  -  +  -  :       20874 :     const CBlockIndex* prev_block = WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock));
                   +  - ]
      74         [ +  - ]:        6958 :     chainman.GenerateCoinbaseCommitment(block, prev_block);
      75                 :             : 
      76         [ +  - ]:        6958 :     block.hashMerkleRoot = BlockMerkleRoot(block);
      77                 :        6958 : }
      78                 :             : 
      79                 :       48128 : static BlockAssembler::Options ClampOptions(BlockAssembler::Options options)
      80                 :             : {
      81         [ +  - ]:       48128 :     options.block_reserved_weight = std::clamp<size_t>(options.block_reserved_weight, MINIMUM_BLOCK_RESERVED_WEIGHT, MAX_BLOCK_WEIGHT);
      82         [ -  + ]:       48128 :     options.coinbase_output_max_additional_sigops = std::clamp<size_t>(options.coinbase_output_max_additional_sigops, 0, 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         [ +  - ]:       48128 :     options.nBlockMaxWeight = std::clamp<size_t>(options.nBlockMaxWeight, options.block_reserved_weight, MAX_BLOCK_WEIGHT);
      86                 :       48128 :     return options;
      87                 :             : }
      88                 :             : 
      89                 :       48128 : BlockAssembler::BlockAssembler(Chainstate& chainstate, const CTxMemPool* mempool, const Options& options)
      90         [ +  + ]:       48128 :     : chainparams{chainstate.m_chainman.GetParams()},
      91         [ +  + ]:       48128 :       m_mempool{options.use_mempool ? mempool : nullptr},
      92                 :       48128 :       m_chainstate{chainstate},
      93         [ +  + ]:       48476 :       m_options{ClampOptions(options)}
      94                 :             : {
      95                 :       48128 : }
      96                 :             : 
      97                 :       40586 : void ApplyArgsManOptions(const ArgsManager& args, BlockAssembler::Options& options)
      98                 :             : {
      99                 :             :     // Block resource limits
     100         [ +  - ]:       40586 :     options.nBlockMaxWeight = args.GetIntArg("-blockmaxweight", options.nBlockMaxWeight);
     101   [ +  -  +  + ]:       81172 :     if (const auto blockmintxfee{args.GetArg("-blockmintxfee")}) {
     102   [ +  -  +  - ]:          36 :         if (const auto parsed{ParseMoney(*blockmintxfee)}) options.blockMinFeeRate = CFeeRate{*parsed};
     103                 :           0 :     }
     104         [ +  - ]:       40586 :     options.print_modified_fee = args.GetBoolArg("-printpriority", options.print_modified_fee);
     105         [ +  - ]:       40586 :     options.block_reserved_weight = args.GetIntArg("-blockreservedweight", options.block_reserved_weight);
     106                 :       40586 : }
     107                 :             : 
     108                 :       48128 : void BlockAssembler::resetBlock()
     109                 :             : {
     110                 :             :     // Reserve space for fixed-size block header, txs count, and coinbase tx.
     111                 :       48128 :     nBlockWeight = m_options.block_reserved_weight;
     112                 :       48128 :     nBlockSigOpsCost = m_options.coinbase_output_max_additional_sigops;
     113                 :             : 
     114                 :             :     // These counters do not include coinbase tx
     115                 :       48128 :     nBlockTx = 0;
     116                 :       48128 :     nFees = 0;
     117                 :       48128 : }
     118                 :             : 
     119                 :       48128 : std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock()
     120                 :             : {
     121                 :       48128 :     const auto time_start{SteadyClock::now()};
     122                 :             : 
     123                 :       48128 :     resetBlock();
     124                 :             : 
     125         [ -  + ]:       48128 :     pblocktemplate.reset(new CBlockTemplate());
     126                 :       48128 :     CBlock* const pblock = &pblocktemplate->block; // pointer for convenience
     127                 :             : 
     128                 :             :     // Add dummy coinbase tx as first transaction. It is skipped by the
     129                 :             :     // getblocktemplate RPC and mining interface consumers must not use it.
     130                 :       48128 :     pblock->vtx.emplace_back();
     131                 :             : 
     132                 :       48128 :     LOCK(::cs_main);
     133         [ -  + ]:       48128 :     CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip();
     134         [ -  + ]:       48128 :     assert(pindexPrev != nullptr);
     135                 :       48128 :     nHeight = pindexPrev->nHeight + 1;
     136                 :             : 
     137         [ +  - ]:       48128 :     pblock->nVersion = m_chainstate.m_chainman.m_versionbitscache.ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
     138                 :             :     // -regtest only: allow overriding block.nVersion with
     139                 :             :     // -blockversion=N to test forking scenarios
     140         [ +  + ]:       48128 :     if (chainparams.MineBlocksOnDemand()) {
     141   [ +  -  +  - ]:       47982 :         pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion);
     142                 :             :     }
     143                 :             : 
     144                 :       48128 :     pblock->nTime = TicksSinceEpoch<std::chrono::seconds>(NodeClock::now());
     145                 :       48128 :     m_lock_time_cutoff = pindexPrev->GetMedianTimePast();
     146                 :             : 
     147         [ +  + ]:       48128 :     if (m_mempool) {
     148         [ +  - ]:       41168 :         LOCK(m_mempool->cs);
     149                 :       41168 :         m_mempool->StartBlockBuilding();
     150         [ +  - ]:       41168 :         addChunks();
     151         [ +  - ]:       41168 :         m_mempool->StopBlockBuilding();
     152                 :       41168 :     }
     153                 :             : 
     154                 :       48128 :     const auto time_1{SteadyClock::now()};
     155                 :             : 
     156         [ +  + ]:       48128 :     m_last_block_num_txs = nBlockTx;
     157         [ +  + ]:       48128 :     m_last_block_weight = nBlockWeight;
     158                 :             : 
     159                 :             :     // Create coinbase transaction.
     160         [ +  - ]:       48128 :     CMutableTransaction coinbaseTx;
     161                 :             : 
     162                 :             :     // Construct coinbase transaction struct in parallel
     163         [ +  - ]:       48128 :     CoinbaseTx& coinbase_tx{pblocktemplate->m_coinbase_tx};
     164                 :       48128 :     coinbase_tx.version = coinbaseTx.version;
     165                 :             : 
     166         [ +  - ]:       48128 :     coinbaseTx.vin.resize(1);
     167                 :       48128 :     coinbaseTx.vin[0].prevout.SetNull();
     168         [ +  - ]:       48128 :     coinbaseTx.vin[0].nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; // Make sure timelock is enforced.
     169                 :       48128 :     coinbase_tx.sequence = coinbaseTx.vin[0].nSequence;
     170                 :             : 
     171                 :             :     // Add an output that spends the full coinbase reward.
     172         [ +  - ]:       48128 :     coinbaseTx.vout.resize(1);
     173                 :       48128 :     coinbaseTx.vout[0].scriptPubKey = m_options.coinbase_output_script;
     174                 :             :     // Block subsidy + fees
     175         [ +  - ]:       48128 :     const CAmount block_reward{nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus())};
     176         [ +  - ]:       48128 :     coinbaseTx.vout[0].nValue = block_reward;
     177                 :       48128 :     coinbase_tx.block_reward_remaining = block_reward;
     178                 :             : 
     179                 :             :     // Start the coinbase scriptSig with the block height as required by BIP34.
     180                 :             :     // The trailing OP_0 (historically an extranonce) is optional padding and
     181                 :             :     // could be removed without a consensus change. Mining clients are expected
     182                 :             :     // to append extra data to this prefix, so increasing its length would reduce
     183                 :             :     // the space they can use and may break existing clients.
     184   [ +  -  +  - ]:       48128 :     coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
     185                 :       48128 :     coinbase_tx.script_sig_prefix = coinbaseTx.vin[0].scriptSig;
     186         [ -  + ]:       48128 :     Assert(nHeight > 0);
     187                 :       48128 :     coinbaseTx.nLockTime = static_cast<uint32_t>(nHeight - 1);
     188                 :       48128 :     coinbase_tx.lock_time = coinbaseTx.nLockTime;
     189                 :             : 
     190   [ +  -  -  + ]:       96256 :     pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
     191         [ +  - ]:       48128 :     pblocktemplate->vchCoinbaseCommitment = m_chainstate.m_chainman.GenerateCoinbaseCommitment(*pblock, pindexPrev);
     192                 :             : 
     193         [ +  + ]:       48128 :     const CTransactionRef& final_coinbase{pblock->vtx[0]};
     194         [ +  + ]:       48128 :     if (final_coinbase->HasWitness()) {
     195         [ -  + ]:       47437 :         const auto& witness_stack{final_coinbase->vin[0].scriptWitness.stack};
     196                 :             :         // Consensus requires the coinbase witness stack to have exactly one
     197                 :             :         // element of 32 bytes.
     198   [ -  +  +  -  :       47437 :         Assert(witness_stack.size() == 1 && witness_stack[0].size() == 32);
          -  +  -  +  -  
                      + ]
     199   [ -  +  -  + ]:       47437 :         coinbase_tx.witness = uint256(witness_stack[0]);
     200                 :             :     }
     201         [ +  - ]:       48128 :     if (const int witness_index = GetWitnessCommitmentIndex(*pblock); witness_index != NO_WITNESS_COMMITMENT) {
     202   [ +  -  -  +  :       48128 :         Assert(witness_index >= 0 && static_cast<size_t>(witness_index) < final_coinbase->vout.size());
             -  +  -  + ]
     203         [ +  - ]:       48128 :         coinbase_tx.required_outputs.push_back(final_coinbase->vout[witness_index]);
     204                 :             :     }
     205                 :             : 
     206         [ +  - ]:       48128 :     LogInfo("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
     207                 :             : 
     208                 :             :     // Fill in header
     209                 :       48128 :     pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
     210         [ +  - ]:       48128 :     UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
     211         [ +  - ]:       48128 :     pblock->nBits          = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
     212                 :       48128 :     pblock->nNonce         = 0;
     213                 :             : 
     214         [ +  - ]:       48128 :     if (m_options.test_block_validity) {
     215   [ +  -  +  + ]:       48128 :         if (BlockValidationState state{TestBlockValidity(m_chainstate, *pblock, /*check_pow=*/false, /*check_merkle_root=*/false)}; !state.IsValid()) {
     216   [ +  -  +  -  :          10 :             throw std::runtime_error(strprintf("TestBlockValidity failed: %s", state.ToString()));
                   +  - ]
     217                 :       48128 :         }
     218                 :             :     }
     219                 :       48123 :     const auto time_2{SteadyClock::now()};
     220                 :             : 
     221   [ +  -  +  -  :       48123 :     LogDebug(BCLog::BENCH, "CreateNewBlock() chunks: %.2fms, validity: %.2fms (total %.2fms)\n",
                   +  - ]
     222                 :             :              Ticks<MillisecondsDouble>(time_1 - time_start),
     223                 :             :              Ticks<MillisecondsDouble>(time_2 - time_1),
     224                 :             :              Ticks<MillisecondsDouble>(time_2 - time_start));
     225                 :             : 
     226                 :       48123 :     return std::move(pblocktemplate);
     227         [ +  - ]:       96251 : }
     228                 :             : 
     229                 :       46558 : bool BlockAssembler::TestChunkBlockLimits(FeePerWeight chunk_feerate, int64_t chunk_sigops_cost) const
     230                 :             : {
     231         [ +  + ]:       46558 :     if (nBlockWeight + chunk_feerate.size >= m_options.nBlockMaxWeight) {
     232                 :             :         return false;
     233                 :             :     }
     234         [ +  + ]:        9328 :     if (nBlockSigOpsCost + chunk_sigops_cost >= MAX_BLOCK_SIGOPS_COST) {
     235                 :           2 :         return false;
     236                 :             :     }
     237                 :             :     return true;
     238                 :             : }
     239                 :             : 
     240                 :             : // Perform transaction-level checks before adding to block:
     241                 :             : // - transaction finality (locktime)
     242                 :        9326 : bool BlockAssembler::TestChunkTransactions(const std::vector<CTxMemPoolEntryRef>& txs) const
     243                 :             : {
     244         [ +  + ]:       19506 :     for (const auto tx : txs) {
     245         [ +  + ]:       10182 :         if (!IsFinalTx(tx.get().GetTx(), nHeight, m_lock_time_cutoff)) {
     246                 :             :             return false;
     247                 :             :         }
     248                 :             :     }
     249                 :             :     return true;
     250                 :             : }
     251                 :             : 
     252                 :       10180 : void BlockAssembler::AddToBlock(const CTxMemPoolEntry& entry)
     253                 :             : {
     254   [ +  -  +  - ]:       20360 :     pblocktemplate->block.vtx.emplace_back(entry.GetSharedTx());
     255                 :       10180 :     pblocktemplate->vTxFees.push_back(entry.GetFee());
     256                 :       10180 :     pblocktemplate->vTxSigOpsCost.push_back(entry.GetSigOpCost());
     257         [ +  + ]:       10180 :     nBlockWeight += entry.GetTxWeight();
     258                 :       10180 :     ++nBlockTx;
     259         [ +  + ]:       10180 :     nBlockSigOpsCost += entry.GetSigOpCost();
     260                 :       10180 :     nFees += entry.GetFee();
     261                 :             : 
     262         [ +  + ]:       10180 :     if (m_options.print_modified_fee) {
     263   [ +  -  +  -  :         176 :         LogInfo("fee rate %s txid %s\n",
             +  -  +  - ]
     264                 :             :                   CFeeRate(entry.GetModifiedFee(), entry.GetTxSize()).ToString(),
     265                 :             :                   entry.GetTx().GetHash().ToString());
     266                 :             :     }
     267                 :       10180 : }
     268                 :             : 
     269                 :       41168 : void BlockAssembler::addChunks()
     270                 :             : {
     271                 :             :     // Limit the number of attempts to add transactions to the block when it is
     272                 :             :     // close to full; this is just a simple heuristic to finish quickly if the
     273                 :             :     // mempool has a lot of entries.
     274                 :       41168 :     const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
     275                 :       41168 :     constexpr int32_t BLOCK_FULL_ENOUGH_WEIGHT_DELTA = 4000;
     276                 :       41168 :     int64_t nConsecutiveFailed = 0;
     277                 :             : 
     278                 :       41168 :     std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> selected_transactions;
     279         [ +  - ]:       41168 :     selected_transactions.reserve(MAX_CLUSTER_COUNT_LIMIT);
     280                 :       41168 :     FeePerWeight chunk_feerate;
     281                 :             : 
     282                 :             :     // This fills selected_transactions
     283         [ +  - ]:       41168 :     chunk_feerate = m_mempool->GetBlockBuilderChunk(selected_transactions);
     284                 :       41168 :     FeePerVSize chunk_feerate_vsize = ToFeePerVSize(chunk_feerate);
     285                 :             : 
     286   [ -  +  +  + ]:       87717 :     while (selected_transactions.size() > 0) {
     287                 :             :         // Check to see if min fee rate is still respected.
     288         [ +  + ]:       46604 :         if (chunk_feerate_vsize << m_options.blockMinFeeRate.GetFeePerVSize()) {
     289                 :             :             // Everything else we might consider has a lower feerate
     290                 :             :             return;
     291                 :             :         }
     292                 :             : 
     293                 :       46558 :         int64_t chunk_sig_ops = 0;
     294         [ +  + ]:       96051 :         for (const auto& tx : selected_transactions) {
     295                 :       49493 :             chunk_sig_ops += tx.get().GetSigOpCost();
     296                 :             :         }
     297                 :             : 
     298                 :             :         // Check to see if this chunk will fit.
     299   [ +  -  +  +  :       46558 :         if (!TestChunkBlockLimits(chunk_feerate, chunk_sig_ops) || !TestChunkTransactions(selected_transactions)) {
             +  -  +  + ]
     300                 :             :             // This chunk won't fit, so we skip it and will try the next best one.
     301                 :       37234 :             m_mempool->SkipBuilderChunk();
     302                 :       37234 :             ++nConsecutiveFailed;
     303                 :             : 
     304         [ +  + ]:       37234 :             if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight +
     305         [ -  + ]:           9 :                     BLOCK_FULL_ENOUGH_WEIGHT_DELTA > m_options.nBlockMaxWeight) {
     306                 :             :                 // Give up if we're close to full and haven't succeeded in a while
     307                 :             :                 return;
     308                 :             :             }
     309                 :             :         } else {
     310                 :        9324 :             m_mempool->IncludeBuilderChunk();
     311                 :             : 
     312                 :             :             // This chunk will fit, so add it to the block.
     313                 :        9324 :             nConsecutiveFailed = 0;
     314         [ +  + ]:       19504 :             for (const auto& tx : selected_transactions) {
     315         [ +  - ]:       10180 :                 AddToBlock(tx);
     316                 :             :             }
     317         [ +  - ]:        9324 :             pblocktemplate->m_package_feerates.emplace_back(chunk_feerate_vsize);
     318                 :             :         }
     319                 :             : 
     320         [ +  - ]:       46549 :         selected_transactions.clear();
     321         [ +  - ]:       46549 :         chunk_feerate = m_mempool->GetBlockBuilderChunk(selected_transactions);
     322                 :       46549 :         chunk_feerate_vsize = ToFeePerVSize(chunk_feerate);
     323                 :             :     }
     324                 :       41168 : }
     325                 :             : 
     326                 :          55 : void AddMerkleRootAndCoinbase(CBlock& block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce)
     327                 :             : {
     328   [ -  +  -  + ]:          55 :     if (block.vtx.size() == 0) {
     329                 :           0 :         block.vtx.emplace_back(coinbase);
     330                 :             :     } else {
     331                 :          55 :         block.vtx[0] = coinbase;
     332                 :             :     }
     333                 :          55 :     block.nVersion = version;
     334                 :          55 :     block.nTime = timestamp;
     335                 :          55 :     block.nNonce = nonce;
     336                 :          55 :     block.hashMerkleRoot = BlockMerkleRoot(block);
     337                 :             : 
     338                 :             :     // Reset cached checks
     339                 :          55 :     block.m_checked_witness_commitment = false;
     340                 :          55 :     block.m_checked_merkle_root = false;
     341                 :          55 :     block.fChecked = false;
     342                 :          55 : }
     343                 :             : 
     344                 :           0 : void InterruptWait(KernelNotifications& kernel_notifications, bool& interrupt_wait)
     345                 :             : {
     346                 :           0 :     LOCK(kernel_notifications.m_tip_block_mutex);
     347                 :           0 :     interrupt_wait = true;
     348         [ #  # ]:           0 :     kernel_notifications.m_tip_block_cv.notify_all();
     349                 :           0 : }
     350                 :             : 
     351                 :          62 : std::unique_ptr<CBlockTemplate> WaitAndCreateNewBlock(ChainstateManager& chainman,
     352                 :             :                                                       KernelNotifications& kernel_notifications,
     353                 :             :                                                       CTxMemPool* mempool,
     354                 :             :                                                       const std::unique_ptr<CBlockTemplate>& block_template,
     355                 :             :                                                       const BlockWaitOptions& options,
     356                 :             :                                                       const BlockAssembler::Options& assemble_options,
     357                 :             :                                                       bool& interrupt_wait)
     358                 :             : {
     359                 :             :     // Delay calculating the current template fees, just in case a new block
     360                 :             :     // comes in before the next tick.
     361                 :          62 :     CAmount current_fees = -1;
     362                 :             : 
     363                 :             :     // Alternate waiting for a new tip and checking if fees have risen.
     364                 :             :     // The latter check is expensive so we only run it once per second.
     365                 :          62 :     auto now{NodeClock::now()};
     366                 :          62 :     const auto deadline = now + options.timeout;
     367                 :          62 :     const MillisecondsDouble tick{1000};
     368                 :          62 :     const bool allow_min_difficulty{chainman.GetParams().GetConsensus().fPowAllowMinDifficultyBlocks};
     369                 :             : 
     370                 :          62 :     do {
     371                 :          62 :         bool tip_changed{false};
     372                 :          62 :         {
     373                 :          62 :             WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
     374                 :             :             // Note that wait_until() checks the predicate before waiting
     375         [ +  - ]:          62 :             kernel_notifications.m_tip_block_cv.wait_until(lock, std::min(now + tick, deadline), [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
     376                 :          69 :                 AssertLockHeld(kernel_notifications.m_tip_block_mutex);
     377                 :          69 :                 const auto tip_block{kernel_notifications.TipBlock()};
     378                 :             :                 // We assume tip_block is set, because this is an instance
     379                 :             :                 // method on BlockTemplate and no template could have been
     380                 :             :                 // generated before a tip exists.
     381   [ +  -  +  + ]:          69 :                 tip_changed = Assume(tip_block) && tip_block != block_template->block.hashPrevBlock;
     382   [ +  +  +  -  :          69 :                 return tip_changed || chainman.m_interrupt || interrupt_wait;
                   -  + ]
     383                 :             :             });
     384         [ -  + ]:          62 :             if (interrupt_wait) {
     385                 :           0 :                 interrupt_wait = false;
     386         [ #  # ]:           0 :                 return nullptr;
     387                 :             :             }
     388                 :           0 :         }
     389                 :             : 
     390         [ -  + ]:          62 :         if (chainman.m_interrupt) return nullptr;
     391                 :             :         // At this point the tip changed, a full tick went by or we reached
     392                 :             :         // the deadline.
     393                 :             : 
     394                 :             :         // Must release m_tip_block_mutex before locking cs_main, to avoid deadlocks.
     395                 :          62 :         LOCK(::cs_main);
     396                 :             : 
     397                 :             :         // On test networks return a minimum difficulty block after 20 minutes
     398   [ +  +  +  + ]:          62 :         if (!tip_changed && allow_min_difficulty) {
     399   [ +  -  -  + ]:           6 :             const NodeClock::time_point tip_time{std::chrono::seconds{chainman.ActiveChain().Tip()->GetBlockTime()}};
     400         [ +  + ]:           3 :             if (now > tip_time + 20min) {
     401                 :           1 :                 tip_changed = true;
     402                 :             :             }
     403                 :             :         }
     404                 :             : 
     405                 :             :         /**
     406                 :             :          * We determine if fees increased compared to the previous template by generating
     407                 :             :          * a fresh template. There may be more efficient ways to determine how much
     408                 :             :          * (approximate) fees for the next block increased, perhaps more so after
     409                 :             :          * Cluster Mempool.
     410                 :             :          *
     411                 :             :          * We'll also create a new template if the tip changed during this iteration.
     412                 :             :          */
     413   [ +  +  +  - ]:          62 :         if (options.fee_threshold < MAX_MONEY || tip_changed) {
     414                 :           0 :             auto new_tmpl{BlockAssembler{
     415                 :             :                 chainman.ActiveChainstate(),
     416                 :             :                 mempool,
     417   [ +  -  +  - ]:          62 :                 assemble_options}
     418         [ +  - ]:          62 :                               .CreateNewBlock()};
     419                 :             : 
     420                 :             :             // If the tip changed, return the new template regardless of its fees.
     421         [ +  + ]:          62 :             if (tip_changed) return new_tmpl;
     422                 :             : 
     423                 :             :             // Calculate the original template total fees if we haven't already
     424         [ +  - ]:           6 :             if (current_fees == -1) {
     425                 :           6 :                 current_fees = std::accumulate(block_template->vTxFees.begin(), block_template->vTxFees.end(), CAmount{0});
     426                 :             :             }
     427                 :             : 
     428                 :             :             // Check if fees increased enough to return the new template
     429                 :           6 :             const CAmount new_fees = std::accumulate(new_tmpl->vTxFees.begin(), new_tmpl->vTxFees.end(), CAmount{0});
     430         [ +  + ]:           6 :             Assume(options.fee_threshold != MAX_MONEY);
     431         [ +  + ]:           6 :             if (new_fees >= current_fees + options.fee_threshold) return new_tmpl;
     432         [ +  - ]:          62 :         }
     433                 :             : 
     434         [ +  - ]:           4 :         now = NodeClock::now();
     435         [ -  + ]:          62 :     } while (now < deadline);
     436                 :             : 
     437                 :           4 :     return nullptr;
     438                 :             : }
     439                 :             : 
     440                 :       42851 : std::optional<BlockRef> GetTip(ChainstateManager& chainman)
     441                 :             : {
     442                 :       42851 :     LOCK(::cs_main);
     443   [ +  -  -  + ]:       42851 :     CBlockIndex* tip{chainman.ActiveChain().Tip()};
     444         [ -  + ]:       42851 :     if (!tip) return {};
     445                 :       42851 :     return BlockRef{tip->GetBlockHash(), tip->nHeight};
     446                 :       42851 : }
     447                 :             : 
     448                 :       40638 : std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const uint256& current_tip, MillisecondsDouble& timeout)
     449                 :             : {
     450                 :       40638 :     Assume(timeout >= 0ms); // No internal callers should use a negative timeout
     451         [ -  + ]:       40638 :     if (timeout < 0ms) timeout = 0ms;
     452         [ +  + ]:       40638 :     if (timeout > std::chrono::years{100}) timeout = std::chrono::years{100}; // Upper bound to avoid UB in std::chrono
     453                 :       40638 :     auto deadline{std::chrono::steady_clock::now() + timeout};
     454                 :       40638 :     {
     455                 :       40638 :         WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
     456                 :             :         // For callers convenience, wait longer than the provided timeout
     457                 :             :         // during startup for the tip to be non-null. That way this function
     458                 :             :         // always returns valid tip information when possible and only
     459                 :             :         // returns null when shutting down, not when timing out.
     460         [ +  - ]:       40638 :         kernel_notifications.m_tip_block_cv.wait(lock, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
     461   [ -  +  -  - ]:       40638 :             return kernel_notifications.TipBlock() || chainman.m_interrupt;
     462                 :             :         });
     463   [ +  -  -  +  :       40638 :         if (chainman.m_interrupt) return {};
                   -  - ]
     464                 :             :         // At this point TipBlock is set, so continue to wait until it is
     465                 :             :         // different then `current_tip` provided by caller.
     466         [ +  - ]:       40638 :         kernel_notifications.m_tip_block_cv.wait_until(lock, deadline, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
     467   [ +  +  +  + ]:       40657 :             return Assume(kernel_notifications.TipBlock()) != current_tip || chainman.m_interrupt;
     468                 :             :         });
     469                 :           0 :     }
     470         [ +  + ]:       40638 :     if (chainman.m_interrupt) return {};
     471                 :             : 
     472                 :             :     // Must release m_tip_block_mutex before getTip() locks cs_main, to
     473                 :             :     // avoid deadlocks.
     474                 :       40636 :     return GetTip(chainman);
     475                 :             : }
     476                 :             : 
     477                 :             : } // namespace node
        

Generated by: LCOV version 2.0-1