Bitcoin Core 29.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 <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 <memory>
17#include <optional>
18#include <stdint.h>
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
26class ArgsManager;
27class CBlockIndex;
28class CChainParams;
29class CScript;
30class Chainstate;
32
33namespace Consensus { struct Params; };
34
36
37namespace node {
38class KernelNotifications;
39
40static 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 std::vector<unsigned char> vchCoinbaseCommitment;
50 /* A vector of package fee rates, ordered by the sequence in which
51 * packages are selected for inclusion in the block template.*/
52 std::vector<FeeFrac> m_package_feerates;
53};
54
55// Container for tracking updates to ancestor feerate as we include (parent)
56// transactions in a block
59 {
60 iter = entry;
61 nSizeWithAncestors = entry->GetSizeWithAncestors();
62 nModFeesWithAncestors = entry->GetModFeesWithAncestors();
63 nSigOpCostWithAncestors = entry->GetSigOpCostWithAncestors();
64 }
65
66 CAmount GetModifiedFee() const { return iter->GetModifiedFee(); }
67 uint64_t GetSizeWithAncestors() const { return nSizeWithAncestors; }
69 size_t GetTxSize() const { return iter->GetTxSize(); }
70 const CTransaction& GetTx() const { return iter->GetTx(); }
71
76};
77
84 bool operator()(const CTxMemPool::txiter& a, const CTxMemPool::txiter& b) const
85 {
86 return &(*a) < &(*b);
87 }
88};
89
93 {
94 return entry.iter;
95 }
96};
97
98// A comparator that sorts transactions based on number of ancestors.
99// This is sufficient to sort an ancestor package in an order that is valid
100// to appear in a block.
102 bool operator()(const CTxMemPool::txiter& a, const CTxMemPool::txiter& b) const
103 {
104 if (a->GetCountWithAncestors() != b->GetCountWithAncestors()) {
105 return a->GetCountWithAncestors() < b->GetCountWithAncestors();
106 }
107 return CompareIteratorByHash()(a, b);
108 }
109};
110
111
112struct CTxMemPoolModifiedEntry_Indices final : boost::multi_index::indexed_by<
113 boost::multi_index::ordered_unique<
114 modifiedentry_iter,
115 CompareCTxMemPoolIter
116 >,
117 // sorted by modified ancestor fee rate
118 boost::multi_index::ordered_non_unique<
119 // Reuse same tag from CTxMemPool's similar index
120 boost::multi_index::tag<ancestor_score>,
121 boost::multi_index::identity<CTxMemPoolModifiedEntry>,
122 CompareTxMemPoolEntryByAncestorFee
123 >
124>
125{};
126
127typedef boost::multi_index_container<
131
132typedef indexed_modified_transaction_set::nth_index<0>::type::iterator modtxiter;
133typedef indexed_modified_transaction_set::index<ancestor_score>::type::iterator modtxscoreiter;
134
136{
138
140 {
141 e.nModFeesWithAncestors -= iter->GetModifiedFee();
142 e.nSizeWithAncestors -= iter->GetTxSize();
143 e.nSigOpCostWithAncestors -= iter->GetSigOpCost();
144 }
145
147};
148
151{
152private:
153 // The constructed block template
154 std::unique_ptr<CBlockTemplate> pblocktemplate;
155
156 // Information on the current status of the block
157 uint64_t nBlockWeight;
158 uint64_t nBlockTx;
161 std::unordered_set<Txid, SaltedTxidHasher> inBlock;
162
163 // Chain context for the block
166
168 const CTxMemPool* const m_mempool;
170
171public:
173 // Configuration parameters for the block size
176 // Whether to call TestBlockValidity() at the end of CreateNewBlock().
179 };
180
181 explicit BlockAssembler(Chainstate& chainstate, const CTxMemPool* mempool, const Options& options);
182
184 std::unique_ptr<CBlockTemplate> CreateNewBlock();
185
187 inline static std::optional<int64_t> m_last_block_num_txs{};
189 inline static std::optional<int64_t> m_last_block_weight{};
190
191private:
193
194 // utility functions
196 void resetBlock();
199
200 // Methods for how to add transactions to a block.
207 void addPackageTxs(int& nPackagesSelected, int& nDescendantsUpdated) EXCLUSIVE_LOCKS_REQUIRED(!m_mempool->cs);
208
209 // helper functions for addPackageTxs()
213 bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const;
218 bool TestPackageTransactions(const CTxMemPool::setEntries& package) const;
220 void SortForBlock(const CTxMemPool::setEntries& package, std::vector<CTxMemPool::txiter>& sortedEntries);
221};
222
228int64_t GetMinimumTime(const CBlockIndex* pindexPrev, const int64_t difficulty_adjustment_interval);
229
230int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev);
231
233void RegenerateCommitments(CBlock& block, ChainstateManager& chainman);
234
237
238/* Compute the block's merkle root, insert or replace the coinbase transaction and the merkle root into the block */
239void AddMerkleRootAndCoinbase(CBlock& block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce);
240
245std::unique_ptr<CBlockTemplate> WaitAndCreateNewBlock(ChainstateManager& chainman,
246 KernelNotifications& kernel_notifications,
247 CTxMemPool* mempool,
248 const std::unique_ptr<CBlockTemplate>& block_template,
249 const BlockWaitOptions& options,
250 const BlockAssembler::Options& assemble_options);
251
252/* Locks cs_main and returns the block hash and block height of the active chain if it exists; otherwise, returns nullopt.*/
253std::optional<BlockRef> GetTip(ChainstateManager& chainman);
254
255/* 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`).
256 * Returns the current tip, or nullopt if the node is shutting down. */
257std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const uint256& current_tip, MillisecondsDouble& timeout);
258} // namespace node
259
260#endif // BITCOIN_NODE_MINER_H
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
ArgsManager gArgs
Definition: args.cpp:42
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:69
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:33
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:415
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
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:390
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:506
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:866
Generate a new block, without valid proof-of-work.
Definition: miner.h:151
Chainstate & m_chainstate
Definition: miner.h:169
void onlyUnconfirmed(CTxMemPool::setEntries &testSet)
Remove confirmed (inBlock) entries from given set.
Definition: miner.cpp:197
void resetBlock()
Clear the block's state and prepare for assembling a new block.
Definition: miner.cpp:108
bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
Test if a new package would "fit" in the block.
Definition: miner.cpp:209
const CTxMemPool *const m_mempool
Definition: miner.h:168
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:223
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:302
const CChainParams & chainparams
Definition: miner.h:167
const Options m_options
Definition: miner.h:192
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:281
uint64_t nBlockTx
Definition: miner.h:158
uint64_t nBlockSigOpsCost
Definition: miner.h:159
int64_t m_lock_time_cutoff
Definition: miner.h:165
std::unordered_set< Txid, SaltedTxidHasher > inBlock
Definition: miner.h:161
uint64_t nBlockWeight
Definition: miner.h:157
std::unique_ptr< CBlockTemplate > pblocktemplate
Definition: miner.h:154
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:187
void AddToBlock(CTxMemPool::txiter iter)
Add a tx to the block.
Definition: miner.cpp:233
BlockAssembler(Chainstate &chainstate, const CTxMemPool *mempool, const Options &options)
Definition: miner.cpp:89
std::unique_ptr< CBlockTemplate > CreateNewBlock()
Construct a new block template.
Definition: miner.cpp:121
static std::optional< int64_t > m_last_block_weight
The weight of the last assembled block (including reserved weight for block header,...
Definition: miner.h:189
256-bit opaque blob.
Definition: uint256.h:196
unsigned int nonce
Definition: miner_tests.cpp:74
Transaction validation functions.
Definition: messages.h:20
boost::multi_index_container< CTxMemPoolModifiedEntry, CTxMemPoolModifiedEntry_Indices > indexed_modified_transaction_set
Definition: miner.h:130
indexed_modified_transaction_set::nth_index< 0 >::type::iterator modtxiter
Definition: miner.h:132
void RegenerateCommitments(CBlock &block, ChainstateManager &chainman)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed.
Definition: miner.cpp:66
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:35
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:48
indexed_modified_transaction_set::index< ancestor_score >::type::iterator modtxscoreiter
Definition: miner.h:133
util::Result< void > ApplyArgsManOptions(const ArgsManager &args, BlockManager::Options &opts)
static const bool DEFAULT_PRINT_MODIFIED_FEE
Definition: miner.h:40
std::optional< BlockRef > WaitTipChanged(ChainstateManager &chainman, KernelNotifications &kernel_notifications, const uint256 &current_tip, MillisecondsDouble &timeout)
Definition: miner.cpp:554
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)
Return a new block template when fees rise to a certain threshold or after a new tip; return nullopt ...
Definition: miner.cpp:457
void AddMerkleRootAndCoinbase(CBlock &block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce)
Definition: miner.cpp:444
std::optional< BlockRef > GetTip(ChainstateManager &chainman)
Definition: miner.cpp:546
is a home for public enum and struct type definitions that are used 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:32
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
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
Parameters that influence chain consensus.
Definition: params.h:83
Hash/height pair to help track and identify blocks.
Definition: types.h:13
std::vector< int64_t > vTxSigOpsCost
Definition: miner.h:48
std::vector< FeeFrac > m_package_feerates
Definition: miner.h:52
std::vector< CAmount > vTxFees
Definition: miner.h:46
std::vector< unsigned char > vchCoinbaseCommitment
Definition: miner.h:49
Definition: miner.h:125
Definition: miner.h:57
CAmount nModFeesWithAncestors
Definition: miner.h:74
CAmount GetModFeesWithAncestors() const
Definition: miner.h:68
CTxMemPoolModifiedEntry(CTxMemPool::txiter entry)
Definition: miner.h:58
CAmount GetModifiedFee() const
Definition: miner.h:66
const CTransaction & GetTx() const
Definition: miner.h:70
size_t GetTxSize() const
Definition: miner.h:69
uint64_t GetSizeWithAncestors() const
Definition: miner.h:67
uint64_t nSizeWithAncestors
Definition: miner.h:73
CTxMemPool::txiter iter
Definition: miner.h:72
int64_t nSigOpCostWithAncestors
Definition: miner.h:75
Comparator for CTxMemPool::txiter objects.
Definition: miner.h:83
bool operator()(const CTxMemPool::txiter &a, const CTxMemPool::txiter &b) const
Definition: miner.h:84
bool operator()(const CTxMemPool::txiter &a, const CTxMemPool::txiter &b) const
Definition: miner.h:102
CTxMemPool::txiter result_type
Definition: miner.h:91
result_type operator()(const CTxMemPoolModifiedEntry &entry) const
Definition: miner.h:92
update_for_parent_inclusion(CTxMemPool::txiter it)
Definition: miner.h:137
CTxMemPool::txiter iter
Definition: miner.h:146
void operator()(CTxMemPoolModifiedEntry &e)
Definition: miner.h:139
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
std::chrono::duration< double, std::chrono::milliseconds::period > MillisecondsDouble
Definition: time.h:88