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 <node/types.h>
10 #include <policy/policy.h>
11 #include <primitives/block.h>
12 #include <txmempool.h>
13 
14 #include <memory>
15 #include <optional>
16 #include <stdint.h>
17 
18 #include <boost/multi_index/identity.hpp>
19 #include <boost/multi_index/indexed_by.hpp>
20 #include <boost/multi_index/ordered_index.hpp>
21 #include <boost/multi_index/tag.hpp>
22 #include <boost/multi_index_container.hpp>
23 
24 class ArgsManager;
25 class CBlockIndex;
26 class CChainParams;
27 class CScript;
28 class Chainstate;
29 class ChainstateManager;
30 
31 namespace Consensus { struct Params; };
32 
33 namespace node {
34 static const bool DEFAULT_PRINT_MODIFIED_FEE = false;
35 
37 {
39  std::vector<CAmount> vTxFees;
40  std::vector<int64_t> vTxSigOpsCost;
41  std::vector<unsigned char> vchCoinbaseCommitment;
42 };
43 
44 // Container for tracking updates to ancestor feerate as we include (parent)
45 // transactions in a block
48  {
49  iter = entry;
50  nSizeWithAncestors = entry->GetSizeWithAncestors();
51  nModFeesWithAncestors = entry->GetModFeesWithAncestors();
52  nSigOpCostWithAncestors = entry->GetSigOpCostWithAncestors();
53  }
54 
55  CAmount GetModifiedFee() const { return iter->GetModifiedFee(); }
56  uint64_t GetSizeWithAncestors() const { return nSizeWithAncestors; }
58  size_t GetTxSize() const { return iter->GetTxSize(); }
59  const CTransaction& GetTx() const { return iter->GetTx(); }
60 
65 };
66 
73  bool operator()(const CTxMemPool::txiter& a, const CTxMemPool::txiter& b) const
74  {
75  return &(*a) < &(*b);
76  }
77 };
78 
82  {
83  return entry.iter;
84  }
85 };
86 
87 // A comparator that sorts transactions based on number of ancestors.
88 // This is sufficient to sort an ancestor package in an order that is valid
89 // to appear in a block.
91  bool operator()(const CTxMemPool::txiter& a, const CTxMemPool::txiter& b) const
92  {
93  if (a->GetCountWithAncestors() != b->GetCountWithAncestors()) {
94  return a->GetCountWithAncestors() < b->GetCountWithAncestors();
95  }
96  return CompareIteratorByHash()(a, b);
97  }
98 };
99 
100 typedef boost::multi_index_container<
101  CTxMemPoolModifiedEntry,
102  boost::multi_index::indexed_by<
103  boost::multi_index::ordered_unique<
104  modifiedentry_iter,
105  CompareCTxMemPoolIter
106  >,
107  // sorted by modified ancestor fee rate
108  boost::multi_index::ordered_non_unique<
109  // Reuse same tag from CTxMemPool's similar index
110  boost::multi_index::tag<ancestor_score>,
111  boost::multi_index::identity<CTxMemPoolModifiedEntry>,
113  >
114  >
116 
117 typedef indexed_modified_transaction_set::nth_index<0>::type::iterator modtxiter;
118 typedef indexed_modified_transaction_set::index<ancestor_score>::type::iterator modtxscoreiter;
119 
121 {
123 
125  {
126  e.nModFeesWithAncestors -= iter->GetModifiedFee();
127  e.nSizeWithAncestors -= iter->GetTxSize();
128  e.nSigOpCostWithAncestors -= iter->GetSigOpCost();
129  }
130 
132 };
133 
136 {
137 private:
138  // The constructed block template
139  std::unique_ptr<CBlockTemplate> pblocktemplate;
140 
141  // Information on the current status of the block
142  uint64_t nBlockWeight;
143  uint64_t nBlockTx;
146  std::unordered_set<Txid, SaltedTxidHasher> inBlock;
147 
148  // Chain context for the block
149  int nHeight;
151 
153  const CTxMemPool* const m_mempool;
155 
156 public:
158  // Configuration parameters for the block size
161  // Whether to call TestBlockValidity() at the end of CreateNewBlock().
164  };
165 
166  explicit BlockAssembler(Chainstate& chainstate, const CTxMemPool* mempool, const Options& options);
167 
169  std::unique_ptr<CBlockTemplate> CreateNewBlock(const CScript& scriptPubKeyIn);
170 
171  inline static std::optional<int64_t> m_last_block_num_txs{};
172  inline static std::optional<int64_t> m_last_block_weight{};
173 
174 private:
176 
177  // utility functions
179  void resetBlock();
181  void AddToBlock(CTxMemPool::txiter iter);
182 
183  // Methods for how to add transactions to a block.
187  void addPackageTxs(const CTxMemPool& mempool, int& nPackagesSelected, int& nDescendantsUpdated) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs);
188 
189  // helper functions for addPackageTxs()
193  bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const;
198  bool TestPackageTransactions(const CTxMemPool::setEntries& package) const;
200  void SortForBlock(const CTxMemPool::setEntries& package, std::vector<CTxMemPool::txiter>& sortedEntries);
201 };
202 
203 int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev);
204 
206 void RegenerateCommitments(CBlock& block, ChainstateManager& chainman);
207 
210 } // namespace node
211 
212 #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:304
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:394
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:391
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:513
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:871
Definition: txmempool.h:164
Generate a new block, without valid proof-of-work.
Definition: miner.h:136
Chainstate & m_chainstate
Definition: miner.h:154
void onlyUnconfirmed(CTxMemPool::setEntries &testSet)
Remove confirmed (inBlock) entries from given set.
Definition: miner.cpp:182
void resetBlock()
Clear the block's state and prepare for assembling a new block.
Definition: miner.cpp:88
bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
Test if a new package would "fit" in the block.
Definition: miner.cpp:194
const CTxMemPool *const m_mempool
Definition: miner.h:153
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:208
const CChainParams & chainparams
Definition: miner.h:152
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:287
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn)
Construct a new block template with coinbase to scriptPubKeyIn.
Definition: miner.cpp:101
const Options m_options
Definition: miner.h:175
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:266
uint64_t nBlockTx
Definition: miner.h:143
uint64_t nBlockSigOpsCost
Definition: miner.h:144
int64_t m_lock_time_cutoff
Definition: miner.h:150
std::unordered_set< Txid, SaltedTxidHasher > inBlock
Definition: miner.h:146
uint64_t nBlockWeight
Definition: miner.h:142
std::unique_ptr< CBlockTemplate > pblocktemplate
Definition: miner.h:139
static std::optional< int64_t > m_last_block_num_txs
Definition: miner.h:171
void AddToBlock(CTxMemPool::txiter iter)
Add a tx to the block.
Definition: miner.cpp:218
BlockAssembler(Chainstate &chainstate, const CTxMemPool *mempool, const Options &options)
Definition: miner.cpp:70
static std::optional< int64_t > m_last_block_weight
Definition: miner.h:172
Transaction validation functions.
Definition: messages.h:20
indexed_modified_transaction_set::nth_index< 0 >::type::iterator modtxiter
Definition: miner.h:117
void RegenerateCommitments(CBlock &block, ChainstateManager &chainman)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed.
Definition: miner.cpp:48
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:118
util::Result< void > ApplyArgsManOptions(const ArgsManager &args, BlockManager::Options &opts)
static const bool DEFAULT_PRINT_MODIFIED_FEE
Definition: miner.h:34
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:115
is a home for public enum and struct type definitions that are used by internally by node code,...
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:40
std::vector< CAmount > vTxFees
Definition: miner.h:39
std::vector< unsigned char > vchCoinbaseCommitment
Definition: miner.h:41
Definition: miner.h:46
CAmount nModFeesWithAncestors
Definition: miner.h:63
CAmount GetModFeesWithAncestors() const
Definition: miner.h:57
CTxMemPoolModifiedEntry(CTxMemPool::txiter entry)
Definition: miner.h:47
CAmount GetModifiedFee() const
Definition: miner.h:55
size_t GetTxSize() const
Definition: miner.h:58
uint64_t GetSizeWithAncestors() const
Definition: miner.h:56
uint64_t nSizeWithAncestors
Definition: miner.h:62
CTxMemPool::txiter iter
Definition: miner.h:61
int64_t nSigOpCostWithAncestors
Definition: miner.h:64
const CTransaction & GetTx() const
Definition: miner.h:59
Comparator for CTxMemPool::txiter objects.
Definition: miner.h:72
bool operator()(const CTxMemPool::txiter &a, const CTxMemPool::txiter &b) const
Definition: miner.h:73
bool operator()(const CTxMemPool::txiter &a, const CTxMemPool::txiter &b) const
Definition: miner.h:91
CTxMemPool::txiter result_type
Definition: miner.h:80
result_type operator()(const CTxMemPoolModifiedEntry &entry) const
Definition: miner.h:81
update_for_parent_inclusion(CTxMemPool::txiter it)
Definition: miner.h:122
CTxMemPool::txiter iter
Definition: miner.h:131
void operator()(CTxMemPoolModifiedEntry &e)
Definition: miner.h:124
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49