LCOV - code coverage report
Current view: top level - src/node - miner.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 94.9 % 237 225
Test Date: 2026-02-04 05:05:50 Functions: 95.2 % 21 20
Branches: 62.5 % 312 195

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

Generated by: LCOV version 2.0-1