LCOV - code coverage report
Current view: top level - src/node - miner.h Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 100.0 % 1 1
Test Date: 2026-06-07 07:36:48 Functions: - 0 0

            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              : #ifndef BITCOIN_NODE_MINER_H
       7              : #define BITCOIN_NODE_MINER_H
       8              : 
       9              : #include <consensus/amount.h>
      10              : #include <node/mining_types.h>
      11              : #include <primitives/block.h>
      12              : #include <primitives/transaction.h>
      13              : #include <threadsafety.h>
      14              : #include <txmempool.h>
      15              : #include <util/feefrac.h>
      16              : #include <util/time.h>
      17              : 
      18              : #include <cstdint>
      19              : #include <memory>
      20              : #include <optional>
      21              : #include <string>
      22              : #include <vector>
      23              : 
      24              : class CBlockIndex;
      25              : class CChainParams;
      26              : class Chainstate;
      27              : class ChainstateManager;
      28              : 
      29              : namespace Consensus {
      30              : struct Params;
      31              : } // namespace Consensus
      32              : class uint256;
      33              : namespace interfaces {
      34              : struct BlockRef;
      35              : } // namespace interfaces
      36              : 
      37              : using interfaces::BlockRef;
      38              : 
      39              : namespace node {
      40              : class KernelNotifications;
      41              : 
      42              : struct CBlockTemplate
      43              : {
      44              :     CBlock block;
      45              :     // Fees per transaction, not including coinbase transaction (unlike CBlock::vtx).
      46              :     std::vector<CAmount> vTxFees;
      47              :     // Sigops per transaction, not including coinbase transaction (unlike CBlock::vtx).
      48              :     std::vector<int64_t> vTxSigOpsCost;
      49              :     /* A vector of package fee rates, ordered by the sequence in which
      50              :      * packages are selected for inclusion in the block template.*/
      51              :     std::vector<FeePerVSize> m_package_feerates;
      52              :     /*
      53              :      * Template containing all coinbase transaction fields that are set by our
      54              :      * miner code.
      55              :      */
      56              :     CoinbaseTx m_coinbase_tx;
      57              : };
      58              : 
      59              : /** Generate a new block, without valid proof-of-work */
      60         8144 : class BlockAssembler
      61              : {
      62              : private:
      63              :     // The constructed block template
      64              :     std::unique_ptr<CBlockTemplate> pblocktemplate;
      65              : 
      66              :     // Information on the current status of the block
      67              :     uint64_t nBlockWeight;
      68              :     uint64_t nBlockTx;
      69              :     uint64_t nBlockSigOpsCost;
      70              :     CAmount nFees;
      71              : 
      72              :     // Chain context for the block
      73              :     int nHeight;
      74              :     int64_t m_lock_time_cutoff;
      75              : 
      76              :     const CChainParams& chainparams;
      77              :     const CTxMemPool* const m_mempool;
      78              :     Chainstate& m_chainstate;
      79              : 
      80              : public:
      81              :     explicit BlockAssembler(Chainstate& chainstate,
      82              :                             const CTxMemPool* mempool,
      83              :                             BlockCreateOptions create_options);
      84              : 
      85              :     /** Construct a new block template */
      86              :     std::unique_ptr<CBlockTemplate> CreateNewBlock();
      87              : 
      88              :     /** The number of transactions in the last assembled block (excluding coinbase transaction) */
      89              :     inline static std::optional<int64_t> m_last_block_num_txs{};
      90              :     /** The weight of the last assembled block (including reserved weight for block header, txs count and coinbase tx) */
      91              :     inline static std::optional<int64_t> m_last_block_weight{};
      92              : 
      93              : private:
      94              :     const BlockCreateOptions m_options;
      95              : 
      96              :     // utility functions
      97              :     /** Clear the block's state and prepare for assembling a new block */
      98              :     void resetBlock();
      99              :     /** Add a tx to the block */
     100              :     void AddToBlock(const CTxMemPoolEntry& entry);
     101              : 
     102              :     // Methods for how to add transactions to a block.
     103              :     /** Add transactions based on chunk feerate
     104              :       *
     105              :       * @pre BlockAssembler::m_mempool must not be nullptr
     106              :     */
     107              :     void addChunks() EXCLUSIVE_LOCKS_REQUIRED(m_mempool->cs);
     108              : 
     109              :     // helper functions for addChunks()
     110              :     /** Test if a new chunk would "fit" in the block */
     111              :     bool TestChunkBlockLimits(FeePerWeight chunk_feerate, int64_t chunk_sigops_cost) const;
     112              :     /** Perform locktime checks on each transaction in a chunk:
     113              :       * This check should always succeed, and is here
     114              :       * only as an extra check in case of a bug */
     115              :     bool TestChunkTransactions(const std::vector<CTxMemPoolEntryRef>& txs) const;
     116              : };
     117              : 
     118              : /**
     119              :  * Get the minimum time a miner should use in the next block. This always
     120              :  * accounts for the BIP94 timewarp rule, so does not necessarily reflect the
     121              :  * consensus limit.
     122              :  */
     123              : int64_t GetMinimumTime(const CBlockIndex* pindexPrev, int64_t difficulty_adjustment_interval);
     124              : 
     125              : int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev);
     126              : 
     127              : /** Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed */
     128              : void RegenerateCommitments(CBlock& block, ChainstateManager& chainman);
     129              : 
     130              : /* Compute the block's merkle root, insert or replace the coinbase transaction and the merkle root into the block */
     131              : void AddMerkleRootAndCoinbase(CBlock& block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce);
     132              : 
     133              : //! Submit a block and capture the validation state via the BlockChecked callback.
     134              : //! Returns whether ProcessNewBlock accepted the block.
     135              : bool SubmitBlock(ChainstateManager& chainman, const std::shared_ptr<const CBlock>& block, bool* new_block, std::string& reason, std::string& debug);
     136              : 
     137              : /* Interrupt a blocking call. */
     138              : void InterruptWait(KernelNotifications& kernel_notifications, bool& interrupt_wait);
     139              : /**
     140              :  * Return a new block template when fees rise to a certain threshold or after a
     141              :  * new tip; return nullopt if timeout is reached.
     142              :  */
     143              : std::unique_ptr<CBlockTemplate> WaitAndCreateNewBlock(ChainstateManager& chainman,
     144              :                                                       KernelNotifications& kernel_notifications,
     145              :                                                       CTxMemPool* mempool,
     146              :                                                       const std::unique_ptr<CBlockTemplate>& block_template,
     147              :                                                       const BlockWaitOptions& wait_options,
     148              :                                                       const BlockCreateOptions& create_options,
     149              :                                                       bool& interrupt_wait);
     150              : 
     151              : /* Locks cs_main and returns the block hash and block height of the active chain if it exists; otherwise, returns nullopt.*/
     152              : std::optional<BlockRef> GetTip(ChainstateManager& chainman);
     153              : 
     154              : /* Waits for the connected tip to change until timeout has elapsed. During node initialization, this will wait until the tip is connected (regardless of `timeout`).
     155              :  * Returns the current tip, or nullopt if the node is shutting down or interrupt()
     156              :  * is called.
     157              :  */
     158              : std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const uint256& current_tip, MillisecondsDouble& timeout, bool& interrupt);
     159              : 
     160              : /**
     161              :  * Wait while the best known header extends the current chain tip AND at least
     162              :  * one block is being added to the tip every 3 seconds. If the tip is
     163              :  * sufficiently far behind, allow up to 20 seconds for the next tip update.
     164              :  *
     165              :  * It’s not safe to keep waiting, because a malicious miner could announce a
     166              :  * header and delay revealing the block, causing all other miners using this
     167              :  * software to stall. At the same time, we need to balance between the default
     168              :  * waiting time being brief, but not ending the cooldown prematurely when a
     169              :  * random block is slow to download (or process).
     170              :  *
     171              :  * The cooldown only applies to createNewBlock(), which is typically called
     172              :  * once per connected client. Subsequent templates are provided by waitNext().
     173              :  *
     174              :  * @param last_tip tip at the start of the cooldown window.
     175              :  * @param interrupt_mining set to true to interrupt the cooldown.
     176              :  *
     177              :  * @returns false if interrupted.
     178              :  */
     179              : bool CooldownIfHeadersAhead(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const BlockRef& last_tip, bool& interrupt_mining);
     180              : } // namespace node
     181              : 
     182              : #endif // BITCOIN_NODE_MINER_H
        

Generated by: LCOV version 2.0-1