1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 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_MINER_H
7 #define BITCOIN_MINER_H
8 
9 #include <primitives/block.h>
10 #include <txmempool.h>
11 #include <validation.h>
12 
13 #include <memory>
14 #include <optional>
15 #include <stdint.h>
16 
17 #include <boost/multi_index_container.hpp>
18 #include <boost/multi_index/ordered_index.hpp>
19 
20 class CBlockIndex;
21 class CChainParams;
22 class CScript;
23 
24 namespace Consensus { struct Params; };
25 
26 static const bool DEFAULT_PRINTPRIORITY = false;
27 
28 struct CBlockTemplate
29 {
30     CBlock block;
31     std::vector<CAmount> vTxFees;
32     std::vector<int64_t> vTxSigOpsCost;
33     std::vector<unsigned char> vchCoinbaseCommitment;
34 };
35 
36 // Container for tracking updates to ancestor feerate as we include (parent)
37 // transactions in a block
38 struct CTxMemPoolModifiedEntry {
CTxMemPoolModifiedEntryCTxMemPoolModifiedEntry39     explicit CTxMemPoolModifiedEntry(CTxMemPool::txiter entry)
40     {
41         iter = entry;
42         nSizeWithAncestors = entry->GetSizeWithAncestors();
43         nModFeesWithAncestors = entry->GetModFeesWithAncestors();
44         nSigOpCostWithAncestors = entry->GetSigOpCostWithAncestors();
45     }
46 
GetModifiedFeeCTxMemPoolModifiedEntry47     int64_t GetModifiedFee() const { return iter->GetModifiedFee(); }
GetSizeWithAncestorsCTxMemPoolModifiedEntry48     uint64_t GetSizeWithAncestors() const { return nSizeWithAncestors; }
GetModFeesWithAncestorsCTxMemPoolModifiedEntry49     CAmount GetModFeesWithAncestors() const { return nModFeesWithAncestors; }
GetTxSizeCTxMemPoolModifiedEntry50     size_t GetTxSize() const { return iter->GetTxSize(); }
GetTxCTxMemPoolModifiedEntry51     const CTransaction& GetTx() const { return iter->GetTx(); }
52 
53     CTxMemPool::txiter iter;
54     uint64_t nSizeWithAncestors;
55     CAmount nModFeesWithAncestors;
56     int64_t nSigOpCostWithAncestors;
57 };
58 
59 /** Comparator for CTxMemPool::txiter objects.
60  *  It simply compares the internal memory address of the CTxMemPoolEntry object
61  *  pointed to. This means it has no meaning, and is only useful for using them
62  *  as key in other indexes.
63  */
64 struct CompareCTxMemPoolIter {
operatorCompareCTxMemPoolIter65     bool operator()(const CTxMemPool::txiter& a, const CTxMemPool::txiter& b) const
66     {
67         return &(*a) < &(*b);
68     }
69 };
70 
71 struct modifiedentry_iter {
72     typedef CTxMemPool::txiter result_type;
operatormodifiedentry_iter73     result_type operator() (const CTxMemPoolModifiedEntry &entry) const
74     {
75         return entry.iter;
76     }
77 };
78 
79 // A comparator that sorts transactions based on number of ancestors.
80 // This is sufficient to sort an ancestor package in an order that is valid
81 // to appear in a block.
82 struct CompareTxIterByAncestorCount {
operatorCompareTxIterByAncestorCount83     bool operator()(const CTxMemPool::txiter &a, const CTxMemPool::txiter &b) const
84     {
85         if (a->GetCountWithAncestors() != b->GetCountWithAncestors())
86             return a->GetCountWithAncestors() < b->GetCountWithAncestors();
87         return CompareIteratorByHash()(a, b);
88     }
89 };
90 
91 typedef boost::multi_index_container<
92     CTxMemPoolModifiedEntry,
93     boost::multi_index::indexed_by<
94         boost::multi_index::ordered_unique<
95             modifiedentry_iter,
96             CompareCTxMemPoolIter
97         >,
98         // sorted by modified ancestor fee rate
99         boost::multi_index::ordered_non_unique<
100             // Reuse same tag from CTxMemPool's similar index
101             boost::multi_index::tag<ancestor_score>,
102             boost::multi_index::identity<CTxMemPoolModifiedEntry>,
103             CompareTxMemPoolEntryByAncestorFee
104         >
105     >
106 > indexed_modified_transaction_set;
107 
108 typedef indexed_modified_transaction_set::nth_index<0>::type::iterator modtxiter;
109 typedef indexed_modified_transaction_set::index<ancestor_score>::type::iterator modtxscoreiter;
110 
111 struct update_for_parent_inclusion
112 {
update_for_parent_inclusionupdate_for_parent_inclusion113     explicit update_for_parent_inclusion(CTxMemPool::txiter it) : iter(it) {}
114 
operatorupdate_for_parent_inclusion115     void operator() (CTxMemPoolModifiedEntry &e)
116     {
117         e.nModFeesWithAncestors -= iter->GetFee();
118         e.nSizeWithAncestors -= iter->GetTxSize();
119         e.nSigOpCostWithAncestors -= iter->GetSigOpCost();
120     }
121 
122     CTxMemPool::txiter iter;
123 };
124 
125 /** Generate a new block, without valid proof-of-work */
126 class BlockAssembler
127 {
128 private:
129     // The constructed block template
130     std::unique_ptr<CBlockTemplate> pblocktemplate;
131 
132     // Configuration parameters for the block size
133     bool fIncludeWitness;
134     unsigned int nBlockMaxWeight;
135     CFeeRate blockMinFeeRate;
136 
137     // Information on the current status of the block
138     uint64_t nBlockWeight;
139     uint64_t nBlockTx;
140     uint64_t nBlockSigOpsCost;
141     CAmount nFees;
142     CTxMemPool::setEntries inBlock;
143 
144     // Chain context for the block
145     int nHeight;
146     int64_t nLockTimeCutoff;
147     const CChainParams& chainparams;
148     const CTxMemPool& m_mempool;
149     CChainState& m_chainstate;
150 
151 public:
152     struct Options {
153         Options();
154         size_t nBlockMaxWeight;
155         CFeeRate blockMinFeeRate;
156     };
157 
158     explicit BlockAssembler(CChainState& chainstate, const CTxMemPool& mempool, const CChainParams& params);
159     explicit BlockAssembler(CChainState& chainstate, const CTxMemPool& mempool, const CChainParams& params, const Options& options);
160 
161     /** Construct a new block template with coinbase to scriptPubKeyIn */
162     std::unique_ptr<CBlockTemplate> CreateNewBlock(const CScript& scriptPubKeyIn);
163 
164     inline static std::optional<int64_t> m_last_block_num_txs{};
165     inline static std::optional<int64_t> m_last_block_weight{};
166 
167 private:
168     // utility functions
169     /** Clear the block's state and prepare for assembling a new block */
170     void resetBlock();
171     /** Add a tx to the block */
172     void AddToBlock(CTxMemPool::txiter iter);
173 
174     // Methods for how to add transactions to a block.
175     /** Add transactions based on feerate including unconfirmed ancestors
176       * Increments nPackagesSelected / nDescendantsUpdated with corresponding
177       * statistics from the package selection (for logging statistics). */
178     void addPackageTxs(int& nPackagesSelected, int& nDescendantsUpdated) EXCLUSIVE_LOCKS_REQUIRED(m_mempool.cs);
179 
180     // helper functions for addPackageTxs()
181     /** Remove confirmed (inBlock) entries from given set */
182     void onlyUnconfirmed(CTxMemPool::setEntries& testSet);
183     /** Test if a new package would "fit" in the block */
184     bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const;
185     /** Perform checks on each transaction in a package:
186       * locktime, premature-witness, serialized size (if necessary)
187       * These checks should always succeed, and they're here
188       * only as an extra check in case of suboptimal node configuration */
189     bool TestPackageTransactions(const CTxMemPool::setEntries& package) const;
190     /** Return true if given transaction from mapTx has already been evaluated,
191       * or if the transaction's cached data in mapTx is incorrect. */
192     bool SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set& mapModifiedTx, CTxMemPool::setEntries& failedTx) EXCLUSIVE_LOCKS_REQUIRED(m_mempool.cs);
193     /** Sort the package in an order that is valid to appear in a block */
194     void SortForBlock(const CTxMemPool::setEntries& package, std::vector<CTxMemPool::txiter>& sortedEntries);
195     /** Add descendants of given transactions to mapModifiedTx with ancestor
196       * state updated assuming given transactions are inBlock. Returns number
197       * of updated descendants. */
198     int UpdatePackagesForAdded(const CTxMemPool::setEntries& alreadyAdded, indexed_modified_transaction_set& mapModifiedTx) EXCLUSIVE_LOCKS_REQUIRED(m_mempool.cs);
199 };
200 
201 /** Modify the extranonce in a block */
202 void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
203 int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev);
204 
205 /** Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed */
206 void RegenerateCommitments(CBlock& block, ChainstateManager& chainman);
207 
208 #endif // BITCOIN_MINER_H
209