1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 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.
9 double dHashesPerSec = 0.0;
10 int64 nHPSTimerStart = 0;
12 //////////////////////////////////////////////////////////////////////////////
17 int static FormatHashBlocks(void* pbuffer, unsigned int len)
19 unsigned char* pdata = (unsigned char*)pbuffer;
20 unsigned int blocks = 1 + ((len + 8) / 64);
21 unsigned char* pend = pdata + 64 * blocks;
22 memset(pdata + len, 0, 64 * blocks - len);
24 unsigned int bits = len * 8;
25 pend[-1] = (bits >> 0) & 0xff;
26 pend[-2] = (bits >> 8) & 0xff;
27 pend[-3] = (bits >> 16) & 0xff;
28 pend[-4] = (bits >> 24) & 0xff;
32 static const unsigned int pSHA256InitState[8] =
33 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
35 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
38 unsigned char data[64];
42 for (int i = 0; i < 16; i++)
43 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
45 for (int i = 0; i < 8; i++)
46 ctx.h[i] = ((uint32_t*)pinit)[i];
48 SHA256_Update(&ctx, data, sizeof(data));
49 for (int i = 0; i < 8; i++)
50 ((uint32_t*)pstate)[i] = ctx.h[i];
54 // ScanHash scans nonces looking for a hash with at least some zero bits.
55 // It operates on big endian data. Caller does the byte reversing.
56 // All input buffers are 16-byte aligned. nNonce is usually preserved
57 // between calls, but periodically or if nNonce is 0xffff0000 or above,
58 // the block is rebuilt and nNonce starts over at zero.
60 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
62 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
66 // Hash pdata using pmidstate as the starting state into
67 // pre-formatted buffer phash1, then hash phash1 into phash
69 SHA256Transform(phash1, pdata, pmidstate);
70 SHA256Transform(phash, phash1, pSHA256InitState);
72 // Return the nonce if the hash has at least some zero bits,
73 // caller will check if it has enough to reach the target
74 if (((unsigned short*)phash)[14] == 0)
77 // If nothing found after trying for a while, return -1
78 if ((nNonce & 0xffff) == 0)
80 nHashesDone = 0xffff+1;
81 return (unsigned int) -1;
83 if ((nNonce & 0xfff) == 0)
84 boost::this_thread::interruption_point();
88 // Some explaining would be appreciated
93 set<uint256> setDependsOn;
97 COrphan(CTransaction* ptxIn)
100 dPriority = dFeePerKb = 0;
105 LogPrintf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
106 ptx->GetHash().ToString().c_str(), dPriority, dFeePerKb);
107 BOOST_FOREACH(uint256 hash, setDependsOn)
108 LogPrintf(" setDependsOn %s\n", hash.ToString().c_str());
113 uint64 nLastBlockTx = 0;
114 uint64 nLastBlockSize = 0;
116 // We want to sort transactions by priority and fee, so:
117 typedef boost::tuple<double, double, CTransaction*> TxPriority;
118 class TxPriorityCompare
122 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
123 bool operator()(const TxPriority& a, const TxPriority& b)
127 if (a.get<1>() == b.get<1>())
128 return a.get<0>() < b.get<0>();
129 return a.get<1>() < b.get<1>();
133 if (a.get<0>() == b.get<0>())
134 return a.get<1>() < b.get<1>();
135 return a.get<0>() < b.get<0>();
140 CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
143 auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
144 if(!pblocktemplate.get())
146 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
148 // Create coinbase tx
151 txNew.vin[0].prevout.SetNull();
152 txNew.vout.resize(1);
153 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
155 // Add our coinbase tx as first transaction
156 pblock->vtx.push_back(txNew);
157 pblocktemplate->vTxFees.push_back(-1); // updated at end
158 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
160 // Largest block you're willing to create:
161 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
162 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
163 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
165 // How much of the block should be dedicated to high-priority transactions,
166 // included regardless of the fees they pay
167 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
168 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
170 // Minimum block size you want to create; block will be filled with free transactions
171 // until there are no more or the block reaches this size:
172 unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
173 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
175 // Collect memory pool transactions into the block
178 LOCK2(cs_main, mempool.cs);
179 CBlockIndex* pindexPrev = pindexBest;
180 CCoinsViewCache view(*pcoinsTip, true);
182 // Priority order to process transactions
183 list<COrphan> vOrphan; // list memory doesn't move
184 map<uint256, vector<COrphan*> > mapDependers;
185 bool fPrintPriority = GetBoolArg("-printpriority", false);
187 // This vector will be sorted into a priority queue:
188 vector<TxPriority> vecPriority;
189 vecPriority.reserve(mempool.mapTx.size());
190 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
192 CTransaction& tx = (*mi).second;
193 if (tx.IsCoinBase() || !IsFinalTx(tx))
196 COrphan* porphan = NULL;
197 double dPriority = 0;
199 bool fMissingInputs = false;
200 BOOST_FOREACH(const CTxIn& txin, tx.vin)
202 // Read prev transaction
203 if (!view.HaveCoins(txin.prevout.hash))
205 // This should never happen; all transactions in the memory
206 // pool should connect to either transactions in the chain
207 // or other transactions in the memory pool.
208 if (!mempool.mapTx.count(txin.prevout.hash))
210 LogPrintf("ERROR: mempool transaction missing input\n");
211 if (fDebug) assert("mempool transaction missing input" == 0);
212 fMissingInputs = true;
218 // Has to wait for dependencies
221 // Use list for automatic deletion
222 vOrphan.push_back(COrphan(&tx));
223 porphan = &vOrphan.back();
225 mapDependers[txin.prevout.hash].push_back(porphan);
226 porphan->setDependsOn.insert(txin.prevout.hash);
227 nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
230 const CCoins &coins = view.GetCoins(txin.prevout.hash);
232 int64 nValueIn = coins.vout[txin.prevout.n].nValue;
233 nTotalIn += nValueIn;
235 int nConf = pindexPrev->nHeight - coins.nHeight + 1;
237 dPriority += (double)nValueIn * nConf;
239 if (fMissingInputs) continue;
241 // Priority is sum(valuein * age) / txsize
242 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
243 dPriority /= nTxSize;
245 // This is a more accurate fee-per-kilobyte than is used by the client code, because the
246 // client code rounds up the size to the nearest 1K. That's good, because it gives an
247 // incentive to create smaller transactions.
248 double dFeePerKb = double(nTotalIn-GetValueOut(tx)) / (double(nTxSize)/1000.0);
252 porphan->dPriority = dPriority;
253 porphan->dFeePerKb = dFeePerKb;
256 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
259 // Collect transactions into block
260 uint64 nBlockSize = 1000;
262 int nBlockSigOps = 100;
263 bool fSortedByFee = (nBlockPrioritySize <= 0);
265 TxPriorityCompare comparer(fSortedByFee);
266 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
268 while (!vecPriority.empty())
270 // Take highest priority transaction off the priority queue:
271 double dPriority = vecPriority.front().get<0>();
272 double dFeePerKb = vecPriority.front().get<1>();
273 CTransaction& tx = *(vecPriority.front().get<2>());
275 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
276 vecPriority.pop_back();
279 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
280 if (nBlockSize + nTxSize >= nBlockMaxSize)
283 // Legacy limits on sigOps:
284 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
285 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
288 // Skip free transactions if we're past the minimum block size:
289 if (fSortedByFee && (dFeePerKb < CTransaction::nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
292 // Prioritize by fee once past the priority size or we run out of high-priority
295 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
298 comparer = TxPriorityCompare(fSortedByFee);
299 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
302 if (!view.HaveInputs(tx))
305 int64 nTxFees = view.GetValueIn(tx)-GetValueOut(tx);
307 nTxSigOps += GetP2SHSigOpCount(tx, view);
308 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
311 CValidationState state;
312 if (!CheckInputs(tx, state, view, true, SCRIPT_VERIFY_P2SH))
316 uint256 hash = tx.GetHash();
317 UpdateCoins(tx, state, view, txundo, pindexPrev->nHeight+1, hash);
320 pblock->vtx.push_back(tx);
321 pblocktemplate->vTxFees.push_back(nTxFees);
322 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
323 nBlockSize += nTxSize;
325 nBlockSigOps += nTxSigOps;
330 LogPrintf("priority %.1f feeperkb %.1f txid %s\n",
331 dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
334 // Add transactions that depend on this one to the priority queue
335 if (mapDependers.count(hash))
337 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
339 if (!porphan->setDependsOn.empty())
341 porphan->setDependsOn.erase(hash);
342 if (porphan->setDependsOn.empty())
344 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
345 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
352 nLastBlockTx = nBlockTx;
353 nLastBlockSize = nBlockSize;
354 LogPrintf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
356 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
357 pblocktemplate->vTxFees[0] = -nFees;
360 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
361 UpdateTime(*pblock, pindexPrev);
362 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock);
364 pblock->vtx[0].vin[0].scriptSig = CScript() << OP_0 << OP_0;
365 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
367 CBlockIndex indexDummy(*pblock);
368 indexDummy.pprev = pindexPrev;
369 indexDummy.nHeight = pindexPrev->nHeight + 1;
370 CCoinsViewCache viewNew(*pcoinsTip, true);
371 CValidationState state;
372 if (!ConnectBlock(*pblock, state, &indexDummy, viewNew, true))
373 throw std::runtime_error("CreateNewBlock() : ConnectBlock failed");
376 return pblocktemplate.release();
379 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
382 if (!reservekey.GetReservedKey(pubkey))
385 CScript scriptPubKey = CScript() << pubkey << OP_CHECKSIG;
386 return CreateNewBlock(scriptPubKey);
389 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
391 // Update nExtraNonce
392 static uint256 hashPrevBlock;
393 if (hashPrevBlock != pblock->hashPrevBlock)
396 hashPrevBlock = pblock->hashPrevBlock;
399 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
400 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
401 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
403 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
407 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
410 // Pre-build hash buffers
417 uint256 hashPrevBlock;
418 uint256 hashMerkleRoot;
424 unsigned char pchPadding0[64];
426 unsigned char pchPadding1[64];
429 memset(&tmp, 0, sizeof(tmp));
431 tmp.block.nVersion = pblock->nVersion;
432 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
433 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
434 tmp.block.nTime = pblock->nTime;
435 tmp.block.nBits = pblock->nBits;
436 tmp.block.nNonce = pblock->nNonce;
438 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
439 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
441 // Byte swap all the input buffer
442 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
443 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
445 // Precalc the first half of the first hash, which stays constant
446 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
448 memcpy(pdata, &tmp.block, 128);
449 memcpy(phash1, &tmp.hash1, 64);
453 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
455 uint256 hash = pblock->GetHash();
456 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
458 if (hash > hashTarget)
462 LogPrintf("BitcoinMiner:\n");
463 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
465 LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
470 if (pblock->hashPrevBlock != hashBestChain)
471 return error("BitcoinMiner : generated block is stale");
473 // Remove key from key pool
474 reservekey.KeepKey();
476 // Track how many getdata requests this block gets
478 LOCK(wallet.cs_wallet);
479 wallet.mapRequestCount[pblock->GetHash()] = 0;
482 // Process this block the same as if we had received it from another node
483 CValidationState state;
484 if (!ProcessBlock(state, NULL, pblock))
485 return error("BitcoinMiner : ProcessBlock, block not accepted");
491 void static BitcoinMiner(CWallet *pwallet)
493 LogPrintf("BitcoinMiner started\n");
494 SetThreadPriority(THREAD_PRIORITY_LOWEST);
495 RenameThread("bitcoin-miner");
497 // Each thread has its own key and counter
498 CReserveKey reservekey(pwallet);
499 unsigned int nExtraNonce = 0;
502 if (Params().NetworkID() != CChainParams::REGTEST) {
503 // Busy-wait for the network to come online so we don't waste time mining
504 // on an obsolete chain. In regtest mode we expect to fly solo.
505 while (vNodes.empty())
512 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
513 CBlockIndex* pindexPrev = pindexBest;
515 auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
516 if (!pblocktemplate.get())
518 CBlock *pblock = &pblocktemplate->block;
519 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
521 LogPrintf("Running BitcoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
522 ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
525 // Pre-build hash buffers
527 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
528 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
529 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
531 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
533 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
534 unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
535 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
541 int64 nStart = GetTime();
542 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
544 uint256& hash = *alignup<16>(hashbuf);
547 unsigned int nHashesDone = 0;
548 unsigned int nNonceFound;
551 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
552 (char*)&hash, nHashesDone);
554 // Check if something found
555 if (nNonceFound != (unsigned int) -1)
557 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
558 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
560 if (hash <= hashTarget)
563 pblock->nNonce = ByteReverse(nNonceFound);
564 assert(hash == pblock->GetHash());
566 SetThreadPriority(THREAD_PRIORITY_NORMAL);
567 CheckWork(pblock, *pwallet, reservekey);
568 SetThreadPriority(THREAD_PRIORITY_LOWEST);
570 // In regression test mode, stop mining after a block is found. This
571 // allows developers to controllably generate a block on demand.
572 if (Params().NetworkID() == CChainParams::REGTEST)
573 throw boost::thread_interrupted();
580 static int64 nHashCounter;
581 if (nHPSTimerStart == 0)
583 nHPSTimerStart = GetTimeMillis();
587 nHashCounter += nHashesDone;
588 if (GetTimeMillis() - nHPSTimerStart > 4000)
590 static CCriticalSection cs;
593 if (GetTimeMillis() - nHPSTimerStart > 4000)
595 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
596 nHPSTimerStart = GetTimeMillis();
598 static int64 nLogTime;
599 if (GetTime() - nLogTime > 30 * 60)
601 nLogTime = GetTime();
602 LogPrintf("hashmeter %6.0f khash/s\n", dHashesPerSec/1000.0);
608 // Check for stop or if block needs to be rebuilt
609 boost::this_thread::interruption_point();
610 if (vNodes.empty() && Params().NetworkID() != CChainParams::REGTEST)
612 if (nBlockNonce >= 0xffff0000)
614 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
616 if (pindexPrev != pindexBest)
619 // Update nTime every few seconds
620 UpdateTime(*pblock, pindexPrev);
621 nBlockTime = ByteReverse(pblock->nTime);
624 // Changing pblock->nTime can change work required on testnet:
625 nBlockBits = ByteReverse(pblock->nBits);
626 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
630 catch (boost::thread_interrupted)
632 LogPrintf("BitcoinMiner terminated\n");
637 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
639 static boost::thread_group* minerThreads = NULL;
641 int nThreads = GetArg("-genproclimit", -1);
643 if (Params().NetworkID() == CChainParams::REGTEST)
646 nThreads = boost::thread::hardware_concurrency();
649 if (minerThreads != NULL)
651 minerThreads->interrupt_all();
656 if (nThreads == 0 || !fGenerate)
659 minerThreads = new boost::thread_group();
660 for (int i = 0; i < nThreads; i++)
661 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));