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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2013 The Bitcoin developers
  3. // Distributed under the MIT/X11 software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include "miner.h"
  6. #include "core.h"
  7. #include "main.h"
  8. #include "net.h"
  9. #ifdef ENABLE_WALLET
  10. #include "wallet.h"
  11. #endif
  12. //////////////////////////////////////////////////////////////////////////////
  13. //
  14. // BitcoinMiner
  15. //
  16. int static FormatHashBlocks(void* pbuffer, unsigned int len)
  17. {
  18. unsigned char* pdata = (unsigned char*)pbuffer;
  19. unsigned int blocks = 1 + ((len + 8) / 64);
  20. unsigned char* pend = pdata + 64 * blocks;
  21. memset(pdata + len, 0, 64 * blocks - len);
  22. pdata[len] = 0x80;
  23. unsigned int bits = len * 8;
  24. pend[-1] = (bits >> 0) & 0xff;
  25. pend[-2] = (bits >> 8) & 0xff;
  26. pend[-3] = (bits >> 16) & 0xff;
  27. pend[-4] = (bits >> 24) & 0xff;
  28. return blocks;
  29. }
  30. static const unsigned int pSHA256InitState[8] =
  31. {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
  32. void SHA256Transform(void* pstate, void* pinput, const void* pinit)
  33. {
  34. SHA256_CTX ctx;
  35. unsigned char data[64];
  36. SHA256_Init(&ctx);
  37. for (int i = 0; i < 16; i++)
  38. ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
  39. for (int i = 0; i < 8; i++)
  40. ctx.h[i] = ((uint32_t*)pinit)[i];
  41. SHA256_Update(&ctx, data, sizeof(data));
  42. for (int i = 0; i < 8; i++)
  43. ((uint32_t*)pstate)[i] = ctx.h[i];
  44. }
  45. // Some explaining would be appreciated
  46. class COrphan
  47. {
  48. public:
  49. const CTransaction* ptx;
  50. set<uint256> setDependsOn;
  51. double dPriority;
  52. double dFeePerKb;
  53. COrphan(const CTransaction* ptxIn)
  54. {
  55. ptx = ptxIn;
  56. dPriority = dFeePerKb = 0;
  57. }
  58. void print() const
  59. {
  60. LogPrintf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
  61. ptx->GetHash().ToString(), dPriority, dFeePerKb);
  62. BOOST_FOREACH(uint256 hash, setDependsOn)
  63. LogPrintf(" setDependsOn %s\n", hash.ToString());
  64. }
  65. };
  66. uint64_t nLastBlockTx = 0;
  67. uint64_t nLastBlockSize = 0;
  68. // We want to sort transactions by priority and fee, so:
  69. typedef boost::tuple<double, double, const CTransaction*> TxPriority;
  70. class TxPriorityCompare
  71. {
  72. bool byFee;
  73. public:
  74. TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
  75. bool operator()(const TxPriority& a, const TxPriority& b)
  76. {
  77. if (byFee)
  78. {
  79. if (a.get<1>() == b.get<1>())
  80. return a.get<0>() < b.get<0>();
  81. return a.get<1>() < b.get<1>();
  82. }
  83. else
  84. {
  85. if (a.get<0>() == b.get<0>())
  86. return a.get<1>() < b.get<1>();
  87. return a.get<0>() < b.get<0>();
  88. }
  89. }
  90. };
  91. CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
  92. {
  93. // Create new block
  94. auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
  95. if(!pblocktemplate.get())
  96. return NULL;
  97. CBlock *pblock = &pblocktemplate->block; // pointer for convenience
  98. // Create coinbase tx
  99. CTransaction txNew;
  100. txNew.vin.resize(1);
  101. txNew.vin[0].prevout.SetNull();
  102. txNew.vout.resize(1);
  103. txNew.vout[0].scriptPubKey = scriptPubKeyIn;
  104. // Add our coinbase tx as first transaction
  105. pblock->vtx.push_back(txNew);
  106. pblocktemplate->vTxFees.push_back(-1); // updated at end
  107. pblocktemplate->vTxSigOps.push_back(-1); // updated at end
  108. // Largest block you're willing to create:
  109. unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
  110. // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
  111. nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
  112. // How much of the block should be dedicated to high-priority transactions,
  113. // included regardless of the fees they pay
  114. unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
  115. nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
  116. // Minimum block size you want to create; block will be filled with free transactions
  117. // until there are no more or the block reaches this size:
  118. unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
  119. nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
  120. // Collect memory pool transactions into the block
  121. int64_t nFees = 0;
  122. {
  123. LOCK2(cs_main, mempool.cs);
  124. CBlockIndex* pindexPrev = chainActive.Tip();
  125. CCoinsViewCache view(*pcoinsTip, true);
  126. // Priority order to process transactions
  127. list<COrphan> vOrphan; // list memory doesn't move
  128. map<uint256, vector<COrphan*> > mapDependers;
  129. bool fPrintPriority = GetBoolArg("-printpriority", false);
  130. // This vector will be sorted into a priority queue:
  131. vector<TxPriority> vecPriority;
  132. vecPriority.reserve(mempool.mapTx.size());
  133. for (map<uint256, CTxMemPoolEntry>::iterator mi = mempool.mapTx.begin();
  134. mi != mempool.mapTx.end(); ++mi)
  135. {
  136. const CTransaction& tx = mi->second.GetTx();
  137. if (tx.IsCoinBase() || !IsFinalTx(tx, pindexPrev->nHeight + 1))
  138. continue;
  139. COrphan* porphan = NULL;
  140. double dPriority = 0;
  141. int64_t nTotalIn = 0;
  142. bool fMissingInputs = false;
  143. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  144. {
  145. // Read prev transaction
  146. if (!view.HaveCoins(txin.prevout.hash))
  147. {
  148. // This should never happen; all transactions in the memory
  149. // pool should connect to either transactions in the chain
  150. // or other transactions in the memory pool.
  151. if (!mempool.mapTx.count(txin.prevout.hash))
  152. {
  153. LogPrintf("ERROR: mempool transaction missing input\n");
  154. if (fDebug) assert("mempool transaction missing input" == 0);
  155. fMissingInputs = true;
  156. if (porphan)
  157. vOrphan.pop_back();
  158. break;
  159. }
  160. // Has to wait for dependencies
  161. if (!porphan)
  162. {
  163. // Use list for automatic deletion
  164. vOrphan.push_back(COrphan(&tx));
  165. porphan = &vOrphan.back();
  166. }
  167. mapDependers[txin.prevout.hash].push_back(porphan);
  168. porphan->setDependsOn.insert(txin.prevout.hash);
  169. nTotalIn += mempool.mapTx[txin.prevout.hash].GetTx().vout[txin.prevout.n].nValue;
  170. continue;
  171. }
  172. const CCoins &coins = view.GetCoins(txin.prevout.hash);
  173. int64_t nValueIn = coins.vout[txin.prevout.n].nValue;
  174. nTotalIn += nValueIn;
  175. int nConf = pindexPrev->nHeight - coins.nHeight + 1;
  176. dPriority += (double)nValueIn * nConf;
  177. }
  178. if (fMissingInputs) continue;
  179. // Priority is sum(valuein * age) / modified_txsize
  180. unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
  181. dPriority = tx.ComputePriority(dPriority, nTxSize);
  182. // This is a more accurate fee-per-kilobyte than is used by the client code, because the
  183. // client code rounds up the size to the nearest 1K. That's good, because it gives an
  184. // incentive to create smaller transactions.
  185. double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
  186. if (porphan)
  187. {
  188. porphan->dPriority = dPriority;
  189. porphan->dFeePerKb = dFeePerKb;
  190. }
  191. else
  192. vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &mi->second.GetTx()));
  193. }
  194. // Collect transactions into block
  195. uint64_t nBlockSize = 1000;
  196. uint64_t nBlockTx = 0;
  197. int nBlockSigOps = 100;
  198. bool fSortedByFee = (nBlockPrioritySize <= 0);
  199. TxPriorityCompare comparer(fSortedByFee);
  200. std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
  201. while (!vecPriority.empty())
  202. {
  203. // Take highest priority transaction off the priority queue:
  204. double dPriority = vecPriority.front().get<0>();
  205. double dFeePerKb = vecPriority.front().get<1>();
  206. const CTransaction& tx = *(vecPriority.front().get<2>());
  207. std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
  208. vecPriority.pop_back();
  209. // Size limits
  210. unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
  211. if (nBlockSize + nTxSize >= nBlockMaxSize)
  212. continue;
  213. // Legacy limits on sigOps:
  214. unsigned int nTxSigOps = GetLegacySigOpCount(tx);
  215. if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
  216. continue;
  217. // Skip free transactions if we're past the minimum block size:
  218. if (fSortedByFee && (dFeePerKb < CTransaction::nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
  219. continue;
  220. // Prioritize by fee once past the priority size or we run out of high-priority
  221. // transactions:
  222. if (!fSortedByFee &&
  223. ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
  224. {
  225. fSortedByFee = true;
  226. comparer = TxPriorityCompare(fSortedByFee);
  227. std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
  228. }
  229. if (!view.HaveInputs(tx))
  230. continue;
  231. int64_t nTxFees = view.GetValueIn(tx)-tx.GetValueOut();
  232. nTxSigOps += GetP2SHSigOpCount(tx, view);
  233. if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
  234. continue;
  235. CValidationState state;
  236. if (!CheckInputs(tx, state, view, true, SCRIPT_VERIFY_P2SH))
  237. continue;
  238. CTxUndo txundo;
  239. uint256 hash = tx.GetHash();
  240. UpdateCoins(tx, state, view, txundo, pindexPrev->nHeight+1, hash);
  241. // Added
  242. pblock->vtx.push_back(tx);
  243. pblocktemplate->vTxFees.push_back(nTxFees);
  244. pblocktemplate->vTxSigOps.push_back(nTxSigOps);
  245. nBlockSize += nTxSize;
  246. ++nBlockTx;
  247. nBlockSigOps += nTxSigOps;
  248. nFees += nTxFees;
  249. if (fPrintPriority)
  250. {
  251. LogPrintf("priority %.1f feeperkb %.1f txid %s\n",
  252. dPriority, dFeePerKb, tx.GetHash().ToString());
  253. }
  254. // Add transactions that depend on this one to the priority queue
  255. if (mapDependers.count(hash))
  256. {
  257. BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
  258. {
  259. if (!porphan->setDependsOn.empty())
  260. {
  261. porphan->setDependsOn.erase(hash);
  262. if (porphan->setDependsOn.empty())
  263. {
  264. vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
  265. std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
  266. }
  267. }
  268. }
  269. }
  270. }
  271. nLastBlockTx = nBlockTx;
  272. nLastBlockSize = nBlockSize;
  273. LogPrintf("CreateNewBlock(): total size %"PRIu64"\n", nBlockSize);
  274. pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
  275. pblocktemplate->vTxFees[0] = -nFees;
  276. // Fill in header
  277. pblock->hashPrevBlock = pindexPrev->GetBlockHash();
  278. UpdateTime(*pblock, pindexPrev);
  279. pblock->nBits = GetNextWorkRequired(pindexPrev, pblock);
  280. pblock->nNonce = 0;
  281. pblock->vtx[0].vin[0].scriptSig = CScript() << OP_0 << OP_0;
  282. pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
  283. CBlockIndex indexDummy(*pblock);
  284. indexDummy.pprev = pindexPrev;
  285. indexDummy.nHeight = pindexPrev->nHeight + 1;
  286. CCoinsViewCache viewNew(*pcoinsTip, true);
  287. CValidationState state;
  288. if (!ConnectBlock(*pblock, state, &indexDummy, viewNew, true))
  289. throw std::runtime_error("CreateNewBlock() : ConnectBlock failed");
  290. }
  291. return pblocktemplate.release();
  292. }
  293. void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
  294. {
  295. // Update nExtraNonce
  296. static uint256 hashPrevBlock;
  297. if (hashPrevBlock != pblock->hashPrevBlock)
  298. {
  299. nExtraNonce = 0;
  300. hashPrevBlock = pblock->hashPrevBlock;
  301. }
  302. ++nExtraNonce;
  303. unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
  304. pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
  305. assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
  306. pblock->hashMerkleRoot = pblock->BuildMerkleTree();
  307. }
  308. void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
  309. {
  310. //
  311. // Pre-build hash buffers
  312. //
  313. struct
  314. {
  315. struct unnamed2
  316. {
  317. int nVersion;
  318. uint256 hashPrevBlock;
  319. uint256 hashMerkleRoot;
  320. unsigned int nTime;
  321. unsigned int nBits;
  322. unsigned int nNonce;
  323. }
  324. block;
  325. unsigned char pchPadding0[64];
  326. uint256 hash1;
  327. unsigned char pchPadding1[64];
  328. }
  329. tmp;
  330. memset(&tmp, 0, sizeof(tmp));
  331. tmp.block.nVersion = pblock->nVersion;
  332. tmp.block.hashPrevBlock = pblock->hashPrevBlock;
  333. tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
  334. tmp.block.nTime = pblock->nTime;
  335. tmp.block.nBits = pblock->nBits;
  336. tmp.block.nNonce = pblock->nNonce;
  337. FormatHashBlocks(&tmp.block, sizeof(tmp.block));
  338. FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
  339. // Byte swap all the input buffer
  340. for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
  341. ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
  342. // Precalc the first half of the first hash, which stays constant
  343. SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
  344. memcpy(pdata, &tmp.block, 128);
  345. memcpy(phash1, &tmp.hash1, 64);
  346. }
  347. #ifdef ENABLE_WALLET
  348. //////////////////////////////////////////////////////////////////////////////
  349. //
  350. // Internal miner
  351. //
  352. double dHashesPerSec = 0.0;
  353. int64_t nHPSTimerStart = 0;
  354. //
  355. // ScanHash scans nonces looking for a hash with at least some zero bits.
  356. // It operates on big endian data. Caller does the byte reversing.
  357. // All input buffers are 16-byte aligned. nNonce is usually preserved
  358. // between calls, but periodically or if nNonce is 0xffff0000 or above,
  359. // the block is rebuilt and nNonce starts over at zero.
  360. //
  361. unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
  362. {
  363. unsigned int& nNonce = *(unsigned int*)(pdata + 12);
  364. for (;;)
  365. {
  366. // Crypto++ SHA256
  367. // Hash pdata using pmidstate as the starting state into
  368. // pre-formatted buffer phash1, then hash phash1 into phash
  369. nNonce++;
  370. SHA256Transform(phash1, pdata, pmidstate);
  371. SHA256Transform(phash, phash1, pSHA256InitState);
  372. // Return the nonce if the hash has at least some zero bits,
  373. // caller will check if it has enough to reach the target
  374. if (((unsigned short*)phash)[14] == 0)
  375. return nNonce;
  376. // If nothing found after trying for a while, return -1
  377. if ((nNonce & 0xffff) == 0)
  378. {
  379. nHashesDone = 0xffff+1;
  380. return (unsigned int) -1;
  381. }
  382. if ((nNonce & 0xfff) == 0)
  383. boost::this_thread::interruption_point();
  384. }
  385. }
  386. CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
  387. {
  388. CPubKey pubkey;
  389. if (!reservekey.GetReservedKey(pubkey))
  390. return NULL;
  391. CScript scriptPubKey = CScript() << pubkey << OP_CHECKSIG;
  392. return CreateNewBlock(scriptPubKey);
  393. }
  394. bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
  395. {
  396. uint256 hash = pblock->GetHash();
  397. uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
  398. if (hash > hashTarget)
  399. return false;
  400. //// debug print
  401. LogPrintf("BitcoinMiner:\n");
  402. LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex(), hashTarget.GetHex());
  403. pblock->print();
  404. LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue));
  405. // Found a solution
  406. {
  407. LOCK(cs_main);
  408. if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
  409. return error("BitcoinMiner : generated block is stale");
  410. // Remove key from key pool
  411. reservekey.KeepKey();
  412. // Track how many getdata requests this block gets
  413. {
  414. LOCK(wallet.cs_wallet);
  415. wallet.mapRequestCount[pblock->GetHash()] = 0;
  416. }
  417. // Process this block the same as if we had received it from another node
  418. CValidationState state;
  419. if (!ProcessBlock(state, NULL, pblock))
  420. return error("BitcoinMiner : ProcessBlock, block not accepted");
  421. }
  422. return true;
  423. }
  424. void static BitcoinMiner(CWallet *pwallet)
  425. {
  426. LogPrintf("BitcoinMiner started\n");
  427. SetThreadPriority(THREAD_PRIORITY_LOWEST);
  428. RenameThread("bitcoin-miner");
  429. // Each thread has its own key and counter
  430. CReserveKey reservekey(pwallet);
  431. unsigned int nExtraNonce = 0;
  432. try { while (true) {
  433. if (Params().NetworkID() != CChainParams::REGTEST) {
  434. // Busy-wait for the network to come online so we don't waste time mining
  435. // on an obsolete chain. In regtest mode we expect to fly solo.
  436. while (vNodes.empty())
  437. MilliSleep(1000);
  438. }
  439. //
  440. // Create new block
  441. //
  442. unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
  443. CBlockIndex* pindexPrev = chainActive.Tip();
  444. auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
  445. if (!pblocktemplate.get())
  446. return;
  447. CBlock *pblock = &pblocktemplate->block;
  448. IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
  449. LogPrintf("Running BitcoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
  450. ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
  451. //
  452. // Pre-build hash buffers
  453. //
  454. char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
  455. char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
  456. char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
  457. FormatHashBuffers(pblock, pmidstate, pdata, phash1);
  458. unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
  459. unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
  460. unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
  461. //
  462. // Search
  463. //
  464. int64_t nStart = GetTime();
  465. uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
  466. uint256 hashbuf[2];
  467. uint256& hash = *alignup<16>(hashbuf);
  468. while (true)
  469. {
  470. unsigned int nHashesDone = 0;
  471. unsigned int nNonceFound;
  472. // Crypto++ SHA256
  473. nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
  474. (char*)&hash, nHashesDone);
  475. // Check if something found
  476. if (nNonceFound != (unsigned int) -1)
  477. {
  478. for (unsigned int i = 0; i < sizeof(hash)/4; i++)
  479. ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
  480. if (hash <= hashTarget)
  481. {
  482. // Found a solution
  483. pblock->nNonce = ByteReverse(nNonceFound);
  484. assert(hash == pblock->GetHash());
  485. SetThreadPriority(THREAD_PRIORITY_NORMAL);
  486. CheckWork(pblock, *pwallet, reservekey);
  487. SetThreadPriority(THREAD_PRIORITY_LOWEST);
  488. // In regression test mode, stop mining after a block is found. This
  489. // allows developers to controllably generate a block on demand.
  490. if (Params().NetworkID() == CChainParams::REGTEST)
  491. throw boost::thread_interrupted();
  492. break;
  493. }
  494. }
  495. // Meter hashes/sec
  496. static int64_t nHashCounter;
  497. if (nHPSTimerStart == 0)
  498. {
  499. nHPSTimerStart = GetTimeMillis();
  500. nHashCounter = 0;
  501. }
  502. else
  503. nHashCounter += nHashesDone;
  504. if (GetTimeMillis() - nHPSTimerStart > 4000)
  505. {
  506. static CCriticalSection cs;
  507. {
  508. LOCK(cs);
  509. if (GetTimeMillis() - nHPSTimerStart > 4000)
  510. {
  511. dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
  512. nHPSTimerStart = GetTimeMillis();
  513. nHashCounter = 0;
  514. static int64_t nLogTime;
  515. if (GetTime() - nLogTime > 30 * 60)
  516. {
  517. nLogTime = GetTime();
  518. LogPrintf("hashmeter %6.0f khash/s\n", dHashesPerSec/1000.0);
  519. }
  520. }
  521. }
  522. }
  523. // Check for stop or if block needs to be rebuilt
  524. boost::this_thread::interruption_point();
  525. if (vNodes.empty() && Params().NetworkID() != CChainParams::REGTEST)
  526. break;
  527. if (nBlockNonce >= 0xffff0000)
  528. break;
  529. if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
  530. break;
  531. if (pindexPrev != chainActive.Tip())
  532. break;
  533. // Update nTime every few seconds
  534. UpdateTime(*pblock, pindexPrev);
  535. nBlockTime = ByteReverse(pblock->nTime);
  536. if (TestNet())
  537. {
  538. // Changing pblock->nTime can change work required on testnet:
  539. nBlockBits = ByteReverse(pblock->nBits);
  540. hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
  541. }
  542. }
  543. } }
  544. catch (boost::thread_interrupted)
  545. {
  546. LogPrintf("BitcoinMiner terminated\n");
  547. throw;
  548. }
  549. }
  550. void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
  551. {
  552. static boost::thread_group* minerThreads = NULL;
  553. if (nThreads < 0) {
  554. if (Params().NetworkID() == CChainParams::REGTEST)
  555. nThreads = 1;
  556. else
  557. nThreads = boost::thread::hardware_concurrency();
  558. }
  559. if (minerThreads != NULL)
  560. {
  561. minerThreads->interrupt_all();
  562. delete minerThreads;
  563. minerThreads = NULL;
  564. }
  565. if (nThreads == 0 || !fGenerate)
  566. return;
  567. minerThreads = new boost::thread_group();
  568. for (int i = 0; i < nThreads; i++)
  569. minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
  570. }
  571. #endif