You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

miner.cpp 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. #include "miner.h"
  6. #include "amount.h"
  7. #include "chain.h"
  8. #include "chainparams.h"
  9. #include "coins.h"
  10. #include "consensus/consensus.h"
  11. #include "consensus/merkle.h"
  12. #include "consensus/validation.h"
  13. #include "hash.h"
  14. #include "main.h"
  15. #include "net.h"
  16. #include "policy/policy.h"
  17. #include "pow.h"
  18. #include "primitives/transaction.h"
  19. #include "script/standard.h"
  20. #include "timedata.h"
  21. #include "txmempool.h"
  22. #include "util.h"
  23. #include "utilmoneystr.h"
  24. #include "validationinterface.h"
  25. #include <boost/thread.hpp>
  26. #include <boost/tuple/tuple.hpp>
  27. #include <queue>
  28. using namespace std;
  29. //////////////////////////////////////////////////////////////////////////////
  30. //
  31. // BitcoinMiner
  32. //
  33. //
  34. // Unconfirmed transactions in the memory pool often depend on other
  35. // transactions in the memory pool. When we select transactions from the
  36. // pool, we select by highest priority or fee rate, so we might consider
  37. // transactions that depend on transactions that aren't yet in the block.
  38. uint64_t nLastBlockTx = 0;
  39. uint64_t nLastBlockSize = 0;
  40. class ScoreCompare
  41. {
  42. public:
  43. ScoreCompare() {}
  44. bool operator()(const CTxMemPool::txiter a, const CTxMemPool::txiter b)
  45. {
  46. return CompareTxMemPoolEntryByScore()(*b,*a); // Convert to less than
  47. }
  48. };
  49. int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
  50. {
  51. int64_t nOldTime = pblock->nTime;
  52. int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
  53. if (nOldTime < nNewTime)
  54. pblock->nTime = nNewTime;
  55. // Updating time can change work required on testnet:
  56. if (consensusParams.fPowAllowMinDifficultyBlocks)
  57. pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
  58. return nNewTime - nOldTime;
  59. }
  60. CBlockTemplate* CreateNewBlock(const CChainParams& chainparams, const CScript& scriptPubKeyIn)
  61. {
  62. // Create new block
  63. auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
  64. if(!pblocktemplate.get())
  65. return NULL;
  66. CBlock *pblock = &pblocktemplate->block; // pointer for convenience
  67. // Create coinbase tx
  68. CMutableTransaction txNew;
  69. txNew.vin.resize(1);
  70. txNew.vin[0].prevout.SetNull();
  71. txNew.vout.resize(1);
  72. txNew.vout[0].scriptPubKey = scriptPubKeyIn;
  73. // Add dummy coinbase tx as first transaction
  74. pblock->vtx.push_back(CTransaction());
  75. pblocktemplate->vTxFees.push_back(-1); // updated at end
  76. pblocktemplate->vTxSigOps.push_back(-1); // updated at end
  77. // Largest block you're willing to create:
  78. unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
  79. // Limit to between 1K and MAX_BLOCK_SIZE-1K for sanity:
  80. nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
  81. // How much of the block should be dedicated to high-priority transactions,
  82. // included regardless of the fees they pay
  83. unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
  84. nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
  85. // Minimum block size you want to create; block will be filled with free transactions
  86. // until there are no more or the block reaches this size:
  87. unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
  88. nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
  89. // Collect memory pool transactions into the block
  90. CTxMemPool::setEntries inBlock;
  91. CTxMemPool::setEntries waitSet;
  92. // This vector will be sorted into a priority queue:
  93. vector<TxCoinAgePriority> vecPriority;
  94. TxCoinAgePriorityCompare pricomparer;
  95. std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash> waitPriMap;
  96. typedef std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash>::iterator waitPriIter;
  97. double actualPriority = -1;
  98. std::priority_queue<CTxMemPool::txiter, std::vector<CTxMemPool::txiter>, ScoreCompare> clearedTxs;
  99. bool fPrintPriority = GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
  100. uint64_t nBlockSize = 1000;
  101. uint64_t nBlockTx = 0;
  102. unsigned int nBlockSigOps = 100;
  103. int lastFewTxs = 0;
  104. CAmount nFees = 0;
  105. {
  106. LOCK2(cs_main, mempool.cs);
  107. CBlockIndex* pindexPrev = chainActive.Tip();
  108. const int nHeight = pindexPrev->nHeight + 1;
  109. pblock->nTime = GetAdjustedTime();
  110. const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
  111. pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
  112. // -regtest only: allow overriding block.nVersion with
  113. // -blockversion=N to test forking scenarios
  114. if (chainparams.MineBlocksOnDemand())
  115. pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
  116. int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
  117. ? nMedianTimePast
  118. : pblock->GetBlockTime();
  119. bool fPriorityBlock = nBlockPrioritySize > 0;
  120. if (fPriorityBlock) {
  121. vecPriority.reserve(mempool.mapTx.size());
  122. for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
  123. mi != mempool.mapTx.end(); ++mi)
  124. {
  125. double dPriority = mi->GetPriority(nHeight);
  126. CAmount dummy;
  127. mempool.ApplyDeltas(mi->GetTx().GetHash(), dPriority, dummy);
  128. vecPriority.push_back(TxCoinAgePriority(dPriority, mi));
  129. }
  130. std::make_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
  131. }
  132. CTxMemPool::indexed_transaction_set::index<mining_score>::type::iterator mi = mempool.mapTx.get<mining_score>().begin();
  133. CTxMemPool::txiter iter;
  134. while (mi != mempool.mapTx.get<mining_score>().end() || !clearedTxs.empty())
  135. {
  136. bool priorityTx = false;
  137. if (fPriorityBlock && !vecPriority.empty()) { // add a tx from priority queue to fill the blockprioritysize
  138. priorityTx = true;
  139. iter = vecPriority.front().second;
  140. actualPriority = vecPriority.front().first;
  141. std::pop_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
  142. vecPriority.pop_back();
  143. }
  144. else if (clearedTxs.empty()) { // add tx with next highest score
  145. iter = mempool.mapTx.project<0>(mi);
  146. mi++;
  147. }
  148. else { // try to add a previously postponed child tx
  149. iter = clearedTxs.top();
  150. clearedTxs.pop();
  151. }
  152. if (inBlock.count(iter))
  153. continue; // could have been added to the priorityBlock
  154. const CTransaction& tx = iter->GetTx();
  155. bool fOrphan = false;
  156. BOOST_FOREACH(CTxMemPool::txiter parent, mempool.GetMemPoolParents(iter))
  157. {
  158. if (!inBlock.count(parent)) {
  159. fOrphan = true;
  160. break;
  161. }
  162. }
  163. if (fOrphan) {
  164. if (priorityTx)
  165. waitPriMap.insert(std::make_pair(iter,actualPriority));
  166. else
  167. waitSet.insert(iter);
  168. continue;
  169. }
  170. unsigned int nTxSize = iter->GetTxSize();
  171. if (fPriorityBlock &&
  172. (nBlockSize + nTxSize >= nBlockPrioritySize || !AllowFree(actualPriority))) {
  173. fPriorityBlock = false;
  174. waitPriMap.clear();
  175. }
  176. if (!priorityTx &&
  177. (iter->GetModifiedFee() < ::minRelayTxFee.GetFee(nTxSize) && nBlockSize >= nBlockMinSize)) {
  178. break;
  179. }
  180. if (nBlockSize + nTxSize >= nBlockMaxSize) {
  181. if (nBlockSize > nBlockMaxSize - 100 || lastFewTxs > 50) {
  182. break;
  183. }
  184. // Once we're within 1000 bytes of a full block, only look at 50 more txs
  185. // to try to fill the remaining space.
  186. if (nBlockSize > nBlockMaxSize - 1000) {
  187. lastFewTxs++;
  188. }
  189. continue;
  190. }
  191. if (!IsFinalTx(tx, nHeight, nLockTimeCutoff))
  192. continue;
  193. unsigned int nTxSigOps = iter->GetSigOpCount();
  194. if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) {
  195. if (nBlockSigOps > MAX_BLOCK_SIGOPS - 2) {
  196. break;
  197. }
  198. continue;
  199. }
  200. CAmount nTxFees = iter->GetFee();
  201. // Added
  202. pblock->vtx.push_back(tx);
  203. pblocktemplate->vTxFees.push_back(nTxFees);
  204. pblocktemplate->vTxSigOps.push_back(nTxSigOps);
  205. nBlockSize += nTxSize;
  206. ++nBlockTx;
  207. nBlockSigOps += nTxSigOps;
  208. nFees += nTxFees;
  209. if (fPrintPriority)
  210. {
  211. double dPriority = iter->GetPriority(nHeight);
  212. CAmount dummy;
  213. mempool.ApplyDeltas(tx.GetHash(), dPriority, dummy);
  214. LogPrintf("priority %.1f fee %s txid %s\n",
  215. dPriority , CFeeRate(iter->GetModifiedFee(), nTxSize).ToString(), tx.GetHash().ToString());
  216. }
  217. inBlock.insert(iter);
  218. // Add transactions that depend on this one to the priority queue
  219. BOOST_FOREACH(CTxMemPool::txiter child, mempool.GetMemPoolChildren(iter))
  220. {
  221. if (fPriorityBlock) {
  222. waitPriIter wpiter = waitPriMap.find(child);
  223. if (wpiter != waitPriMap.end()) {
  224. vecPriority.push_back(TxCoinAgePriority(wpiter->second,child));
  225. std::push_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
  226. waitPriMap.erase(wpiter);
  227. }
  228. }
  229. else {
  230. if (waitSet.count(child)) {
  231. clearedTxs.push(child);
  232. waitSet.erase(child);
  233. }
  234. }
  235. }
  236. }
  237. nLastBlockTx = nBlockTx;
  238. nLastBlockSize = nBlockSize;
  239. LogPrintf("CreateNewBlock(): total size %u txs: %u fees: %ld sigops %d\n", nBlockSize, nBlockTx, nFees, nBlockSigOps);
  240. // Compute final coinbase transaction.
  241. txNew.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
  242. txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
  243. pblock->vtx[0] = txNew;
  244. pblocktemplate->vTxFees[0] = -nFees;
  245. // Fill in header
  246. pblock->hashPrevBlock = pindexPrev->GetBlockHash();
  247. UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
  248. pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
  249. pblock->nNonce = 0;
  250. pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
  251. CValidationState state;
  252. if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
  253. throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
  254. }
  255. }
  256. return pblocktemplate.release();
  257. }
  258. void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
  259. {
  260. // Update nExtraNonce
  261. static uint256 hashPrevBlock;
  262. if (hashPrevBlock != pblock->hashPrevBlock)
  263. {
  264. nExtraNonce = 0;
  265. hashPrevBlock = pblock->hashPrevBlock;
  266. }
  267. ++nExtraNonce;
  268. unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
  269. CMutableTransaction txCoinbase(pblock->vtx[0]);
  270. txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
  271. assert(txCoinbase.vin[0].scriptSig.size() <= 100);
  272. pblock->vtx[0] = txCoinbase;
  273. pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
  274. }