Bitcoin Core  27.99.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 <policy/policy.h>
10 #include <primitives/block.h>
11 #include <txmempool.h>
12 
13 #include <memory>
14 #include <optional>
15 #include <stdint.h>
16 
17 #include <boost/multi_index/identity.hpp>
18 #include <boost/multi_index/indexed_by.hpp>
19 #include <boost/multi_index/ordered_index.hpp>
20 #include <boost/multi_index/tag.hpp>
21 #include <boost/multi_index_container.hpp>
22 
23 class ArgsManager;
24 class CBlockIndex;
25 class CChainParams;
26 class CScript;
27 class Chainstate;
28 class ChainstateManager;
29 
30 namespace Consensus { struct Params; };
31 
32 namespace node {
33 static const bool DEFAULT_PRINTPRIORITY = false;
34 
36 {
38  std::vector<CAmount> vTxFees;
39  std::vector<int64_t> vTxSigOpsCost;
40  std::vector<unsigned char> vchCoinbaseCommitment;
41 };
42 
43 // Container for tracking updates to ancestor feerate as we include (parent)
44 // transactions in a block
47  {
48  iter = entry;
49  nSizeWithAncestors = entry->GetSizeWithAncestors();
50  nModFeesWithAncestors = entry->GetModFeesWithAncestors();
51  nSigOpCostWithAncestors = entry->GetSigOpCostWithAncestors();
52  }
53 
54  CAmount GetModifiedFee() const { return iter->GetModifiedFee(); }
55  uint64_t GetSizeWithAncestors() const { return nSizeWithAncestors; }
57  size_t GetTxSize() const { return iter->GetTxSize(); }
58  const CTransaction& GetTx() const { return iter->GetTx(); }
59 
64 };
65 
72  bool operator()(const CTxMemPool::txiter& a, const CTxMemPool::txiter& b) const
73  {
74  return &(*a) < &(*b);
75  }
76 };
77 
81  {
82  return entry.iter;
83  }
84 };
85 
86 // A comparator that sorts transactions based on number of ancestors.
87 // This is sufficient to sort an ancestor package in an order that is valid
88 // to appear in a block.
90  bool operator()(const CTxMemPool::txiter& a, const CTxMemPool::txiter& b) const
91  {
92  if (a->GetCountWithAncestors() != b->GetCountWithAncestors()) {
93  return a->GetCountWithAncestors() < b->GetCountWithAncestors();
94  }
95  return CompareIteratorByHash()(a, b);
96  }
97 };
98 
99 typedef boost::multi_index_container<
100  CTxMemPoolModifiedEntry,
101  boost::multi_index::indexed_by<
102  boost::multi_index::ordered_unique<
103  modifiedentry_iter,
104  CompareCTxMemPoolIter
105  >,
106  // sorted by modified ancestor fee rate
107  boost::multi_index::ordered_non_unique<
108  // Reuse same tag from CTxMemPool's similar index
109  boost::multi_index::tag<ancestor_score>,
110  boost::multi_index::identity<CTxMemPoolModifiedEntry>,
112  >
113  >
115 
116 typedef indexed_modified_transaction_set::nth_index<0>::type::iterator modtxiter;
117 typedef indexed_modified_transaction_set::index<ancestor_score>::type::iterator modtxscoreiter;
118 
120 {
122 
124  {
125  e.nModFeesWithAncestors -= iter->GetModifiedFee();
126  e.nSizeWithAncestors -= iter->GetTxSize();
127  e.nSigOpCostWithAncestors -= iter->GetSigOpCost();
128  }
129 
131 };
132 
135 {
136 private:
137  // The constructed block template
138  std::unique_ptr<CBlockTemplate> pblocktemplate;
139 
140  // Information on the current status of the block
141  uint64_t nBlockWeight;
142  uint64_t nBlockTx;
145  std::unordered_set<Txid, SaltedTxidHasher> inBlock;
146 
147  // Chain context for the block
148  int nHeight;
150 
152  const CTxMemPool* const m_mempool;
154 
155 public:
156  struct Options {
157  // Configuration parameters for the block size
160  // Whether to call TestBlockValidity() at the end of CreateNewBlock().
162  };
163 
164  explicit BlockAssembler(Chainstate& chainstate, const CTxMemPool* mempool);
165  explicit BlockAssembler(Chainstate& chainstate, const CTxMemPool* mempool, const Options& options);
166 
168  std::unique_ptr<CBlockTemplate> CreateNewBlock(const CScript& scriptPubKeyIn);
169 
170  inline static std::optional<int64_t> m_last_block_num_txs{};
171  inline static std::optional<int64_t> m_last_block_weight{};
172 
173 private:
175 
176  // utility functions
178  void resetBlock();
180  void AddToBlock(CTxMemPool::txiter iter);
181 
182  // Methods for how to add transactions to a block.
186  void addPackageTxs(const CTxMemPool& mempool, int& nPackagesSelected, int& nDescendantsUpdated) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs);
187 
188  // helper functions for addPackageTxs()
192  bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const;
197  bool TestPackageTransactions(const CTxMemPool::setEntries& package) const;
199  void SortForBlock(const CTxMemPool::setEntries& package, std::vector<CTxMemPool::txiter>& sortedEntries);
200 };
201 
202 int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev);
203 
205 void RegenerateCommitments(CBlock& block, ChainstateManager& chainman);
206 
209 } // namespace node
210 
211 #endif // BITCOIN_NODE_MINER_H
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
ArgsManager gArgs
Definition: args.cpp:41
const CChainParams & Params()
Return the currently selected parameters.
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:22
Definition: block.h:69
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:141
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:81
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:33
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:414
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:296
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:302
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:396
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:393
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:491
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:850
Definition: txmempool.h:162
Generate a new block, without valid proof-of-work.
Definition: miner.h:135
Chainstate & m_chainstate
Definition: miner.h:153
void onlyUnconfirmed(CTxMemPool::setEntries &testSet)
Remove confirmed (inBlock) entries from given set.
Definition: miner.cpp:187
void resetBlock()
Clear the block's state and prepare for assembling a new block.
Definition: miner.cpp:93
bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
Test if a new package would "fit" in the block.
Definition: miner.cpp:199
const CTxMemPool *const m_mempool
Definition: miner.h:152
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:213
const CChainParams & chainparams
Definition: miner.h:151
void addPackageTxs(const CTxMemPool &mempool, int &nPackagesSelected, int &nDescendantsUpdated) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs)
Add transactions based on feerate including unconfirmed ancestors Increments nPackagesSelected / nDes...
Definition: miner.cpp:293
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn)
Construct a new block template with coinbase to scriptPubKeyIn.
Definition: miner.cpp:106
const Options m_options
Definition: miner.h:174
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:272
uint64_t nBlockTx
Definition: miner.h:142
uint64_t nBlockSigOpsCost
Definition: miner.h:143
BlockAssembler(Chainstate &chainstate, const CTxMemPool *mempool)
Definition: miner.cpp:90
int64_t m_lock_time_cutoff
Definition: miner.h:149
std::unordered_set< Txid, SaltedTxidHasher > inBlock
Definition: miner.h:145
uint64_t nBlockWeight
Definition: miner.h:141
std::unique_ptr< CBlockTemplate > pblocktemplate
Definition: miner.h:138
static std::optional< int64_t > m_last_block_num_txs
Definition: miner.h:170
void AddToBlock(CTxMemPool::txiter iter)
Add a tx to the block.
Definition: miner.cpp:223
static std::optional< int64_t > m_last_block_weight
Definition: miner.h:171
Transaction validation functions.
Definition: init.h:25
indexed_modified_transaction_set::nth_index< 0 >::type::iterator modtxiter
Definition: miner.h:116
void RegenerateCommitments(CBlock &block, ChainstateManager &chainman)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed.
Definition: miner.cpp:48
static const bool DEFAULT_PRINTPRIORITY
Definition: miner.h:33
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:31
indexed_modified_transaction_set::index< ancestor_score >::type::iterator modtxscoreiter
Definition: miner.h:117
util::Result< void > ApplyArgsManOptions(const ArgsManager &args, BlockManager::Options &opts)
boost::multi_index_container< CTxMemPoolModifiedEntry, boost::multi_index::indexed_by< boost::multi_index::ordered_unique< modifiedentry_iter, CompareCTxMemPoolIter >, boost::multi_index::ordered_non_unique< boost::multi_index::tag< ancestor_score >, boost::multi_index::identity< CTxMemPoolModifiedEntry >, CompareTxMemPoolEntryByAncestorFee > >> indexed_modified_transaction_set
Definition: miner.h:114
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:25
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
Parameters that influence chain consensus.
Definition: params.h:74
std::vector< int64_t > vTxSigOpsCost
Definition: miner.h:39
std::vector< CAmount > vTxFees
Definition: miner.h:38
std::vector< unsigned char > vchCoinbaseCommitment
Definition: miner.h:40
Definition: miner.h:45
CAmount nModFeesWithAncestors
Definition: miner.h:62
CAmount GetModFeesWithAncestors() const
Definition: miner.h:56
CTxMemPoolModifiedEntry(CTxMemPool::txiter entry)
Definition: miner.h:46
CAmount GetModifiedFee() const
Definition: miner.h:54
size_t GetTxSize() const
Definition: miner.h:57
uint64_t GetSizeWithAncestors() const
Definition: miner.h:55
uint64_t nSizeWithAncestors
Definition: miner.h:61
CTxMemPool::txiter iter
Definition: miner.h:60
int64_t nSigOpCostWithAncestors
Definition: miner.h:63
const CTransaction & GetTx() const
Definition: miner.h:58
Comparator for CTxMemPool::txiter objects.
Definition: miner.h:71
bool operator()(const CTxMemPool::txiter &a, const CTxMemPool::txiter &b) const
Definition: miner.h:72
bool operator()(const CTxMemPool::txiter &a, const CTxMemPool::txiter &b) const
Definition: miner.h:90
CTxMemPool::txiter result_type
Definition: miner.h:79
result_type operator()(const CTxMemPoolModifiedEntry &entry) const
Definition: miner.h:80
update_for_parent_inclusion(CTxMemPool::txiter it)
Definition: miner.h:121
CTxMemPool::txiter iter
Definition: miner.h:130
void operator()(CTxMemPoolModifiedEntry &e)
Definition: miner.h:123
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49