Bitcoin Core  29.1.0
P2P Digital Currency
miner.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2022 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 <node/types.h>
10 #include <policy/policy.h>
11 #include <primitives/block.h>
12 #include <txmempool.h>
13 #include <util/feefrac.h>
14 
15 #include <memory>
16 #include <optional>
17 #include <stdint.h>
18 
19 #include <boost/multi_index/identity.hpp>
20 #include <boost/multi_index/indexed_by.hpp>
21 #include <boost/multi_index/ordered_index.hpp>
22 #include <boost/multi_index/tag.hpp>
23 #include <boost/multi_index_container.hpp>
24 
25 class ArgsManager;
26 class CBlockIndex;
27 class CChainParams;
28 class CScript;
29 class Chainstate;
30 class ChainstateManager;
31 
32 namespace Consensus { struct Params; };
33 
34 namespace node {
35 static const bool DEFAULT_PRINT_MODIFIED_FEE = false;
36 
38 {
40  std::vector<CAmount> vTxFees;
41  std::vector<int64_t> vTxSigOpsCost;
42  std::vector<unsigned char> vchCoinbaseCommitment;
43  /* A vector of package fee rates, ordered by the sequence in which
44  * packages are selected for inclusion in the block template.*/
45  std::vector<FeeFrac> m_package_feerates;
46 };
47 
48 // Container for tracking updates to ancestor feerate as we include (parent)
49 // transactions in a block
52  {
53  iter = entry;
54  nSizeWithAncestors = entry->GetSizeWithAncestors();
55  nModFeesWithAncestors = entry->GetModFeesWithAncestors();
56  nSigOpCostWithAncestors = entry->GetSigOpCostWithAncestors();
57  }
58 
59  CAmount GetModifiedFee() const { return iter->GetModifiedFee(); }
60  uint64_t GetSizeWithAncestors() const { return nSizeWithAncestors; }
62  size_t GetTxSize() const { return iter->GetTxSize(); }
63  const CTransaction& GetTx() const { return iter->GetTx(); }
64 
69 };
70 
77  bool operator()(const CTxMemPool::txiter& a, const CTxMemPool::txiter& b) const
78  {
79  return &(*a) < &(*b);
80  }
81 };
82 
86  {
87  return entry.iter;
88  }
89 };
90 
91 // A comparator that sorts transactions based on number of ancestors.
92 // This is sufficient to sort an ancestor package in an order that is valid
93 // to appear in a block.
95  bool operator()(const CTxMemPool::txiter& a, const CTxMemPool::txiter& b) const
96  {
97  if (a->GetCountWithAncestors() != b->GetCountWithAncestors()) {
98  return a->GetCountWithAncestors() < b->GetCountWithAncestors();
99  }
100  return CompareIteratorByHash()(a, b);
101  }
102 };
103 
104 
105 struct CTxMemPoolModifiedEntry_Indices final : boost::multi_index::indexed_by<
106  boost::multi_index::ordered_unique<
107  modifiedentry_iter,
108  CompareCTxMemPoolIter
109  >,
110  // sorted by modified ancestor fee rate
111  boost::multi_index::ordered_non_unique<
112  // Reuse same tag from CTxMemPool's similar index
113  boost::multi_index::tag<ancestor_score>,
114  boost::multi_index::identity<CTxMemPoolModifiedEntry>,
115  CompareTxMemPoolEntryByAncestorFee
116  >
117 >
118 {};
119 
120 typedef boost::multi_index_container<
124 
125 typedef indexed_modified_transaction_set::nth_index<0>::type::iterator modtxiter;
126 typedef indexed_modified_transaction_set::index<ancestor_score>::type::iterator modtxscoreiter;
127 
129 {
131 
133  {
134  e.nModFeesWithAncestors -= iter->GetModifiedFee();
135  e.nSizeWithAncestors -= iter->GetTxSize();
136  e.nSigOpCostWithAncestors -= iter->GetSigOpCost();
137  }
138 
140 };
141 
144 {
145 private:
146  // The constructed block template
147  std::unique_ptr<CBlockTemplate> pblocktemplate;
148 
149  // Information on the current status of the block
150  uint64_t nBlockWeight;
151  uint64_t nBlockTx;
154  std::unordered_set<Txid, SaltedTxidHasher> inBlock;
155 
156  // Chain context for the block
157  int nHeight;
159 
161  const CTxMemPool* const m_mempool;
163 
164 public:
166  // Configuration parameters for the block size
169  // Whether to call TestBlockValidity() at the end of CreateNewBlock().
172  };
173 
174  explicit BlockAssembler(Chainstate& chainstate, const CTxMemPool* mempool, const Options& options);
175 
177  std::unique_ptr<CBlockTemplate> CreateNewBlock();
178 
180  inline static std::optional<int64_t> m_last_block_num_txs{};
182  inline static std::optional<int64_t> m_last_block_weight{};
183 
184 private:
186 
187  // utility functions
189  void resetBlock();
191  void AddToBlock(CTxMemPool::txiter iter);
192 
193  // Methods for how to add transactions to a block.
200  void addPackageTxs(int& nPackagesSelected, int& nDescendantsUpdated) EXCLUSIVE_LOCKS_REQUIRED(!m_mempool->cs);
201 
202  // helper functions for addPackageTxs()
206  bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const;
211  bool TestPackageTransactions(const CTxMemPool::setEntries& package) const;
213  void SortForBlock(const CTxMemPool::setEntries& package, std::vector<CTxMemPool::txiter>& sortedEntries);
214 };
215 
221 int64_t GetMinimumTime(const CBlockIndex* pindexPrev, const int64_t difficulty_adjustment_interval);
222 
223 int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev);
224 
226 void RegenerateCommitments(CBlock& block, ChainstateManager& chainman);
227 
230 } // namespace node
231 
232 #endif // BITCOIN_NODE_MINER_H
static const bool DEFAULT_PRINT_MODIFIED_FEE
Definition: miner.h:35
indexed_modified_transaction_set::index< ancestor_score >::type::iterator modtxscoreiter
Definition: miner.h:126
void onlyUnconfirmed(CTxMemPool::setEntries &testSet)
Remove confirmed (inBlock) entries from given set.
Definition: miner.cpp:194
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:393
Generate a new block, without valid proof-of-work.
Definition: miner.h:143
uint64_t nBlockWeight
Definition: miner.h:150
void resetBlock()
Clear the block&#39;s state and prepare for assembling a new block.
Definition: miner.cpp:105
Definition: block.h:68
bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
Test if a new package would "fit" in the block.
Definition: miner.cpp:206
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:865
bool operator()(const CTxMemPool::txiter &a, const CTxMemPool::txiter &b) const
Definition: miner.h:95
bool TestPackageTransactions(const CTxMemPool::setEntries &package) const
Perform checks on each transaction in a package: locktime, premature-witness, serialized size (if nec...
Definition: miner.cpp:220
void SortForBlock(const CTxMemPool::setEntries &package, std::vector< CTxMemPool::txiter > &sortedEntries)
Sort the package in an order that is valid to appear in a block.
Definition: miner.cpp:278
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:180
uint64_t nBlockTx
Definition: miner.h:151
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:396
Comparator for CTxMemPool::txiter objects.
Definition: miner.h:76
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:80
util::Result< void > ApplyArgsManOptions(const ArgsManager &args, BlockManager::Options &opts)
void operator()(CTxMemPoolModifiedEntry &e)
Definition: miner.h:132
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:45
int64_t m_lock_time_cutoff
Definition: miner.h:158
std::vector< unsigned char > vchCoinbaseCommitment
Definition: miner.h:42
Definition: miner.h:50
void AddToBlock(CTxMemPool::txiter iter)
Add a tx to the block.
Definition: miner.cpp:230
std::unique_ptr< CBlockTemplate > CreateNewBlock()
Construct a new block template.
Definition: miner.cpp:118
Transaction validation functions.
const CTransaction & GetTx() const
Definition: miner.h:63
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
void addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated) EXCLUSIVE_LOCKS_REQUIRED(!m_mempool -> cs)
Add transactions based on feerate including unconfirmed ancestors Increments nPackagesSelected / nDes...
Definition: miner.cpp:299
std::vector< int64_t > vTxSigOpsCost
Definition: miner.h:41
CAmount nModFeesWithAncestors
Definition: miner.h:67
CAmount GetModifiedFee() const
Definition: miner.h:59
Chainstate stores and provides an API to update our local knowledge of the current best chain...
Definition: validation.h:504
boost::multi_index_container< CTxMemPoolModifiedEntry, CTxMemPoolModifiedEntry_Indices > indexed_modified_transaction_set
Definition: miner.h:123
size_t GetTxSize() const
Definition: miner.h:62
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:32
Parameters that influence chain consensus.
Definition: params.h:74
std::unordered_set< Txid, SaltedTxidHasher > inBlock
Definition: miner.h:154
Chainstate & m_chainstate
Definition: miner.h:162
CTxMemPoolModifiedEntry(CTxMemPool::txiter entry)
Definition: miner.h:51
Definition: messages.h:20
ArgsManager gArgs
Definition: args.cpp:42
CTxMemPool::txiter iter
Definition: miner.h:139
CTxMemPool::txiter iter
Definition: miner.h:65
update_for_parent_inclusion(CTxMemPool::txiter it)
Definition: miner.h:130
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:182
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
CAmount GetModFeesWithAncestors() const
Definition: miner.h:61
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:303
int64_t nSigOpCostWithAncestors
Definition: miner.h:68
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:140
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:414
BlockAssembler(Chainstate &chainstate, const CTxMemPool *mempool, const Options &options)
Definition: miner.cpp:86
bool operator()(const CTxMemPool::txiter &a, const CTxMemPool::txiter &b) const
Definition: miner.h:77
const CChainParams & chainparams
Definition: miner.h:160
indexed_modified_transaction_set::nth_index< 0 >::type::iterator modtxiter
Definition: miner.h:125
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:23
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:32
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:32
uint64_t nBlockSigOpsCost
Definition: miner.h:152
std::vector< CAmount > vTxFees
Definition: miner.h:40
CTxMemPool::txiter result_type
Definition: miner.h:84
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:295
Definition: miner.h:105
result_type operator()(const CTxMemPoolModifiedEntry &entry) const
Definition: miner.h:85
const Options m_options
Definition: miner.h:185
std::unique_ptr< CBlockTemplate > pblocktemplate
Definition: miner.h:147
std::vector< FeeFrac > m_package_feerates
Definition: miner.h:45
is a home for public enum and struct type definitions that are used internally by node code...
void RegenerateCommitments(CBlock &block, ChainstateManager &chainman)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed...
Definition: miner.cpp:63
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:21
uint64_t nSizeWithAncestors
Definition: miner.h:66
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it...
Definition: txmempool.h:390
uint64_t GetSizeWithAncestors() const
Definition: miner.h:60
const CTxMemPool *const m_mempool
Definition: miner.h:161