選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

miner.cpp 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2014 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 "chainparams.h"
  8. #include "consensus/consensus.h"
  9. #include "hash.h"
  10. #include "main.h"
  11. #include "net.h"
  12. #include "pow.h"
  13. #include "primitives/transaction.h"
  14. #include "timedata.h"
  15. #include "util.h"
  16. #include "utilmoneystr.h"
  17. #ifdef ENABLE_WALLET
  18. #include "wallet/wallet.h"
  19. #endif
  20. #include <boost/thread.hpp>
  21. #include <boost/tuple/tuple.hpp>
  22. using namespace std;
  23. //////////////////////////////////////////////////////////////////////////////
  24. //
  25. // BitcoinMiner
  26. //
  27. //
  28. // Unconfirmed transactions in the memory pool often depend on other
  29. // transactions in the memory pool. When we select transactions from the
  30. // pool, we select by highest priority or fee rate, so we might consider
  31. // transactions that depend on transactions that aren't yet in the block.
  32. // The COrphan class keeps track of these 'temporary orphans' while
  33. // CreateBlock is figuring out which transactions to include.
  34. //
  35. class COrphan
  36. {
  37. public:
  38. const CTransaction* ptx;
  39. set<uint256> setDependsOn;
  40. CFeeRate feeRate;
  41. double dPriority;
  42. COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
  43. {
  44. }
  45. };
  46. uint64_t nLastBlockTx = 0;
  47. uint64_t nLastBlockSize = 0;
  48. // We want to sort transactions by priority and fee rate, so:
  49. typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
  50. class TxPriorityCompare
  51. {
  52. bool byFee;
  53. public:
  54. TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
  55. bool operator()(const TxPriority& a, const TxPriority& b)
  56. {
  57. if (byFee)
  58. {
  59. if (a.get<1>() == b.get<1>())
  60. return a.get<0>() < b.get<0>();
  61. return a.get<1>() < b.get<1>();
  62. }
  63. else
  64. {
  65. if (a.get<0>() == b.get<0>())
  66. return a.get<1>() < b.get<1>();
  67. return a.get<0>() < b.get<0>();
  68. }
  69. }
  70. };
  71. void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
  72. {
  73. pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
  74. // Updating time can change work required on testnet:
  75. if (consensusParams.fPowAllowMinDifficultyBlocks)
  76. pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
  77. }
  78. CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
  79. {
  80. const CChainParams& chainparams = Params();
  81. // Create new block
  82. auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
  83. if(!pblocktemplate.get())
  84. return NULL;
  85. CBlock *pblock = &pblocktemplate->block; // pointer for convenience
  86. // -regtest only: allow overriding block.nVersion with
  87. // -blockversion=N to test forking scenarios
  88. if (Params().MineBlocksOnDemand())
  89. pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
  90. // Create coinbase tx
  91. CMutableTransaction txNew;
  92. txNew.vin.resize(1);
  93. txNew.vin[0].prevout.SetNull();
  94. txNew.vout.resize(1);
  95. txNew.vout[0].scriptPubKey = scriptPubKeyIn;
  96. // Add dummy coinbase tx as first transaction
  97. pblock->vtx.push_back(CTransaction());
  98. pblocktemplate->vTxFees.push_back(-1); // updated at end
  99. pblocktemplate->vTxSigOps.push_back(-1); // updated at end
  100. // Largest block you're willing to create:
  101. unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
  102. // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
  103. nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
  104. // How much of the block should be dedicated to high-priority transactions,
  105. // included regardless of the fees they pay
  106. unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
  107. nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
  108. // Minimum block size you want to create; block will be filled with free transactions
  109. // until there are no more or the block reaches this size:
  110. unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
  111. nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
  112. // Collect memory pool transactions into the block
  113. CAmount nFees = 0;
  114. {
  115. LOCK2(cs_main, mempool.cs);
  116. CBlockIndex* pindexPrev = chainActive.Tip();
  117. const int nHeight = pindexPrev->nHeight + 1;
  118. CCoinsViewCache view(pcoinsTip);
  119. // Priority order to process transactions
  120. list<COrphan> vOrphan; // list memory doesn't move
  121. map<uint256, vector<COrphan*> > mapDependers;
  122. bool fPrintPriority = GetBoolArg("-printpriority", false);
  123. // This vector will be sorted into a priority queue:
  124. vector<TxPriority> vecPriority;
  125. vecPriority.reserve(mempool.mapTx.size());
  126. for (map<uint256, CTxMemPoolEntry>::iterator mi = mempool.mapTx.begin();
  127. mi != mempool.mapTx.end(); ++mi)
  128. {
  129. const CTransaction& tx = mi->second.GetTx();
  130. if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight))
  131. continue;
  132. COrphan* porphan = NULL;
  133. double dPriority = 0;
  134. CAmount nTotalIn = 0;
  135. bool fMissingInputs = false;
  136. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  137. {
  138. // Read prev transaction
  139. if (!view.HaveCoins(txin.prevout.hash))
  140. {
  141. // This should never happen; all transactions in the memory
  142. // pool should connect to either transactions in the chain
  143. // or other transactions in the memory pool.
  144. if (!mempool.mapTx.count(txin.prevout.hash))
  145. {
  146. LogPrintf("ERROR: mempool transaction missing input\n");
  147. if (fDebug) assert("mempool transaction missing input" == 0);
  148. fMissingInputs = true;
  149. if (porphan)
  150. vOrphan.pop_back();
  151. break;
  152. }
  153. // Has to wait for dependencies
  154. if (!porphan)
  155. {
  156. // Use list for automatic deletion
  157. vOrphan.push_back(COrphan(&tx));
  158. porphan = &vOrphan.back();
  159. }
  160. mapDependers[txin.prevout.hash].push_back(porphan);
  161. porphan->setDependsOn.insert(txin.prevout.hash);
  162. nTotalIn += mempool.mapTx[txin.prevout.hash].GetTx().vout[txin.prevout.n].nValue;
  163. continue;
  164. }
  165. const CCoins* coins = view.AccessCoins(txin.prevout.hash);
  166. assert(coins);
  167. CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
  168. nTotalIn += nValueIn;
  169. int nConf = nHeight - coins->nHeight;
  170. dPriority += (double)nValueIn * nConf;
  171. }
  172. if (fMissingInputs) continue;
  173. // Priority is sum(valuein * age) / modified_txsize
  174. unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
  175. dPriority = tx.ComputePriority(dPriority, nTxSize);
  176. uint256 hash = tx.GetHash();
  177. mempool.ApplyDeltas(hash, dPriority, nTotalIn);
  178. CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
  179. if (porphan)
  180. {
  181. porphan->dPriority = dPriority;
  182. porphan->feeRate = feeRate;
  183. }
  184. else
  185. vecPriority.push_back(TxPriority(dPriority, feeRate, &mi->second.GetTx()));
  186. }
  187. // Collect transactions into block
  188. uint64_t nBlockSize = 1000;
  189. uint64_t nBlockTx = 0;
  190. int nBlockSigOps = 100;
  191. bool fSortedByFee = (nBlockPrioritySize <= 0);
  192. TxPriorityCompare comparer(fSortedByFee);
  193. std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
  194. while (!vecPriority.empty())
  195. {
  196. // Take highest priority transaction off the priority queue:
  197. double dPriority = vecPriority.front().get<0>();
  198. CFeeRate feeRate = vecPriority.front().get<1>();
  199. const CTransaction& tx = *(vecPriority.front().get<2>());
  200. std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
  201. vecPriority.pop_back();
  202. // Size limits
  203. unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
  204. if (nBlockSize + nTxSize >= nBlockMaxSize)
  205. continue;
  206. // Legacy limits on sigOps:
  207. unsigned int nTxSigOps = GetLegacySigOpCount(tx);
  208. if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
  209. continue;
  210. // Skip free transactions if we're past the minimum block size:
  211. const uint256& hash = tx.GetHash();
  212. double dPriorityDelta = 0;
  213. CAmount nFeeDelta = 0;
  214. mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
  215. if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
  216. continue;
  217. // Prioritise by fee once past the priority size or we run out of high-priority
  218. // transactions:
  219. if (!fSortedByFee &&
  220. ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
  221. {
  222. fSortedByFee = true;
  223. comparer = TxPriorityCompare(fSortedByFee);
  224. std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
  225. }
  226. if (!view.HaveInputs(tx))
  227. continue;
  228. CAmount nTxFees = view.GetValueIn(tx)-tx.GetValueOut();
  229. nTxSigOps += GetP2SHSigOpCount(tx, view);
  230. if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
  231. continue;
  232. // Note that flags: we don't want to set mempool/IsStandard()
  233. // policy here, but we still have to ensure that the block we
  234. // create only contains transactions that are valid in new blocks.
  235. CValidationState state;
  236. if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true))
  237. continue;
  238. UpdateCoins(tx, state, view, nHeight);
  239. // Added
  240. pblock->vtx.push_back(tx);
  241. pblocktemplate->vTxFees.push_back(nTxFees);
  242. pblocktemplate->vTxSigOps.push_back(nTxSigOps);
  243. nBlockSize += nTxSize;
  244. ++nBlockTx;
  245. nBlockSigOps += nTxSigOps;
  246. nFees += nTxFees;
  247. if (fPrintPriority)
  248. {
  249. LogPrintf("priority %.1f fee %s txid %s\n",
  250. dPriority, feeRate.ToString(), tx.GetHash().ToString());
  251. }
  252. // Add transactions that depend on this one to the priority queue
  253. if (mapDependers.count(hash))
  254. {
  255. BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
  256. {
  257. if (!porphan->setDependsOn.empty())
  258. {
  259. porphan->setDependsOn.erase(hash);
  260. if (porphan->setDependsOn.empty())
  261. {
  262. vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
  263. std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
  264. }
  265. }
  266. }
  267. }
  268. }
  269. nLastBlockTx = nBlockTx;
  270. nLastBlockSize = nBlockSize;
  271. LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize);
  272. // Compute final coinbase transaction.
  273. txNew.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
  274. txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
  275. pblock->vtx[0] = txNew;
  276. pblocktemplate->vTxFees[0] = -nFees;
  277. // Fill in header
  278. pblock->hashPrevBlock = pindexPrev->GetBlockHash();
  279. UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
  280. pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
  281. pblock->nNonce = 0;
  282. pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
  283. CValidationState state;
  284. if (!TestBlockValidity(state, *pblock, pindexPrev, false, false))
  285. throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed");
  286. }
  287. return pblocktemplate.release();
  288. }
  289. void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
  290. {
  291. // Update nExtraNonce
  292. static uint256 hashPrevBlock;
  293. if (hashPrevBlock != pblock->hashPrevBlock)
  294. {
  295. nExtraNonce = 0;
  296. hashPrevBlock = pblock->hashPrevBlock;
  297. }
  298. ++nExtraNonce;
  299. unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
  300. CMutableTransaction txCoinbase(pblock->vtx[0]);
  301. txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
  302. assert(txCoinbase.vin[0].scriptSig.size() <= 100);
  303. pblock->vtx[0] = txCoinbase;
  304. pblock->hashMerkleRoot = pblock->BuildMerkleTree();
  305. }
  306. #ifdef ENABLE_WALLET
  307. //////////////////////////////////////////////////////////////////////////////
  308. //
  309. // Internal miner
  310. //
  311. //
  312. // ScanHash scans nonces looking for a hash with at least some zero bits.
  313. // The nonce is usually preserved between calls, but periodically or if the
  314. // nonce is 0xffff0000 or above, the block is rebuilt and nNonce starts over at
  315. // zero.
  316. //
  317. bool static ScanHash(const CBlockHeader *pblock, uint32_t& nNonce, uint256 *phash)
  318. {
  319. // Write the first 76 bytes of the block header to a double-SHA256 state.
  320. CHash256 hasher;
  321. CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
  322. ss << *pblock;
  323. assert(ss.size() == 80);
  324. hasher.Write((unsigned char*)&ss[0], 76);
  325. while (true) {
  326. nNonce++;
  327. // Write the last 4 bytes of the block header (the nonce) to a copy of
  328. // the double-SHA256 state, and compute the result.
  329. CHash256(hasher).Write((unsigned char*)&nNonce, 4).Finalize((unsigned char*)phash);
  330. // Return the nonce if the hash has at least some zero bits,
  331. // caller will check if it has enough to reach the target
  332. if (((uint16_t*)phash)[15] == 0)
  333. return true;
  334. // If nothing found after trying for a while, return -1
  335. if ((nNonce & 0xfff) == 0)
  336. return false;
  337. }
  338. }
  339. CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
  340. {
  341. CPubKey pubkey;
  342. if (!reservekey.GetReservedKey(pubkey))
  343. return NULL;
  344. CScript scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
  345. return CreateNewBlock(scriptPubKey);
  346. }
  347. static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
  348. {
  349. LogPrintf("%s\n", pblock->ToString());
  350. LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue));
  351. // Found a solution
  352. {
  353. LOCK(cs_main);
  354. if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
  355. return error("BitcoinMiner: generated block is stale");
  356. }
  357. // Remove key from key pool
  358. reservekey.KeepKey();
  359. // Track how many getdata requests this block gets
  360. {
  361. LOCK(wallet.cs_wallet);
  362. wallet.mapRequestCount[pblock->GetHash()] = 0;
  363. }
  364. // Process this block the same as if we had received it from another node
  365. CValidationState state;
  366. if (!ProcessNewBlock(state, NULL, pblock))
  367. return error("BitcoinMiner: ProcessNewBlock, block not accepted");
  368. return true;
  369. }
  370. void static BitcoinMiner(CWallet *pwallet)
  371. {
  372. LogPrintf("BitcoinMiner started\n");
  373. SetThreadPriority(THREAD_PRIORITY_LOWEST);
  374. RenameThread("bitcoin-miner");
  375. const CChainParams& chainparams = Params();
  376. // Each thread has its own key and counter
  377. CReserveKey reservekey(pwallet);
  378. unsigned int nExtraNonce = 0;
  379. try {
  380. while (true) {
  381. if (chainparams.MiningRequiresPeers()) {
  382. // Busy-wait for the network to come online so we don't waste time mining
  383. // on an obsolete chain. In regtest mode we expect to fly solo.
  384. do {
  385. bool fvNodesEmpty;
  386. {
  387. LOCK(cs_vNodes);
  388. fvNodesEmpty = vNodes.empty();
  389. }
  390. if (!fvNodesEmpty && !IsInitialBlockDownload())
  391. break;
  392. MilliSleep(1000);
  393. } while (true);
  394. }
  395. //
  396. // Create new block
  397. //
  398. unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
  399. CBlockIndex* pindexPrev = chainActive.Tip();
  400. auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
  401. if (!pblocktemplate.get())
  402. {
  403. LogPrintf("Error in BitcoinMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
  404. return;
  405. }
  406. CBlock *pblock = &pblocktemplate->block;
  407. IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
  408. LogPrintf("Running BitcoinMiner with %u transactions in block (%u bytes)\n", pblock->vtx.size(),
  409. ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
  410. //
  411. // Search
  412. //
  413. int64_t nStart = GetTime();
  414. arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
  415. uint256 hash;
  416. uint32_t nNonce = 0;
  417. while (true) {
  418. // Check if something found
  419. if (ScanHash(pblock, nNonce, &hash))
  420. {
  421. if (UintToArith256(hash) <= hashTarget)
  422. {
  423. // Found a solution
  424. pblock->nNonce = nNonce;
  425. assert(hash == pblock->GetHash());
  426. SetThreadPriority(THREAD_PRIORITY_NORMAL);
  427. LogPrintf("BitcoinMiner:\n");
  428. LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex(), hashTarget.GetHex());
  429. ProcessBlockFound(pblock, *pwallet, reservekey);
  430. SetThreadPriority(THREAD_PRIORITY_LOWEST);
  431. // In regression test mode, stop mining after a block is found.
  432. if (chainparams.MineBlocksOnDemand())
  433. throw boost::thread_interrupted();
  434. break;
  435. }
  436. }
  437. // Check for stop or if block needs to be rebuilt
  438. boost::this_thread::interruption_point();
  439. // Regtest mode doesn't require peers
  440. if (vNodes.empty() && chainparams.MiningRequiresPeers())
  441. break;
  442. if (nNonce >= 0xffff0000)
  443. break;
  444. if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
  445. break;
  446. if (pindexPrev != chainActive.Tip())
  447. break;
  448. // Update nTime every few seconds
  449. UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
  450. if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
  451. {
  452. // Changing pblock->nTime can change work required on testnet:
  453. hashTarget.SetCompact(pblock->nBits);
  454. }
  455. }
  456. }
  457. }
  458. catch (const boost::thread_interrupted&)
  459. {
  460. LogPrintf("BitcoinMiner terminated\n");
  461. throw;
  462. }
  463. catch (const std::runtime_error &e)
  464. {
  465. LogPrintf("BitcoinMiner runtime error: %s\n", e.what());
  466. return;
  467. }
  468. }
  469. void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
  470. {
  471. static boost::thread_group* minerThreads = NULL;
  472. if (nThreads < 0) {
  473. // In regtest threads defaults to 1
  474. if (Params().DefaultMinerThreads())
  475. nThreads = Params().DefaultMinerThreads();
  476. else
  477. nThreads = boost::thread::hardware_concurrency();
  478. }
  479. if (minerThreads != NULL)
  480. {
  481. minerThreads->interrupt_all();
  482. delete minerThreads;
  483. minerThreads = NULL;
  484. }
  485. if (nThreads == 0 || !fGenerate)
  486. return;
  487. minerThreads = new boost::thread_group();
  488. for (int i = 0; i < nThreads; i++)
  489. minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
  490. }
  491. #endif // ENABLE_WALLET