1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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 
12 #include <stdint.h>
13 #include <memory>
14 #include "boost/multi_index_container.hpp"
15 #include "boost/multi_index/ordered_index.hpp"
16 
17 class CBlockIndex;
18 class CChainParams;
19 class CReserveKey;
20 class CScript;
21 class CWallet;
22 
23 namespace Consensus { struct Params; };
24 
25 static const bool DEFAULT_PRINTPRIORITY = false;
26 
27 struct CBlockTemplate
28 {
29     CBlock block;
30     std::vector<CAmount> vTxFees;
31     std::vector<int64_t> vTxSigOpsCost;
32     std::vector<unsigned char> vchCoinbaseCommitment;
33 };
34 
35 // Container for tracking updates to ancestor feerate as we include (parent)
36 // transactions in a block
37 struct CTxMemPoolModifiedEntry {
CTxMemPoolModifiedEntryCTxMemPoolModifiedEntry38     CTxMemPoolModifiedEntry(CTxMemPool::txiter entry)
39     {
40         iter = entry;
41         nSizeWithAncestors = entry->GetSizeWithAncestors();
42         nModFeesWithAncestors = entry->GetModFeesWithAncestors();
43         nSigOpCostWithAncestors = entry->GetSigOpCostWithAncestors();
44     }
45 
46     CTxMemPool::txiter iter;
47     uint64_t nSizeWithAncestors;
48     CAmount nModFeesWithAncestors;
49     int64_t nSigOpCostWithAncestors;
50 };
51 
52 /** Comparator for CTxMemPool::txiter objects.
53  *  It simply compares the internal memory address of the CTxMemPoolEntry object
54  *  pointed to. This means it has no meaning, and is only useful for using them
55  *  as key in other indexes.
56  */
57 struct CompareCTxMemPoolIter {
operatorCompareCTxMemPoolIter58     bool operator()(const CTxMemPool::txiter& a, const CTxMemPool::txiter& b) const
59     {
60         return &(*a) < &(*b);
61     }
62 };
63 
64 struct modifiedentry_iter {
65     typedef CTxMemPool::txiter result_type;
operatormodifiedentry_iter66     result_type operator() (const CTxMemPoolModifiedEntry &entry) const
67     {
68         return entry.iter;
69     }
70 };
71 
72 // This matches the calculation in CompareTxMemPoolEntryByAncestorFee,
73 // except operating on CTxMemPoolModifiedEntry.
74 // TODO: refactor to avoid duplication of this logic.
75 struct CompareModifiedEntry {
operatorCompareModifiedEntry76     bool operator()(const CTxMemPoolModifiedEntry &a, const CTxMemPoolModifiedEntry &b) const
77     {
78         double f1 = (double)a.nModFeesWithAncestors * b.nSizeWithAncestors;
79         double f2 = (double)b.nModFeesWithAncestors * a.nSizeWithAncestors;
80         if (f1 == f2) {
81             return CTxMemPool::CompareIteratorByHash()(a.iter, b.iter);
82         }
83         return f1 > f2;
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.
90 struct CompareTxIterByAncestorCount {
operatorCompareTxIterByAncestorCount91     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         return CTxMemPool::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>,
111             CompareModifiedEntry
112         >
113     >
114 > indexed_modified_transaction_set;
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 
119 struct update_for_parent_inclusion
120 {
update_for_parent_inclusionupdate_for_parent_inclusion121     update_for_parent_inclusion(CTxMemPool::txiter it) : iter(it) {}
122 
operatorupdate_for_parent_inclusion123     void operator() (CTxMemPoolModifiedEntry &e)
124     {
125         e.nModFeesWithAncestors -= iter->GetFee();
126         e.nSizeWithAncestors -= iter->GetTxSize();
127         e.nSigOpCostWithAncestors -= iter->GetSigOpCost();
128     }
129 
130     CTxMemPool::txiter iter;
131 };
132 
133 /** Generate a new block, without valid proof-of-work */
134 class BlockAssembler
135 {
136 private:
137     // The constructed block template
138     std::unique_ptr<CBlockTemplate> pblocktemplate;
139     // A convenience pointer that always refers to the CBlock in pblocktemplate
140     CBlock* pblock;
141 
142     // Configuration parameters for the block size
143     bool fIncludeWitness;
144     unsigned int nBlockMaxWeight, nBlockMaxSize;
145     bool fNeedSizeAccounting;
146 
147     // Information on the current status of the block
148     uint64_t nBlockWeight;
149     uint64_t nBlockSize;
150     uint64_t nBlockTx;
151     uint64_t nBlockSigOpsCost;
152     CAmount nFees;
153     CTxMemPool::setEntries inBlock;
154 
155     // Chain context for the block
156     int nHeight;
157     int64_t nLockTimeCutoff;
158     const CChainParams& chainparams;
159 
160     // Variables used for addPriorityTxs
161     int lastFewTxs;
162     bool blockFinished;
163 
164 public:
165     BlockAssembler(const CChainParams& chainparams);
166     /** Construct a new block template with coinbase to scriptPubKeyIn */
167     CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn);
168 
169 private:
170     // utility functions
171     /** Clear the block's state and prepare for assembling a new block */
172     void resetBlock();
173     /** Add a tx to the block */
174     void AddToBlock(CTxMemPool::txiter iter);
175 
176     // Methods for how to add transactions to a block.
177     /** Add transactions based on tx "priority" */
178     void addPriorityTxs();
179     /** Add transactions based on feerate including unconfirmed ancestors */
180     void addPackageTxs();
181 
182     // helper function for addPriorityTxs
183     /** Test if tx will still "fit" in the block */
184     bool TestForBlock(CTxMemPool::txiter iter);
185     /** Test if tx still has unconfirmed parents not yet in block */
186     bool isStillDependent(CTxMemPool::txiter iter);
187 
188     // helper functions for addPackageTxs()
189     /** Remove confirmed (inBlock) entries from given set */
190     void onlyUnconfirmed(CTxMemPool::setEntries& testSet);
191     /** Test if a new package would "fit" in the block */
192     bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost);
193     /** Perform checks on each transaction in a package:
194       * locktime, premature-witness, serialized size (if necessary)
195       * These checks should always succeed, and they're here
196       * only as an extra check in case of suboptimal node configuration */
197     bool TestPackageTransactions(const CTxMemPool::setEntries& package);
198     /** Return true if given transaction from mapTx has already been evaluated,
199       * or if the transaction's cached data in mapTx is incorrect. */
200     bool SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx);
201     /** Sort the package in an order that is valid to appear in a block */
202     void SortForBlock(const CTxMemPool::setEntries& package, CTxMemPool::txiter entry, std::vector<CTxMemPool::txiter>& sortedEntries);
203     /** Add descendants of given transactions to mapModifiedTx with ancestor
204       * state updated assuming given transactions are inBlock. */
205     void UpdatePackagesForAdded(const CTxMemPool::setEntries& alreadyAdded, indexed_modified_transaction_set &mapModifiedTx);
206 };
207 
208 /** Modify the extranonce in a block */
209 void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
210 int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev);
211 
212 #endif // BITCOIN_MINER_H
213