LCOV - code coverage report
Current view: top level - src/node - miner.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 61.2 % 286 175
Test Date: 2026-09-21 05:37:55 Functions: 66.7 % 24 16
Branches: 32.9 % 410 135

             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 <common/args.h>
      11                 :             : #include <consensus/amount.h>
      12                 :             : #include <consensus/consensus.h>
      13                 :             : #include <consensus/merkle.h>
      14                 :             : #include <consensus/params.h>
      15                 :             : #include <consensus/tx_verify.h>
      16                 :             : #include <consensus/validation.h>
      17                 :             : #include <interfaces/types.h>
      18                 :             : #include <node/blockstorage.h>
      19                 :             : #include <node/kernel_notifications.h>
      20                 :             : #include <node/mining_args.h>
      21                 :             : #include <node/mining_types.h>
      22                 :             : #include <policy/feerate.h>
      23                 :             : #include <policy/policy.h>
      24                 :             : #include <pow.h>
      25                 :             : #include <primitives/block.h>
      26                 :             : #include <primitives/transaction.h>
      27                 :             : #include <script/script.h>
      28                 :             : #include <sync.h>
      29                 :             : #include <tinyformat.h>
      30                 :             : #include <txgraph.h>
      31                 :             : #include <txmempool.h>
      32                 :             : #include <uint256.h>
      33                 :             : #include <util/check.h>
      34                 :             : #include <util/feefrac.h>
      35                 :             : #include <util/log.h>
      36                 :             : #include <util/result.h>
      37                 :             : #include <util/signalinterrupt.h>
      38                 :             : #include <util/time.h>
      39                 :             : #include <util/translation.h>
      40                 :             : #include <validation.h>
      41                 :             : #include <validationinterface.h>
      42                 :             : #include <versionbits.h>
      43                 :             : 
      44                 :             : #include <algorithm>
      45                 :             : #include <compare>
      46                 :             : #include <condition_variable>
      47                 :             : #include <cstddef>
      48                 :             : #include <functional>
      49                 :             : #include <numeric>
      50                 :             : #include <span>
      51                 :             : #include <stdexcept>
      52                 :             : #include <string>
      53                 :             : #include <utility>
      54                 :             : 
      55                 :             : namespace node {
      56                 :             : 
      57                 :      383571 : int64_t GetMinimumTime(const CBlockIndex* pindexPrev, const int64_t difficulty_adjustment_interval)
      58                 :             : {
      59                 :      383571 :     int64_t min_time{pindexPrev->GetMedianTimePast() + 1};
      60                 :             :     // Height of block to be mined.
      61                 :      383571 :     const int height{pindexPrev->nHeight + 1};
      62                 :             :     // Account for BIP94 timewarp rule on all networks. This makes future
      63                 :             :     // activation safer.
      64         [ +  + ]:      383571 :     if (height % difficulty_adjustment_interval == 0) {
      65         [ +  - ]:        3464 :         min_time = std::max<int64_t>(min_time, pindexPrev->GetBlockTime() - MAX_TIMEWARP);
      66                 :             :     }
      67                 :             :     // Account for the BIP54 Murch-Zawy rule on all networks: the last block of
      68                 :             :     // a difficulty adjustment period may not be earlier than its first block.
      69         [ +  + ]:      383571 :     if (height % difficulty_adjustment_interval == difficulty_adjustment_interval - 1) {
      70                 :        1498 :         const int first_height{height - static_cast<int>(difficulty_adjustment_interval) + 1};
      71         [ -  + ]:        1498 :         const CBlockIndex* first_block{Assert(pindexPrev->GetAncestor(first_height))};
      72         [ +  - ]:        2996 :         min_time = std::max<int64_t>(min_time, first_block->GetBlockTime());
      73                 :             :     }
      74                 :      383571 :     return min_time;
      75                 :             : }
      76                 :             : 
      77                 :      383571 : int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
      78                 :             : {
      79                 :      383571 :     int64_t nOldTime = pblock->nTime;
      80         [ +  + ]:      383571 :     int64_t nNewTime{std::max<int64_t>(GetMinimumTime(pindexPrev, consensusParams.DifficultyAdjustmentInterval()),
      81                 :      383571 :                                        TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()))};
      82                 :             : 
      83         [ +  + ]:      383571 :     if (nOldTime < nNewTime) {
      84                 :      267027 :         pblock->nTime = nNewTime;
      85                 :             :     }
      86                 :             : 
      87                 :             :     // Updating time can change work required on testnet:
      88         [ +  - ]:      383571 :     if (consensusParams.fPowAllowMinDifficultyBlocks) {
      89                 :      383571 :         pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
      90                 :             :     }
      91                 :             : 
      92                 :      383571 :     return nNewTime - nOldTime;
      93                 :             : }
      94                 :             : 
      95                 :      124916 : void RegenerateCommitments(CBlock& block, ChainstateManager& chainman)
      96                 :             : {
      97                 :      124916 :     CMutableTransaction tx{*block.vtx.at(0)};
      98                 :      124916 :     tx.vout.erase(tx.vout.begin() + GetWitnessCommitmentIndex(block));
      99   [ +  -  +  -  :      249832 :     block.vtx.at(0) = MakeTransactionRef(tx);
                   -  + ]
     100                 :             : 
     101   [ +  -  +  -  :      374748 :     const CBlockIndex* prev_block = WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock));
                   +  - ]
     102         [ +  - ]:      124916 :     chainman.GenerateCoinbaseCommitment(block, prev_block);
     103                 :             : 
     104         [ +  - ]:      124916 :     block.hashMerkleRoot = BlockMerkleRoot(block);
     105                 :      124916 : }
     106                 :             : 
     107                 :      383569 : BlockAssembler::BlockAssembler(Chainstate& chainstate,
     108                 :             :                                const CTxMemPool* mempool,
     109                 :      383569 :                                BlockCreateOptions options)
     110         [ -  + ]:      383569 :     : chainparams{chainstate.m_chainman.GetParams()},
     111         [ -  + ]:      383569 :       m_mempool{options.use_mempool ? mempool : nullptr},
     112                 :      383569 :       m_chainstate{chainstate},
     113         [ +  - ]:      383569 :       m_options{[&] {
     114   [ +  -  -  + ]:      767138 :           if (auto result{CheckMiningOptions(options, /*use_argnames=*/false)}; !result) {
     115   [ #  #  #  # ]:           0 :               throw std::runtime_error(util::ErrorString(result).original);
     116                 :           0 :           }
     117         [ +  - ]:      767138 :           return FlattenMiningOptions(std::move(options));
     118         [ -  + ]:      383569 :       }()}
     119                 :             : {
     120                 :      383569 : }
     121                 :             : 
     122                 :      383569 : void BlockAssembler::resetBlock()
     123                 :             : {
     124                 :             :     // Reserve space for fixed-size block header, txs count, and coinbase tx.
     125         [ -  + ]:      383569 :     nBlockWeight = *Assert(m_options.block_reserved_weight);
     126                 :      383569 :     nBlockSigOpsCost = m_options.coinbase_output_max_additional_sigops;
     127                 :             : 
     128                 :             :     // These counters do not include coinbase tx
     129                 :      383569 :     nBlockTx = 0;
     130                 :      383569 :     nFees = 0;
     131                 :      383569 : }
     132                 :             : 
     133                 :      383569 : std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock()
     134                 :             : {
     135                 :      383569 :     const auto time_start{SteadyClock::now()};
     136                 :             : 
     137                 :      383569 :     resetBlock();
     138                 :             : 
     139         [ -  + ]:      383569 :     pblocktemplate.reset(new CBlockTemplate());
     140                 :      383569 :     CBlock* const pblock = &pblocktemplate->block; // pointer for convenience
     141                 :             : 
     142                 :             :     // Add dummy coinbase tx as first transaction. It is skipped by the
     143                 :             :     // getblocktemplate RPC and mining interface consumers must not use it.
     144                 :      383569 :     pblock->vtx.emplace_back();
     145                 :             : 
     146                 :      383569 :     LOCK(::cs_main);
     147         [ -  + ]:      383569 :     CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip();
     148         [ -  + ]:      383569 :     assert(pindexPrev != nullptr);
     149                 :      383569 :     nHeight = pindexPrev->nHeight + 1;
     150                 :             : 
     151         [ +  - ]:      383569 :     pblock->nVersion = m_chainstate.m_chainman.m_versionbitscache.ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
     152                 :             :     // -regtest only: allow overriding block.nVersion with
     153                 :             :     // -blockversion=N to test forking scenarios
     154         [ +  - ]:      383569 :     if (chainparams.MineBlocksOnDemand()) {
     155         [ +  - ]:      767138 :         pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion);
     156                 :             :     }
     157                 :             : 
     158                 :      383569 :     pblock->nTime = TicksSinceEpoch<std::chrono::seconds>(NodeClock::now());
     159                 :      383569 :     m_lock_time_cutoff = pindexPrev->GetMedianTimePast();
     160                 :             : 
     161         [ +  - ]:      383569 :     if (m_mempool) {
     162         [ +  - ]:      383569 :         LOCK(m_mempool->cs);
     163                 :      383569 :         m_mempool->StartBlockBuilding();
     164         [ +  - ]:      383569 :         addChunks();
     165         [ +  - ]:      383569 :         m_mempool->StopBlockBuilding();
     166                 :      383569 :     }
     167                 :             : 
     168                 :      383569 :     const auto time_1{SteadyClock::now()};
     169                 :             : 
     170         [ +  + ]:      383569 :     m_last_block_num_txs = nBlockTx;
     171         [ +  + ]:      383569 :     m_last_block_weight = nBlockWeight;
     172                 :             : 
     173                 :             :     // Create coinbase transaction.
     174         [ +  - ]:      383569 :     CMutableTransaction coinbaseTx;
     175                 :             : 
     176                 :             :     // Construct coinbase transaction struct in parallel
     177         [ +  - ]:      383569 :     CoinbaseTx& coinbase_tx{pblocktemplate->m_coinbase_tx};
     178                 :      383569 :     coinbase_tx.version = coinbaseTx.version;
     179                 :             : 
     180         [ +  - ]:      383569 :     coinbaseTx.vin.resize(1);
     181                 :      383569 :     coinbaseTx.vin[0].prevout.SetNull();
     182         [ +  - ]:      383569 :     coinbaseTx.vin[0].nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; // Make sure timelock is enforced.
     183                 :      383569 :     coinbase_tx.sequence = coinbaseTx.vin[0].nSequence;
     184                 :             : 
     185                 :             :     // Add an output that spends the full coinbase reward.
     186         [ +  - ]:      383569 :     coinbaseTx.vout.resize(1);
     187                 :      383569 :     coinbaseTx.vout[0].scriptPubKey = m_options.coinbase_output_script;
     188                 :             :     // Block subsidy + fees
     189         [ +  - ]:      383569 :     const CAmount block_reward{nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus())};
     190         [ +  - ]:      383569 :     coinbaseTx.vout[0].nValue = block_reward;
     191                 :      383569 :     coinbase_tx.block_reward_remaining = block_reward;
     192                 :             : 
     193                 :             :     // Start the coinbase scriptSig with the block height as required by BIP34.
     194                 :             :     // Mining clients are expected to append extra data to this prefix, so
     195                 :             :     // increasing its length would reduce the space they can use and may break
     196                 :             :     // existing clients.
     197         [ +  - ]:      383569 :     coinbaseTx.vin[0].scriptSig = CScript() << nHeight;
     198                 :             :     // Set script_sig_prefix here, so IPC mining clients are not affected by
     199                 :             :     // the optional scriptSig padding below. They provide their own extraNonce,
     200                 :             :     // and in a typical setup a pool name or realistic extraNonce already makes
     201                 :             :     // the scriptSig long enough.
     202                 :      383569 :     coinbase_tx.script_sig_prefix = coinbaseTx.vin[0].scriptSig;
     203         [ +  + ]:      383569 :     if (nHeight <= 16) {
     204                 :             :         // For blocks at heights <= 16, the BIP34-encoded height alone is only
     205                 :             :         // one byte. Consensus requires coinbase scriptSigs to be at least two
     206                 :             :         // bytes long (bad-cb-length), so an OP_0 is always appended at those
     207                 :             :         // heights.
     208         [ +  - ]:       56007 :         coinbaseTx.vin[0].scriptSig << OP_0;
     209                 :             :     }
     210         [ -  + ]:      383569 :     Assert(nHeight > 0);
     211                 :      383569 :     coinbaseTx.nLockTime = static_cast<uint32_t>(nHeight - 1);
     212                 :      383569 :     coinbase_tx.lock_time = coinbaseTx.nLockTime;
     213                 :             : 
     214   [ +  -  -  + ]:      767138 :     pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
     215         [ +  - ]:      383569 :     m_chainstate.m_chainman.GenerateCoinbaseCommitment(*pblock, pindexPrev);
     216                 :             : 
     217         [ +  - ]:      383569 :     const CTransactionRef& final_coinbase{pblock->vtx[0]};
     218         [ +  - ]:      383569 :     if (final_coinbase->HasWitness()) {
     219         [ -  + ]:      383569 :         const auto& witness_stack{final_coinbase->vin[0].scriptWitness.stack};
     220                 :             :         // Consensus requires the coinbase witness stack to have exactly one
     221                 :             :         // element of 32 bytes.
     222   [ -  +  +  -  :      383569 :         Assert(witness_stack.size() == 1 && witness_stack[0].size() == 32);
          -  +  -  +  -  
                      + ]
     223   [ -  +  -  + ]:      383569 :         coinbase_tx.witness = uint256(witness_stack[0]);
     224                 :             :     }
     225         [ +  - ]:      383569 :     if (const int witness_index = GetWitnessCommitmentIndex(*pblock); witness_index != NO_WITNESS_COMMITMENT) {
     226   [ +  -  -  +  :      383569 :         Assert(witness_index >= 0 && static_cast<size_t>(witness_index) < final_coinbase->vout.size());
             -  +  -  + ]
     227         [ +  - ]:      383569 :         coinbase_tx.required_outputs.push_back(final_coinbase->vout[witness_index]);
     228                 :             :     }
     229                 :             : 
     230         [ +  - ]:      383569 :     LogInfo("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
     231                 :             : 
     232                 :             :     // Fill in header
     233                 :      383569 :     pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
     234         [ +  - ]:      383569 :     UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
     235         [ +  - ]:      383569 :     pblock->nBits          = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
     236                 :      383569 :     pblock->nNonce         = 0;
     237                 :             : 
     238         [ +  - ]:      383569 :     if (m_options.test_block_validity) {
     239   [ +  -  -  + ]:      383569 :         if (BlockValidationState state{TestBlockValidity(m_chainstate, *pblock, /*check_pow=*/false, /*check_merkle_root=*/false)}; !state.IsValid()) {
     240   [ #  #  #  #  :           0 :             throw std::runtime_error(strprintf("TestBlockValidity failed: %s", state.ToString()));
                   #  # ]
     241                 :      383569 :         }
     242                 :             :     }
     243                 :      383569 :     const auto time_2{SteadyClock::now()};
     244                 :             : 
     245   [ +  -  +  +  :      383569 :     LogDebug(BCLog::BENCH, "CreateNewBlock() chunks: %.2fms, validity: %.2fms (total %.2fms)\n",
                   +  - ]
     246                 :             :              Ticks<MillisecondsDouble>(time_1 - time_start),
     247                 :             :              Ticks<MillisecondsDouble>(time_2 - time_1),
     248                 :             :              Ticks<MillisecondsDouble>(time_2 - time_start));
     249                 :             : 
     250                 :      383569 :     return std::move(pblocktemplate);
     251         [ +  - ]:      767138 : }
     252                 :             : 
     253                 :       61443 : bool BlockAssembler::TestChunkBlockLimits(int64_t chunk_weight, int64_t chunk_sigops_cost) const
     254                 :             : {
     255                 :             :     // block_max_weight has been flattened before block assembly limit checks.
     256         [ -  + ]:       61443 :     Assert(m_options.block_max_weight);
     257         [ +  + ]:       61443 :     if (nBlockWeight + chunk_weight >= m_options.block_max_weight) {
     258                 :             :         return false;
     259                 :             :     }
     260         [ -  + ]:       45727 :     if (nBlockSigOpsCost + chunk_sigops_cost >= MAX_BLOCK_SIGOPS_COST) {
     261                 :           0 :         return false;
     262                 :             :     }
     263                 :             :     return true;
     264                 :             : }
     265                 :             : 
     266                 :             : // Perform transaction-level checks before adding to block:
     267                 :             : // - transaction finality (locktime)
     268                 :       45727 : bool BlockAssembler::TestChunkTransactions(const std::vector<CTxMemPoolEntryRef>& txs) const
     269                 :             : {
     270         [ +  + ]:       97229 :     for (const auto tx : txs) {
     271         [ +  - ]:       51502 :         if (!IsFinalTx(tx.get().GetTx(), nHeight, m_lock_time_cutoff)) {
     272                 :             :             return false;
     273                 :             :         }
     274                 :             :     }
     275                 :             :     return true;
     276                 :             : }
     277                 :             : 
     278                 :       51502 : void BlockAssembler::AddToBlock(const CTxMemPoolEntry& entry)
     279                 :             : {
     280   [ +  -  +  - ]:      103004 :     pblocktemplate->block.vtx.emplace_back(entry.GetSharedTx());
     281                 :       51502 :     pblocktemplate->vTxFees.push_back(entry.GetFee());
     282                 :       51502 :     pblocktemplate->vTxSigOpsCost.push_back(entry.GetSigOpCost());
     283         [ -  + ]:       51502 :     nBlockWeight += entry.GetTxWeight();
     284                 :       51502 :     ++nBlockTx;
     285         [ -  + ]:       51502 :     nBlockSigOpsCost += entry.GetSigOpCost();
     286                 :       51502 :     nFees += entry.GetFee();
     287                 :             : 
     288         [ -  + ]:       51502 :     if (*m_options.print_modified_fee) {
     289   [ #  #  #  #  :           0 :         LogInfo("fee rate %s txid %s\n",
             #  #  #  # ]
     290                 :             :                   CFeeRate(entry.GetModifiedFee(), entry.GetTxSize()).ToString(),
     291                 :             :                   entry.GetTx().GetHash().ToString());
     292                 :             :     }
     293                 :       51502 : }
     294                 :             : 
     295                 :      383569 : void BlockAssembler::addChunks()
     296                 :             : {
     297                 :             :     // Limit the number of attempts to add transactions to the block when it is
     298                 :             :     // close to full; this is just a simple heuristic to finish quickly if the
     299                 :             :     // mempool has a lot of entries.
     300                 :      383569 :     const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
     301                 :      383569 :     constexpr int32_t BLOCK_FULL_ENOUGH_WEIGHT_DELTA = 4000;
     302                 :      383569 :     int64_t nConsecutiveFailed = 0;
     303                 :             : 
     304                 :      383569 :     std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> selected_transactions;
     305         [ +  - ]:      383569 :     selected_transactions.reserve(MAX_CLUSTER_COUNT_LIMIT);
     306                 :      383569 :     FeePerWeight chunk_feerate;
     307                 :             : 
     308                 :             :     // This fills selected_transactions
     309         [ +  - ]:      383569 :     chunk_feerate = m_mempool->GetBlockBuilderChunk(selected_transactions);
     310                 :      383569 :     FeePerVSize chunk_feerate_vsize = ToFeePerVSize(chunk_feerate);
     311                 :             : 
     312   [ -  +  +  + ]:      445012 :     while (selected_transactions.size() > 0) {
     313                 :             :         // Check to see if min fee rate is still respected.
     314         [ +  + ]:       63050 :         if (ByRatio{chunk_feerate_vsize} < ByRatio{m_options.block_min_fee_rate->GetFeePerVSize()}) {
     315                 :             :             // Everything else we might consider has a lower feerate
     316                 :             :             return;
     317                 :             :         }
     318                 :             : 
     319                 :       61443 :         int64_t chunk_sig_ops = 0;
     320                 :       61443 :         int64_t chunk_weight = 0;
     321         [ +  + ]:      130563 :         for (const auto& tx : selected_transactions) {
     322                 :       69120 :             chunk_sig_ops += tx.get().GetSigOpCost();
     323                 :       69120 :             chunk_weight += tx.get().GetTxWeight();
     324                 :             :         }
     325                 :             : 
     326                 :             :         // Check to see if this chunk will fit.
     327   [ +  -  +  +  :       61443 :         if (!TestChunkBlockLimits(chunk_weight, chunk_sig_ops) || !TestChunkTransactions(selected_transactions)) {
             +  -  -  + ]
     328                 :             :             // This chunk won't fit, so we skip it and will try the next best one.
     329                 :       15716 :             m_mempool->SkipBuilderChunk();
     330                 :       15716 :             ++nConsecutiveFailed;
     331                 :             : 
     332                 :             :             // block_max_weight has been flattened before block assembly limit checks.
     333         [ -  + ]:       15716 :             Assert(m_options.block_max_weight);
     334         [ -  + ]:       15716 :             if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight +
     335         [ #  # ]:           0 :                     BLOCK_FULL_ENOUGH_WEIGHT_DELTA > *m_options.block_max_weight) {
     336                 :             :                 // Give up if we're close to full and haven't succeeded in a while
     337                 :             :                 return;
     338                 :             :             }
     339                 :             :         } else {
     340                 :       45727 :             m_mempool->IncludeBuilderChunk();
     341                 :             : 
     342                 :             :             // This chunk will fit, so add it to the block.
     343                 :       45727 :             nConsecutiveFailed = 0;
     344         [ +  + ]:       97229 :             for (const auto& tx : selected_transactions) {
     345         [ +  - ]:       51502 :                 AddToBlock(tx);
     346                 :             :             }
     347         [ +  - ]:       45727 :             pblocktemplate->m_package_feerates.emplace_back(chunk_feerate_vsize);
     348                 :             :         }
     349                 :             : 
     350         [ +  - ]:       61443 :         selected_transactions.clear();
     351         [ +  - ]:       61443 :         chunk_feerate = m_mempool->GetBlockBuilderChunk(selected_transactions);
     352                 :       61443 :         chunk_feerate_vsize = ToFeePerVSize(chunk_feerate);
     353                 :             :     }
     354                 :      383569 : }
     355                 :             : 
     356                 :           0 : void AddMerkleRootAndCoinbase(CBlock& block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce)
     357                 :             : {
     358   [ #  #  #  # ]:           0 :     if (block.vtx.size() == 0) {
     359                 :           0 :         block.vtx.emplace_back(coinbase);
     360                 :             :     } else {
     361                 :           0 :         block.vtx[0] = coinbase;
     362                 :             :     }
     363                 :           0 :     block.nVersion = version;
     364                 :           0 :     block.nTime = timestamp;
     365                 :           0 :     block.nNonce = nonce;
     366                 :           0 :     block.hashMerkleRoot = BlockMerkleRoot(block);
     367                 :             : 
     368                 :             :     // Reset cached checks
     369                 :           0 :     block.m_checked_witness_commitment = false;
     370                 :           0 :     block.m_checked_merkle_root = false;
     371                 :           0 :     block.fChecked = false;
     372                 :           0 : }
     373                 :             : 
     374                 :             : namespace {
     375                 :             : class SubmitBlockStateCatcher final : public CValidationInterface
     376                 :             : {
     377                 :             : public:
     378                 :             :     uint256 m_hash;
     379                 :             :     bool m_found{false};
     380                 :             :     BlockValidationState m_state;
     381                 :             : 
     382                 :           0 :     explicit SubmitBlockStateCatcher(const uint256& hash) : m_hash{hash} {}
     383                 :             : 
     384                 :             : protected:
     385                 :           0 :     void BlockChecked(const std::shared_ptr<const CBlock>& block, const BlockValidationState& state) override
     386                 :             :     {
     387         [ #  # ]:           0 :         if (block->GetHash() != m_hash) return;
     388                 :             :         // ProcessNewBlock emits BlockChecked synchronously while holding cs_main,
     389                 :             :         // so SubmitBlock can read these fields after ProcessNewBlock returns
     390                 :             :         // without extra synchronization.
     391                 :           0 :         m_found = true;
     392                 :           0 :         m_state = state;
     393                 :             :     }
     394                 :             : };
     395                 :             : } // namespace
     396                 :             : 
     397                 :           0 : bool SubmitBlock(ChainstateManager& chainman, const std::shared_ptr<const CBlock>& block, std::string& reason, std::string& debug)
     398                 :             : {
     399                 :           0 :     reason.clear();
     400                 :           0 :     debug.clear();
     401                 :             : 
     402                 :             :     // This follows the submitblock RPC's validation-state capture pattern, but
     403                 :             :     // is intentionally kept separate from the RPC implementation. The RPC entry
     404                 :             :     // point decodes hex, formats BIP22/JSONRPC results, and calls
     405                 :             :     // UpdateUncommittedBlockStructures() for legacy witness handling. IPC
     406                 :             :     // callers submit already-formed blocks and need bool + reason/debug
     407                 :             :     // results.
     408                 :           0 :     auto sc = std::make_shared<SubmitBlockStateCatcher>(block->GetHash());
     409   [ #  #  #  #  :           0 :     CHECK_NONFATAL(chainman.m_options.signals)->RegisterSharedValidationInterface(sc);
                   #  # ]
     410                 :           0 :     bool new_block;
     411         [ #  # ]:           0 :     bool accepted = chainman.ProcessNewBlock(block, /*force_processing=*/true, /*min_pow_checked=*/true, /*new_block=*/&new_block);
     412                 :             :     // No queue drain is needed. The BlockChecked notification used above is
     413                 :             :     // emitted synchronously by ProcessNewBlock, unlike most validation signals.
     414   [ #  #  #  #  :           0 :     CHECK_NONFATAL(chainman.m_options.signals)->UnregisterSharedValidationInterface(sc);
                   #  # ]
     415                 :             : 
     416   [ #  #  #  # ]:           0 :     if (!new_block && accepted) {
     417         [ #  # ]:           0 :         reason = "duplicate";
     418   [ #  #  #  #  :           0 :     } else if (!accepted && (!sc->m_found || sc->m_state.IsValid())) {
                   #  # ]
     419                 :             :         // ProcessNewBlock can fail without a validation result, for example
     420                 :             :         // from an activation or system error. It can also fail after a valid
     421                 :             :         // BlockChecked result. In these cases the validation result is
     422                 :             :         // inconclusive.
     423         [ #  # ]:           0 :         reason = "inconclusive";
     424         [ #  # ]:           0 :     } else if (!sc->m_found) {
     425                 :             :         // The block was accepted but not connected, for example if it does not
     426                 :             :         // have more work than the current tip.
     427         [ #  # ]:           0 :         reason = "inconclusive";
     428         [ #  # ]:           0 :     } else if (!sc->m_state.IsValid()) {
     429         [ #  # ]:           0 :         reason = sc->m_state.GetRejectReason();
     430         [ #  # ]:           0 :         debug = sc->m_state.GetDebugMessage();
     431                 :             :     }
     432   [ #  #  #  #  :           0 :     const bool result{accepted && new_block && reason.empty()};
                   #  # ]
     433         [ #  # ]:           0 :     CHECK_NONFATAL(result == reason.empty());
     434         [ #  # ]:           0 :     return result;
     435                 :           0 : }
     436                 :             : 
     437                 :           0 : void InterruptWait(KernelNotifications& kernel_notifications, bool& interrupt_wait)
     438                 :             : {
     439                 :           0 :     LOCK(kernel_notifications.m_tip_block_mutex);
     440                 :           0 :     interrupt_wait = true;
     441         [ #  # ]:           0 :     kernel_notifications.m_tip_block_cv.notify_all();
     442                 :           0 : }
     443                 :             : 
     444                 :           0 : std::unique_ptr<CBlockTemplate> WaitAndCreateNewBlock(ChainstateManager& chainman,
     445                 :             :                                                       KernelNotifications& kernel_notifications,
     446                 :             :                                                       CTxMemPool* mempool,
     447                 :             :                                                       const std::unique_ptr<CBlockTemplate>& block_template,
     448                 :             :                                                       const BlockWaitOptions& wait_options,
     449                 :             :                                                       const BlockCreateOptions& create_options,
     450                 :             :                                                       bool& interrupt_wait)
     451                 :             : {
     452                 :             :     // Delay calculating the current template fees, just in case a new block
     453                 :             :     // comes in before the next tick.
     454                 :           0 :     CAmount current_fees = -1;
     455                 :             : 
     456                 :             :     // Alternate waiting for a new tip and checking if fees have risen.
     457                 :             :     // The latter check is expensive so we only run it once per second.
     458                 :           0 :     auto now{NodeClock::now()};
     459                 :           0 :     const auto deadline = now + wait_options.timeout;
     460                 :           0 :     const MillisecondsDouble tick{1000};
     461                 :           0 :     const bool allow_min_difficulty{chainman.GetParams().GetConsensus().fPowAllowMinDifficultyBlocks};
     462                 :             : 
     463                 :           0 :     do {
     464                 :           0 :         bool tip_changed{false};
     465                 :           0 :         {
     466                 :           0 :             WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
     467                 :             :             // Note that wait_until() checks the predicate before waiting
     468         [ #  # ]:           0 :             kernel_notifications.m_tip_block_cv.wait_until(lock, std::min(now + tick, deadline), [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
     469                 :           0 :                 AssertLockHeld(kernel_notifications.m_tip_block_mutex);
     470                 :           0 :                 const auto tip_block{kernel_notifications.TipBlock()};
     471                 :             :                 // We assume tip_block is set, because this is an instance
     472                 :             :                 // method on BlockTemplate and no template could have been
     473                 :             :                 // generated before a tip exists.
     474   [ #  #  #  # ]:           0 :                 tip_changed = Assume(tip_block) && tip_block != block_template->block.hashPrevBlock;
     475   [ #  #  #  #  :           0 :                 return tip_changed || chainman.m_interrupt || interrupt_wait;
                   #  # ]
     476                 :             :             });
     477         [ #  # ]:           0 :             if (interrupt_wait) {
     478                 :           0 :                 interrupt_wait = false;
     479         [ #  # ]:           0 :                 return nullptr;
     480                 :             :             }
     481                 :           0 :         }
     482                 :             : 
     483         [ #  # ]:           0 :         if (chainman.m_interrupt) return nullptr;
     484                 :             :         // At this point the tip changed, a full tick went by or we reached
     485                 :             :         // the deadline.
     486                 :             : 
     487                 :             :         // Must release m_tip_block_mutex before locking cs_main, to avoid deadlocks.
     488                 :           0 :         LOCK(::cs_main);
     489                 :             : 
     490                 :             :         // On test networks return a minimum difficulty block after 20 minutes
     491   [ #  #  #  # ]:           0 :         if (!tip_changed && allow_min_difficulty) {
     492   [ #  #  #  # ]:           0 :             const NodeClock::time_point tip_time{std::chrono::seconds{chainman.ActiveChain().Tip()->GetBlockTime()}};
     493         [ #  # ]:           0 :             if (now > tip_time + 20min) {
     494                 :           0 :                 tip_changed = true;
     495                 :             :             }
     496                 :             :         }
     497                 :             : 
     498                 :             :         /**
     499                 :             :          * We determine if fees increased compared to the previous template by generating
     500                 :             :          * a fresh template. There may be more efficient ways to determine how much
     501                 :             :          * (approximate) fees for the next block increased, perhaps more so after
     502                 :             :          * Cluster Mempool.
     503                 :             :          *
     504                 :             :          * We'll also create a new template if the tip changed during this iteration.
     505                 :             :          */
     506   [ #  #  #  # ]:           0 :         if (wait_options.fee_threshold < MAX_MONEY || tip_changed) {
     507                 :           0 :             auto new_tmpl{BlockAssembler{
     508                 :             :                 chainman.ActiveChainstate(),
     509                 :             :                 mempool,
     510                 :             :                 create_options
     511   [ #  #  #  #  :           0 :                 }.CreateNewBlock()};
                   #  # ]
     512                 :             : 
     513                 :             :             // If the tip changed, return the new template regardless of its fees.
     514         [ #  # ]:           0 :             if (tip_changed) return new_tmpl;
     515                 :             : 
     516                 :             :             // Calculate the original template total fees if we haven't already
     517         [ #  # ]:           0 :             if (current_fees == -1) {
     518                 :           0 :                 current_fees = std::accumulate(block_template->vTxFees.begin(), block_template->vTxFees.end(), CAmount{0});
     519                 :             :             }
     520                 :             : 
     521                 :             :             // Check if fees increased enough to return the new template
     522                 :           0 :             const CAmount new_fees = std::accumulate(new_tmpl->vTxFees.begin(), new_tmpl->vTxFees.end(), CAmount{0});
     523         [ #  # ]:           0 :             Assume(wait_options.fee_threshold != MAX_MONEY);
     524         [ #  # ]:           0 :             if (new_fees >= current_fees + wait_options.fee_threshold) return new_tmpl;
     525         [ #  # ]:           0 :         }
     526                 :             : 
     527         [ #  # ]:           0 :         now = NodeClock::now();
     528         [ #  # ]:           0 :     } while (now < deadline);
     529                 :             : 
     530                 :           0 :     return nullptr;
     531                 :             : }
     532                 :             : 
     533                 :      376645 : std::optional<BlockRef> GetTip(ChainstateManager& chainman)
     534                 :             : {
     535                 :      376645 :     LOCK(::cs_main);
     536   [ +  -  -  + ]:      376645 :     CBlockIndex* tip{chainman.ActiveChain().Tip()};
     537         [ -  + ]:      376645 :     if (!tip) return {};
     538                 :      376645 :     return BlockRef{tip->GetBlockHash(), tip->nHeight};
     539                 :      376645 : }
     540                 :             : 
     541                 :           0 : bool CooldownIfHeadersAhead(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const BlockRef& last_tip, bool& interrupt_mining)
     542                 :             : {
     543                 :           0 :     uint256 last_tip_hash{last_tip.hash};
     544                 :             : 
     545         [ #  # ]:           0 :     while (const std::optional<int> remaining = chainman.BlocksAheadOfTip()) {
     546         [ #  # ]:           0 :         const int cooldown_seconds = std::clamp(*remaining, 3, 20);
     547                 :           0 :         const auto cooldown_deadline{MockableSteadyClock::now() + std::chrono::seconds{cooldown_seconds}};
     548                 :             : 
     549                 :           0 :         {
     550                 :           0 :             WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
     551         [ #  # ]:           0 :             kernel_notifications.m_tip_block_cv.wait_until(lock, cooldown_deadline, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
     552                 :           0 :                 const auto tip_block = kernel_notifications.TipBlock();
     553   [ #  #  #  #  :           0 :                 return chainman.m_interrupt || interrupt_mining || (tip_block && *tip_block != last_tip_hash);
             #  #  #  # ]
     554                 :             :             });
     555   [ #  #  #  #  :           0 :             if (chainman.m_interrupt || interrupt_mining) {
                   #  # ]
     556                 :           0 :                 interrupt_mining = false;
     557         [ #  # ]:           0 :                 return false;
     558                 :             :             }
     559                 :             : 
     560                 :             :             // If the tip changed during the wait, extend the deadline
     561         [ #  # ]:           0 :             const auto tip_block = kernel_notifications.TipBlock();
     562   [ #  #  #  # ]:           0 :             if (tip_block && *tip_block != last_tip_hash) {
     563         [ #  # ]:           0 :                 last_tip_hash = *tip_block;
     564         [ #  # ]:           0 :                 continue;
     565                 :             :             }
     566                 :           0 :         }
     567                 :             : 
     568                 :             :         // No tip change and the cooldown window has expired.
     569         [ #  # ]:           0 :         if (MockableSteadyClock::now() >= cooldown_deadline) break;
     570                 :             :     }
     571                 :             : 
     572                 :             :     return true;
     573                 :             : }
     574                 :             : 
     575                 :      376645 : std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const uint256& current_tip, MillisecondsDouble& timeout, bool& interrupt)
     576                 :             : {
     577         [ -  + ]:      376645 :     Assume(timeout >= 0ms); // No internal callers should use a negative timeout
     578         [ -  + ]:      376645 :     if (timeout < 0ms) timeout = 0ms;
     579         [ +  - ]:      376645 :     if (timeout > std::chrono::years{100}) timeout = std::chrono::years{100}; // Upper bound to avoid UB in std::chrono
     580                 :      376645 :     auto deadline{std::chrono::steady_clock::now() + timeout};
     581                 :      376645 :     {
     582                 :      376645 :         WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
     583                 :             :         // For callers convenience, wait longer than the provided timeout
     584                 :             :         // during startup for the tip to be non-null. That way this function
     585                 :             :         // always returns valid tip information when possible and only
     586                 :             :         // returns null when shutting down, not when timing out.
     587         [ +  - ]:      376645 :         kernel_notifications.m_tip_block_cv.wait(lock, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
     588   [ -  +  -  -  :      376645 :             return kernel_notifications.TipBlock() || chainman.m_interrupt || interrupt;
                   -  - ]
     589                 :             :         });
     590   [ +  -  +  -  :      376645 :         if (chainman.m_interrupt || interrupt) {
                   +  - ]
     591                 :           0 :             interrupt = false;
     592                 :           0 :             return {};
     593                 :             :         }
     594                 :             :         // At this point TipBlock is set, so continue to wait until it is
     595                 :             :         // different then `current_tip` provided by caller.
     596         [ +  - ]:      376645 :         kernel_notifications.m_tip_block_cv.wait_until(lock, deadline, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
     597   [ -  +  -  +  :      376645 :             return Assume(kernel_notifications.TipBlock()) != current_tip || chainman.m_interrupt || interrupt;
             -  -  -  - ]
     598                 :             :         });
     599   [ +  -  +  -  :      376645 :         if (chainman.m_interrupt || interrupt) {
                   +  - ]
     600                 :           0 :             interrupt = false;
     601                 :           0 :             return {};
     602                 :             :         }
     603                 :           0 :     }
     604                 :             : 
     605                 :             :     // Must release m_tip_block_mutex before getTip() locks cs_main, to
     606                 :             :     // avoid deadlocks.
     607                 :      376645 :     return GetTip(chainman);
     608                 :             : }
     609                 :             : 
     610                 :             : } // namespace node
        

Generated by: LCOV version 2.5.0-full