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 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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. // -regtest only: allow overriding block.nVersion with
  68. // -blockversion=N to test forking scenarios
  69. if (chainparams.MineBlocksOnDemand())
  70. pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
  71. // Create coinbase tx
  72. CMutableTransaction txNew;
  73. txNew.vin.resize(1);
  74. txNew.vin[0].prevout.SetNull();
  75. txNew.vout.resize(1);
  76. txNew.vout[0].scriptPubKey = scriptPubKeyIn;
  77. // Add dummy coinbase tx as first transaction
  78. pblock->vtx.push_back(CTransaction());
  79. pblocktemplate->vTxFees.push_back(-1); // updated at end
  80. pblocktemplate->vTxSigOps.push_back(-1); // updated at end
  81. // Largest block you're willing to create:
  82. unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
  83. // Limit to between 1K and MAX_BLOCK_SIZE-1K for sanity:
  84. nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
  85. // How much of the block should be dedicated to high-priority transactions,
  86. // included regardless of the fees they pay
  87. unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
  88. nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
  89. // Minimum block size you want to create; block will be filled with free transactions
  90. // until there are no more or the block reaches this size:
  91. unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
  92. nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
  93. // Collect memory pool transactions into the block
  94. CTxMemPool::setEntries inBlock;
  95. CTxMemPool::setEntries waitSet;
  96. // This vector will be sorted into a priority queue:
  97. vector<TxCoinAgePriority> vecPriority;
  98. TxCoinAgePriorityCompare pricomparer;
  99. std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash> waitPriMap;
  100. typedef std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash>::iterator waitPriIter;
  101. double actualPriority = -1;
  102. std::priority_queue<CTxMemPool::txiter, std::vector<CTxMemPool::txiter>, ScoreCompare> clearedTxs;
  103. bool fPrintPriority = GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
  104. uint64_t nBlockSize = 1000;
  105. uint64_t nBlockTx = 0;
  106. unsigned int nBlockSigOps = 100;
  107. int lastFewTxs = 0;
  108. CAmount nFees = 0;
  109. {
  110. LOCK2(cs_main, mempool.cs);
  111. CBlockIndex* pindexPrev = chainActive.Tip();
  112. const int nHeight = pindexPrev->nHeight + 1;
  113. pblock->nTime = GetAdjustedTime();
  114. const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
  115. int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
  116. ? nMedianTimePast
  117. : pblock->GetBlockTime();
  118. bool fPriorityBlock = nBlockPrioritySize > 0;
  119. if (fPriorityBlock) {
  120. vecPriority.reserve(mempool.mapTx.size());
  121. for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
  122. mi != mempool.mapTx.end(); ++mi)
  123. {
  124. double dPriority = mi->GetPriority(nHeight);
  125. CAmount dummy;
  126. mempool.ApplyDeltas(mi->GetTx().GetHash(), dPriority, dummy);
  127. vecPriority.push_back(TxCoinAgePriority(dPriority, mi));
  128. }
  129. std::make_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
  130. }
  131. CTxMemPool::indexed_transaction_set::nth_index<3>::type::iterator mi = mempool.mapTx.get<3>().begin();
  132. CTxMemPool::txiter iter;
  133. while (mi != mempool.mapTx.get<3>().end() || !clearedTxs.empty())
  134. {
  135. bool priorityTx = false;
  136. if (fPriorityBlock && !vecPriority.empty()) { // add a tx from priority queue to fill the blockprioritysize
  137. priorityTx = true;
  138. iter = vecPriority.front().second;
  139. actualPriority = vecPriority.front().first;
  140. std::pop_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
  141. vecPriority.pop_back();
  142. }
  143. else if (clearedTxs.empty()) { // add tx with next highest score
  144. iter = mempool.mapTx.project<0>(mi);
  145. mi++;
  146. }
  147. else { // try to add a previously postponed child tx
  148. iter = clearedTxs.top();
  149. clearedTxs.pop();
  150. }
  151. if (inBlock.count(iter))
  152. continue; // could have been added to the priorityBlock
  153. const CTransaction& tx = iter->GetTx();
  154. bool fOrphan = false;
  155. BOOST_FOREACH(CTxMemPool::txiter parent, mempool.GetMemPoolParents(iter))
  156. {
  157. if (!inBlock.count(parent)) {
  158. fOrphan = true;
  159. break;
  160. }
  161. }
  162. if (fOrphan) {
  163. if (priorityTx)
  164. waitPriMap.insert(std::make_pair(iter,actualPriority));
  165. else
  166. waitSet.insert(iter);
  167. continue;
  168. }
  169. unsigned int nTxSize = iter->GetTxSize();
  170. if (fPriorityBlock &&
  171. (nBlockSize + nTxSize >= nBlockPrioritySize || !AllowFree(actualPriority))) {
  172. fPriorityBlock = false;
  173. waitPriMap.clear();
  174. }
  175. if (!priorityTx &&
  176. (iter->GetModifiedFee() < ::minRelayTxFee.GetFee(nTxSize) && nBlockSize >= nBlockMinSize)) {
  177. break;
  178. }
  179. if (nBlockSize + nTxSize >= nBlockMaxSize) {
  180. if (nBlockSize > nBlockMaxSize - 100 || lastFewTxs > 50) {
  181. break;
  182. }
  183. // Once we're within 1000 bytes of a full block, only look at 50 more txs
  184. // to try to fill the remaining space.
  185. if (nBlockSize > nBlockMaxSize - 1000) {
  186. lastFewTxs++;
  187. }
  188. continue;
  189. }
  190. if (!IsFinalTx(tx, nHeight, nLockTimeCutoff))
  191. continue;
  192. unsigned int nTxSigOps = iter->GetSigOpCount();
  193. if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) {
  194. if (nBlockSigOps > MAX_BLOCK_SIGOPS - 2) {
  195. break;
  196. }
  197. continue;
  198. }
  199. CAmount nTxFees = iter->GetFee();
  200. // Added
  201. pblock->vtx.push_back(tx);
  202. pblocktemplate->vTxFees.push_back(nTxFees);
  203. pblocktemplate->vTxSigOps.push_back(nTxSigOps);
  204. nBlockSize += nTxSize;
  205. ++nBlockTx;
  206. nBlockSigOps += nTxSigOps;
  207. nFees += nTxFees;
  208. if (fPrintPriority)
  209. {
  210. double dPriority = iter->GetPriority(nHeight);
  211. CAmount dummy;
  212. mempool.ApplyDeltas(tx.GetHash(), dPriority, dummy);
  213. LogPrintf("priority %.1f fee %s txid %s\n",
  214. dPriority , CFeeRate(iter->GetModifiedFee(), nTxSize).ToString(), tx.GetHash().ToString());
  215. }
  216. inBlock.insert(iter);
  217. // Add transactions that depend on this one to the priority queue
  218. BOOST_FOREACH(CTxMemPool::txiter child, mempool.GetMemPoolChildren(iter))
  219. {
  220. if (fPriorityBlock) {
  221. waitPriIter wpiter = waitPriMap.find(child);
  222. if (wpiter != waitPriMap.end()) {
  223. vecPriority.push_back(TxCoinAgePriority(wpiter->second,child));
  224. std::push_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
  225. waitPriMap.erase(wpiter);
  226. }
  227. }
  228. else {
  229. if (waitSet.count(child)) {
  230. clearedTxs.push(child);
  231. waitSet.erase(child);
  232. }
  233. }
  234. }
  235. }
  236. nLastBlockTx = nBlockTx;
  237. nLastBlockSize = nBlockSize;
  238. LogPrintf("CreateNewBlock(): total size %u txs: %u fees: %ld sigops %d\n", nBlockSize, nBlockTx, nFees, nBlockSigOps);
  239. // Compute final coinbase transaction.
  240. txNew.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
  241. txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
  242. pblock->vtx[0] = txNew;
  243. pblocktemplate->vTxFees[0] = -nFees;
  244. // Fill in header
  245. pblock->hashPrevBlock = pindexPrev->GetBlockHash();
  246. UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
  247. pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
  248. pblock->nNonce = 0;
  249. pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
  250. CValidationState state;
  251. if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
  252. throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
  253. }
  254. }
  255. return pblocktemplate.release();
  256. }
  257. void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
  258. {
  259. // Update nExtraNonce
  260. static uint256 hashPrevBlock;
  261. if (hashPrevBlock != pblock->hashPrevBlock)
  262. {
  263. nExtraNonce = 0;
  264. hashPrevBlock = pblock->hashPrevBlock;
  265. }
  266. ++nExtraNonce;
  267. unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
  268. CMutableTransaction txCoinbase(pblock->vtx[0]);
  269. txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
  270. assert(txCoinbase.vin[0].scriptSig.size() <= 100);
  271. pblock->vtx[0] = txCoinbase;
  272. pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
  273. }
  274. //////////////////////////////////////////////////////////////////////////////
  275. //
  276. // Internal miner
  277. //
  278. //
  279. // ScanHash scans nonces looking for a hash with at least some zero bits.
  280. // The nonce is usually preserved between calls, but periodically or if the
  281. // nonce is 0xffff0000 or above, the block is rebuilt and nNonce starts over at
  282. // zero.
  283. //
  284. bool static ScanHash(const CBlockHeader *pblock, uint32_t& nNonce, uint256 *phash)
  285. {
  286. // Write the first 76 bytes of the block header to a double-SHA256 state.
  287. CHash256 hasher;
  288. CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
  289. ss << *pblock;
  290. assert(ss.size() == 80);
  291. hasher.Write((unsigned char*)&ss[0], 76);
  292. while (true) {
  293. nNonce++;
  294. // Write the last 4 bytes of the block header (the nonce) to a copy of
  295. // the double-SHA256 state, and compute the result.
  296. CHash256(hasher).Write((unsigned char*)&nNonce, 4).Finalize((unsigned char*)phash);
  297. // Return the nonce if the hash has at least some zero bits,
  298. // caller will check if it has enough to reach the target
  299. if (((uint16_t*)phash)[15] == 0)
  300. return true;
  301. // If nothing found after trying for a while, return -1
  302. if ((nNonce & 0xfff) == 0)
  303. return false;
  304. }
  305. }
  306. static bool ProcessBlockFound(const CBlock* pblock, const CChainParams& chainparams)
  307. {
  308. LogPrintf("%s\n", pblock->ToString());
  309. LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue));
  310. // Found a solution
  311. {
  312. LOCK(cs_main);
  313. if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
  314. return error("BitcoinMiner: generated block is stale");
  315. }
  316. // Inform about the new block
  317. GetMainSignals().BlockFound(pblock->GetHash());
  318. // Process this block the same as if we had received it from another node
  319. CValidationState state;
  320. if (!ProcessNewBlock(state, chainparams, NULL, pblock, true, NULL))
  321. return error("BitcoinMiner: ProcessNewBlock, block not accepted");
  322. return true;
  323. }
  324. void static BitcoinMiner(const CChainParams& chainparams)
  325. {
  326. LogPrintf("BitcoinMiner started\n");
  327. SetThreadPriority(THREAD_PRIORITY_LOWEST);
  328. RenameThread("bitcoin-miner");
  329. unsigned int nExtraNonce = 0;
  330. boost::shared_ptr<CReserveScript> coinbaseScript;
  331. GetMainSignals().ScriptForMining(coinbaseScript);
  332. try {
  333. // Throw an error if no script was provided. This can happen
  334. // due to some internal error but also if the keypool is empty.
  335. // In the latter case, already the pointer is NULL.
  336. if (!coinbaseScript || coinbaseScript->reserveScript.empty())
  337. throw std::runtime_error("No coinbase script available (mining requires a wallet)");
  338. while (true) {
  339. if (chainparams.MiningRequiresPeers()) {
  340. // Busy-wait for the network to come online so we don't waste time mining
  341. // on an obsolete chain. In regtest mode we expect to fly solo.
  342. do {
  343. bool fvNodesEmpty;
  344. {
  345. LOCK(cs_vNodes);
  346. fvNodesEmpty = vNodes.empty();
  347. }
  348. if (!fvNodesEmpty && !IsInitialBlockDownload())
  349. break;
  350. MilliSleep(1000);
  351. } while (true);
  352. }
  353. //
  354. // Create new block
  355. //
  356. unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
  357. CBlockIndex* pindexPrev = chainActive.Tip();
  358. auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlock(chainparams, coinbaseScript->reserveScript));
  359. if (!pblocktemplate.get())
  360. {
  361. LogPrintf("Error in BitcoinMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
  362. return;
  363. }
  364. CBlock *pblock = &pblocktemplate->block;
  365. IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
  366. LogPrintf("Running BitcoinMiner with %u transactions in block (%u bytes)\n", pblock->vtx.size(),
  367. ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
  368. //
  369. // Search
  370. //
  371. int64_t nStart = GetTime();
  372. arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
  373. uint256 hash;
  374. uint32_t nNonce = 0;
  375. while (true) {
  376. // Check if something found
  377. if (ScanHash(pblock, nNonce, &hash))
  378. {
  379. if (UintToArith256(hash) <= hashTarget)
  380. {
  381. // Found a solution
  382. pblock->nNonce = nNonce;
  383. assert(hash == pblock->GetHash());
  384. SetThreadPriority(THREAD_PRIORITY_NORMAL);
  385. LogPrintf("BitcoinMiner:\n");
  386. LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex(), hashTarget.GetHex());
  387. ProcessBlockFound(pblock, chainparams);
  388. SetThreadPriority(THREAD_PRIORITY_LOWEST);
  389. coinbaseScript->KeepScript();
  390. // In regression test mode, stop mining after a block is found.
  391. if (chainparams.MineBlocksOnDemand())
  392. throw boost::thread_interrupted();
  393. break;
  394. }
  395. }
  396. // Check for stop or if block needs to be rebuilt
  397. boost::this_thread::interruption_point();
  398. // Regtest mode doesn't require peers
  399. if (vNodes.empty() && chainparams.MiningRequiresPeers())
  400. break;
  401. if (nNonce >= 0xffff0000)
  402. break;
  403. if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
  404. break;
  405. if (pindexPrev != chainActive.Tip())
  406. break;
  407. // Update nTime every few seconds
  408. if (UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev) < 0)
  409. break; // Recreate the block if the clock has run backwards,
  410. // so that we can use the correct time.
  411. if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
  412. {
  413. // Changing pblock->nTime can change work required on testnet:
  414. hashTarget.SetCompact(pblock->nBits);
  415. }
  416. }
  417. }
  418. }
  419. catch (const boost::thread_interrupted&)
  420. {
  421. LogPrintf("BitcoinMiner terminated\n");
  422. throw;
  423. }
  424. catch (const std::runtime_error &e)
  425. {
  426. LogPrintf("BitcoinMiner runtime error: %s\n", e.what());
  427. return;
  428. }
  429. }
  430. void GenerateBitcoins(bool fGenerate, int nThreads, const CChainParams& chainparams)
  431. {
  432. static boost::thread_group* minerThreads = NULL;
  433. if (nThreads < 0)
  434. nThreads = GetNumCores();
  435. if (minerThreads != NULL)
  436. {
  437. minerThreads->interrupt_all();
  438. delete minerThreads;
  439. minerThreads = NULL;
  440. }
  441. if (nThreads == 0 || !fGenerate)
  442. return;
  443. minerThreads = new boost::thread_group();
  444. for (int i = 0; i < nThreads; i++)
  445. minerThreads->create_thread(boost::bind(&BitcoinMiner, boost::cref(chainparams)));
  446. }