Bitcoin Core  31.0.0
P2P Digital Currency
miner.h
Go to the documentation of this file.
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 <interfaces/types.h>
10 #include <node/types.h>
11 #include <policy/policy.h>
12 #include <primitives/block.h>
13 #include <txmempool.h>
14 #include <util/feefrac.h>
15 
16 #include <cstdint>
17 #include <memory>
18 #include <optional>
19 
20 #include <boost/multi_index/identity.hpp>
21 #include <boost/multi_index/indexed_by.hpp>
22 #include <boost/multi_index/ordered_index.hpp>
23 #include <boost/multi_index/tag.hpp>
24 #include <boost/multi_index_container.hpp>
25 
26 class ArgsManager;
27 class CBlockIndex;
28 class CChainParams;
29 class CScript;
30 class Chainstate;
31 class ChainstateManager;
32 
33 namespace Consensus { struct Params; };
34 
36 
37 namespace node {
38 class KernelNotifications;
39 
40 static const bool DEFAULT_PRINT_MODIFIED_FEE = false;
41 
43 {
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  */
57 };
58 
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;
71 
72  // Chain context for the block
73  int nHeight;
75 
77  const CTxMemPool* const m_mempool;
79 
80 public:
82  // Configuration parameters for the block size
85  // Whether to call TestBlockValidity() at the end of CreateNewBlock().
86  bool test_block_validity{true};
88  };
89 
90  explicit BlockAssembler(Chainstate& chainstate, const CTxMemPool* mempool, const Options& options);
91 
93  std::unique_ptr<CBlockTemplate> CreateNewBlock();
94 
96  inline static std::optional<int64_t> m_last_block_num_txs{};
98  inline static std::optional<int64_t> m_last_block_weight{};
99 
100 private:
102 
103  // utility functions
105  void resetBlock();
107  void AddToBlock(const CTxMemPoolEntry& entry);
108 
109  // Methods for how to add transactions to a block.
115 
116  // helper functions for addChunks()
118  bool TestChunkBlockLimits(FeePerWeight chunk_feerate, int64_t chunk_sigops_cost) const;
122  bool TestChunkTransactions(const std::vector<CTxMemPoolEntryRef>& txs) const;
123 };
124 
130 int64_t GetMinimumTime(const CBlockIndex* pindexPrev, int64_t difficulty_adjustment_interval);
131 
132 int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev);
133 
135 void RegenerateCommitments(CBlock& block, ChainstateManager& chainman);
136 
139 
140 /* Compute the block's merkle root, insert or replace the coinbase transaction and the merkle root into the block */
141 void AddMerkleRootAndCoinbase(CBlock& block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce);
142 
143 
144 /* Interrupt a blocking call. */
145 void InterruptWait(KernelNotifications& kernel_notifications, bool& interrupt_wait);
151  KernelNotifications& kernel_notifications,
152  CTxMemPool* mempool,
153  const std::unique_ptr<CBlockTemplate>& block_template,
154  const BlockWaitOptions& options,
155  const BlockAssembler::Options& assemble_options,
156  bool& interrupt_wait);
157 
158 /* Locks cs_main and returns the block hash and block height of the active chain if it exists; otherwise, returns nullopt.*/
159 std::optional<BlockRef> GetTip(ChainstateManager& chainman);
160 
161 /* 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`).
162  * Returns the current tip, or nullopt if the node is shutting down or interrupt()
163  * is called.
164  */
165 std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const uint256& current_tip, MillisecondsDouble& timeout, bool& interrupt);
166 
186 bool CooldownIfHeadersAhead(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const BlockRef& last_tip, bool& interrupt_mining);
187 } // namespace node
188 
189 #endif // BITCOIN_NODE_MINER_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:403
static const bool DEFAULT_PRINT_MODIFIED_FEE
Definition: miner.h:40
Generate a new block, without valid proof-of-work.
Definition: miner.h:60
uint64_t nBlockWeight
Definition: miner.h:67
unsigned int nonce
Definition: miner_tests.cpp:82
void resetBlock()
Clear the block&#39;s state and prepare for assembling a new block.
Definition: miner.cpp:111
Definition: block.h:73
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
Definition: validation.h:939
bool TestChunkBlockLimits(FeePerWeight chunk_feerate, int64_t chunk_sigops_cost) const
Test if a new chunk would "fit" in the block.
Definition: miner.cpp:239
std::optional< BlockRef > GetTip(ChainstateManager &chainman)
Definition: miner.cpp:450
bool TestChunkTransactions(const std::vector< CTxMemPoolEntryRef > &txs) const
Perform locktime checks on each transaction in a chunk: This check should always succeed, and is here only as an extra check in case of a bug.
Definition: miner.cpp:252
static std::optional< int64_t > m_last_block_num_txs
The number of transactions in the last assembled block (excluding coinbase transaction) ...
Definition: miner.h:96
Hash/height pair to help track and identify blocks.
Definition: types.h:13
uint64_t nBlockTx
Definition: miner.h:68
std::optional< BlockRef > WaitTipChanged(ChainstateManager &chainman, KernelNotifications &kernel_notifications, const uint256 &current_tip, MillisecondsDouble &timeout, bool &interrupt)
Definition: miner.cpp:492
Definition: common.h:29
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:76
util::Result< void > ApplyArgsManOptions(const ArgsManager &args, BlockManager::Options &opts)
Tagged wrapper around FeeFrac to avoid unit confusion.
Definition: feefrac.h:238
CTxMemPoolEntry::CTxMemPoolEntryRef CTxMemPoolEntryRef
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:49
int64_t m_lock_time_cutoff
Definition: miner.h:74
CAmount nFees
Definition: miner.h:70
std::unique_ptr< CBlockTemplate > CreateNewBlock()
Construct a new block template.
Definition: miner.cpp:122
Transaction validation functions.
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: mempool_entry.h:65
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
std::vector< int64_t > vTxSigOpsCost
Definition: miner.h:48
Chainstate stores and provides an API to update our local knowledge of the current best chain...
Definition: validation.h:550
void AddMerkleRootAndCoinbase(CBlock &block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce)
Definition: miner.cpp:336
Template containing all coinbase transaction fields that are set by our miner code.
Definition: types.h:119
void InterruptWait(KernelNotifications &kernel_notifications, bool &interrupt_wait)
Definition: miner.cpp:354
Chainstate & m_chainstate
Definition: miner.h:78
Definition: messages.h:21
ArgsManager gArgs
Definition: args.cpp:40
int64_t GetMinimumTime(const CBlockIndex *pindexPrev, const int64_t difficulty_adjustment_interval)
Get the minimum time a miner should use in the next block.
Definition: miner.cpp:36
static std::optional< int64_t > m_last_block_weight
The weight of the last assembled block (including reserved weight for block header, txs count and coinbase tx)
Definition: miner.h:98
256-bit opaque blob.
Definition: uint256.h:195
void addChunks() EXCLUSIVE_LOCKS_REQUIRED(m_mempool -> cs)
Add transactions based on chunk feerate.
Definition: miner.cpp:279
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:51
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:186
std::vector< FeePerVSize > m_package_feerates
Definition: miner.h:51
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:93
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
BlockAssembler(Chainstate &chainstate, const CTxMemPool *mempool, const Options &options)
Definition: miner.cpp:90
const CChainParams & chainparams
Definition: miner.h:76
static constexpr unsigned int DEFAULT_BLOCK_MAX_WEIGHT
Default for -blockmaxweight, which controls the range of block weights the mining code will create...
Definition: policy.h:24
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac...
Definition: feerate.h:31
static void pool cs
bool CooldownIfHeadersAhead(ChainstateManager &chainman, KernelNotifications &kernel_notifications, const BlockRef &last_tip, bool &interrupt_mining)
Wait while the best known header extends the current chain tip AND at least one block is being added ...
Definition: miner.cpp:458
static constexpr unsigned int DEFAULT_BLOCK_MIN_TX_FEE
Default for -blockmintxfee, which sets the minimum feerate for a transaction in blocks created by min...
Definition: policy.h:35
uint64_t nBlockSigOpsCost
Definition: miner.h:69
std::vector< CAmount > vTxFees
Definition: miner.h:46
CoinbaseTx m_coinbase_tx
Definition: miner.h:56
const Options m_options
Definition: miner.h:101
std::unique_ptr< CBlockTemplate > pblocktemplate
Definition: miner.h:64
is a home for public enum and struct type definitions that are used internally by node code...
std::unique_ptr< CBlockTemplate > WaitAndCreateNewBlock(ChainstateManager &chainman, KernelNotifications &kernel_notifications, CTxMemPool *mempool, const std::unique_ptr< CBlockTemplate > &block_template, const BlockWaitOptions &options, const BlockAssembler::Options &assemble_options, bool &interrupt_wait)
Return a new block template when fees rise to a certain threshold or after a new tip; return nullopt ...
Definition: miner.cpp:361
void AddToBlock(const CTxMemPoolEntry &entry)
Add a tx to the block.
Definition: miner.cpp:262
void RegenerateCommitments(CBlock &block, ChainstateManager &chainman)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed...
Definition: miner.cpp:67
std::chrono::duration< double, std::chrono::milliseconds::period > MillisecondsDouble
Definition: time.h:94
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:26
const CTxMemPool *const m_mempool
Definition: miner.h:77