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.
13 //////////////////////////////////////////////////////////////////////////////
18 int static FormatHashBlocks(void* pbuffer, unsigned int len)
20 unsigned char* pdata = (unsigned char*)pbuffer;
21 unsigned int blocks = 1 + ((len + 8) / 64);
22 unsigned char* pend = pdata + 64 * blocks;
23 memset(pdata + len, 0, 64 * blocks - len);
25 unsigned int bits = len * 8;
26 pend[-1] = (bits >> 0) & 0xff;
27 pend[-2] = (bits >> 8) & 0xff;
28 pend[-3] = (bits >> 16) & 0xff;
29 pend[-4] = (bits >> 24) & 0xff;
33 static const unsigned int pSHA256InitState[8] =
34 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
36 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
39 unsigned char data[64];
43 for (int i = 0; i < 16; i++)
44 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
46 for (int i = 0; i < 8; i++)
47 ctx.h[i] = ((uint32_t*)pinit)[i];
49 SHA256_Update(&ctx, data, sizeof(data));
50 for (int i = 0; i < 8; i++)
51 ((uint32_t*)pstate)[i] = ctx.h[i];
54 // Some explaining would be appreciated
58 const CTransaction* ptx;
59 set<uint256> setDependsOn;
63 COrphan(const CTransaction* ptxIn)
66 dPriority = dFeePerKb = 0;
71 LogPrintf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
72 ptx->GetHash().ToString().c_str(), dPriority, dFeePerKb);
73 BOOST_FOREACH(uint256 hash, setDependsOn)
74 LogPrintf(" setDependsOn %s\n", hash.ToString().c_str());
79 uint64_t nLastBlockTx = 0;
80 uint64_t nLastBlockSize = 0;
82 // We want to sort transactions by priority and fee, so:
83 typedef boost::tuple<double, double, const CTransaction*> TxPriority;
84 class TxPriorityCompare
88 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
89 bool operator()(const TxPriority& a, const TxPriority& b)
93 if (a.get<1>() == b.get<1>())
94 return a.get<0>() < b.get<0>();
95 return a.get<1>() < b.get<1>();
99 if (a.get<0>() == b.get<0>())
100 return a.get<1>() < b.get<1>();
101 return a.get<0>() < b.get<0>();
106 CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
109 auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
110 if(!pblocktemplate.get())
112 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
114 // Create coinbase tx
117 txNew.vin[0].prevout.SetNull();
118 txNew.vout.resize(1);
119 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
121 // Add our coinbase tx as first transaction
122 pblock->vtx.push_back(txNew);
123 pblocktemplate->vTxFees.push_back(-1); // updated at end
124 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
126 // Largest block you're willing to create:
127 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
128 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
129 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
131 // How much of the block should be dedicated to high-priority transactions,
132 // included regardless of the fees they pay
133 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
134 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
136 // Minimum block size you want to create; block will be filled with free transactions
137 // until there are no more or the block reaches this size:
138 unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
139 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
141 // Collect memory pool transactions into the block
144 LOCK2(cs_main, mempool.cs);
145 CBlockIndex* pindexPrev = chainActive.Tip();
146 CCoinsViewCache view(*pcoinsTip, true);
148 // Priority order to process transactions
149 list<COrphan> vOrphan; // list memory doesn't move
150 map<uint256, vector<COrphan*> > mapDependers;
151 bool fPrintPriority = GetBoolArg("-printpriority", false);
153 // This vector will be sorted into a priority queue:
154 vector<TxPriority> vecPriority;
155 vecPriority.reserve(mempool.mapTx.size());
156 for (map<uint256, CTxMemPoolEntry>::iterator mi = mempool.mapTx.begin();
157 mi != mempool.mapTx.end(); ++mi)
159 const CTransaction& tx = mi->second.GetTx();
160 if (tx.IsCoinBase() || !IsFinalTx(tx))
163 COrphan* porphan = NULL;
164 double dPriority = 0;
165 int64_t nTotalIn = 0;
166 bool fMissingInputs = false;
167 BOOST_FOREACH(const CTxIn& txin, tx.vin)
169 // Read prev transaction
170 if (!view.HaveCoins(txin.prevout.hash))
172 // This should never happen; all transactions in the memory
173 // pool should connect to either transactions in the chain
174 // or other transactions in the memory pool.
175 if (!mempool.mapTx.count(txin.prevout.hash))
177 LogPrintf("ERROR: mempool transaction missing input\n");
178 if (fDebug) assert("mempool transaction missing input" == 0);
179 fMissingInputs = true;
185 // Has to wait for dependencies
188 // Use list for automatic deletion
189 vOrphan.push_back(COrphan(&tx));
190 porphan = &vOrphan.back();
192 mapDependers[txin.prevout.hash].push_back(porphan);
193 porphan->setDependsOn.insert(txin.prevout.hash);
194 nTotalIn += mempool.mapTx[txin.prevout.hash].GetTx().vout[txin.prevout.n].nValue;
197 const CCoins &coins = view.GetCoins(txin.prevout.hash);
199 int64_t nValueIn = coins.vout[txin.prevout.n].nValue;
200 nTotalIn += nValueIn;
202 int nConf = pindexPrev->nHeight - coins.nHeight + 1;
204 dPriority += (double)nValueIn * nConf;
206 if (fMissingInputs) continue;
208 // Priority is sum(valuein * age) / modified_txsize
209 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
210 dPriority = tx.ComputePriority(dPriority, nTxSize);
212 // This is a more accurate fee-per-kilobyte than is used by the client code, because the
213 // client code rounds up the size to the nearest 1K. That's good, because it gives an
214 // incentive to create smaller transactions.
215 double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
219 porphan->dPriority = dPriority;
220 porphan->dFeePerKb = dFeePerKb;
223 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &mi->second.GetTx()));
226 // Collect transactions into block
227 uint64_t nBlockSize = 1000;
228 uint64_t nBlockTx = 0;
229 int nBlockSigOps = 100;
230 bool fSortedByFee = (nBlockPrioritySize <= 0);
232 TxPriorityCompare comparer(fSortedByFee);
233 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
235 while (!vecPriority.empty())
237 // Take highest priority transaction off the priority queue:
238 double dPriority = vecPriority.front().get<0>();
239 double dFeePerKb = vecPriority.front().get<1>();
240 const CTransaction& tx = *(vecPriority.front().get<2>());
242 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
243 vecPriority.pop_back();
246 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
247 if (nBlockSize + nTxSize >= nBlockMaxSize)
250 // Legacy limits on sigOps:
251 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
252 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
255 // Skip free transactions if we're past the minimum block size:
256 if (fSortedByFee && (dFeePerKb < CTransaction::nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
259 // Prioritize by fee once past the priority size or we run out of high-priority
262 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
265 comparer = TxPriorityCompare(fSortedByFee);
266 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
269 if (!view.HaveInputs(tx))
272 int64_t nTxFees = view.GetValueIn(tx)-tx.GetValueOut();
274 nTxSigOps += GetP2SHSigOpCount(tx, view);
275 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
278 CValidationState state;
279 if (!CheckInputs(tx, state, view, true, SCRIPT_VERIFY_P2SH))
283 uint256 hash = tx.GetHash();
284 UpdateCoins(tx, state, view, txundo, pindexPrev->nHeight+1, hash);
287 pblock->vtx.push_back(tx);
288 pblocktemplate->vTxFees.push_back(nTxFees);
289 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
290 nBlockSize += nTxSize;
292 nBlockSigOps += nTxSigOps;
297 LogPrintf("priority %.1f feeperkb %.1f txid %s\n",
298 dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
301 // Add transactions that depend on this one to the priority queue
302 if (mapDependers.count(hash))
304 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
306 if (!porphan->setDependsOn.empty())
308 porphan->setDependsOn.erase(hash);
309 if (porphan->setDependsOn.empty())
311 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
312 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
319 nLastBlockTx = nBlockTx;
320 nLastBlockSize = nBlockSize;
321 LogPrintf("CreateNewBlock(): total size %"PRIu64"\n", nBlockSize);
323 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
324 pblocktemplate->vTxFees[0] = -nFees;
327 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
328 UpdateTime(*pblock, pindexPrev);
329 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock);
331 pblock->vtx[0].vin[0].scriptSig = CScript() << OP_0 << OP_0;
332 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
334 CBlockIndex indexDummy(*pblock);
335 indexDummy.pprev = pindexPrev;
336 indexDummy.nHeight = pindexPrev->nHeight + 1;
337 CCoinsViewCache viewNew(*pcoinsTip, true);
338 CValidationState state;
339 if (!ConnectBlock(*pblock, state, &indexDummy, viewNew, true))
340 throw std::runtime_error("CreateNewBlock() : ConnectBlock failed");
343 return pblocktemplate.release();
346 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
348 // Update nExtraNonce
349 static uint256 hashPrevBlock;
350 if (hashPrevBlock != pblock->hashPrevBlock)
353 hashPrevBlock = pblock->hashPrevBlock;
356 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
357 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
358 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
360 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
364 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
367 // Pre-build hash buffers
374 uint256 hashPrevBlock;
375 uint256 hashMerkleRoot;
381 unsigned char pchPadding0[64];
383 unsigned char pchPadding1[64];
386 memset(&tmp, 0, sizeof(tmp));
388 tmp.block.nVersion = pblock->nVersion;
389 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
390 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
391 tmp.block.nTime = pblock->nTime;
392 tmp.block.nBits = pblock->nBits;
393 tmp.block.nNonce = pblock->nNonce;
395 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
396 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
398 // Byte swap all the input buffer
399 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
400 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
402 // Precalc the first half of the first hash, which stays constant
403 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
405 memcpy(pdata, &tmp.block, 128);
406 memcpy(phash1, &tmp.hash1, 64);
410 //////////////////////////////////////////////////////////////////////////////
414 double dHashesPerSec = 0.0;
415 int64_t nHPSTimerStart = 0;
418 // ScanHash scans nonces looking for a hash with at least some zero bits.
419 // It operates on big endian data. Caller does the byte reversing.
420 // All input buffers are 16-byte aligned. nNonce is usually preserved
421 // between calls, but periodically or if nNonce is 0xffff0000 or above,
422 // the block is rebuilt and nNonce starts over at zero.
424 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
426 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
430 // Hash pdata using pmidstate as the starting state into
431 // pre-formatted buffer phash1, then hash phash1 into phash
433 SHA256Transform(phash1, pdata, pmidstate);
434 SHA256Transform(phash, phash1, pSHA256InitState);
436 // Return the nonce if the hash has at least some zero bits,
437 // caller will check if it has enough to reach the target
438 if (((unsigned short*)phash)[14] == 0)
441 // If nothing found after trying for a while, return -1
442 if ((nNonce & 0xffff) == 0)
444 nHashesDone = 0xffff+1;
445 return (unsigned int) -1;
447 if ((nNonce & 0xfff) == 0)
448 boost::this_thread::interruption_point();
452 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
455 if (!reservekey.GetReservedKey(pubkey))
458 CScript scriptPubKey = CScript() << pubkey << OP_CHECKSIG;
459 return CreateNewBlock(scriptPubKey);
462 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
464 uint256 hash = pblock->GetHash();
465 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
467 if (hash > hashTarget)
471 LogPrintf("BitcoinMiner:\n");
472 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
474 LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
479 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
480 return error("BitcoinMiner : generated block is stale");
482 // Remove key from key pool
483 reservekey.KeepKey();
485 // Track how many getdata requests this block gets
487 LOCK(wallet.cs_wallet);
488 wallet.mapRequestCount[pblock->GetHash()] = 0;
491 // Process this block the same as if we had received it from another node
492 CValidationState state;
493 if (!ProcessBlock(state, NULL, pblock))
494 return error("BitcoinMiner : ProcessBlock, block not accepted");
500 void static BitcoinMiner(CWallet *pwallet)
502 LogPrintf("BitcoinMiner started\n");
503 SetThreadPriority(THREAD_PRIORITY_LOWEST);
504 RenameThread("bitcoin-miner");
506 // Each thread has its own key and counter
507 CReserveKey reservekey(pwallet);
508 unsigned int nExtraNonce = 0;
511 if (Params().NetworkID() != CChainParams::REGTEST) {
512 // Busy-wait for the network to come online so we don't waste time mining
513 // on an obsolete chain. In regtest mode we expect to fly solo.
514 while (vNodes.empty())
521 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
522 CBlockIndex* pindexPrev = chainActive.Tip();
524 auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
525 if (!pblocktemplate.get())
527 CBlock *pblock = &pblocktemplate->block;
528 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
530 LogPrintf("Running BitcoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
531 ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
534 // Pre-build hash buffers
536 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
537 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
538 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
540 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
542 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
543 unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
544 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
550 int64_t nStart = GetTime();
551 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
553 uint256& hash = *alignup<16>(hashbuf);
556 unsigned int nHashesDone = 0;
557 unsigned int nNonceFound;
560 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
561 (char*)&hash, nHashesDone);
563 // Check if something found
564 if (nNonceFound != (unsigned int) -1)
566 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
567 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
569 if (hash <= hashTarget)
572 pblock->nNonce = ByteReverse(nNonceFound);
573 assert(hash == pblock->GetHash());
575 SetThreadPriority(THREAD_PRIORITY_NORMAL);
576 CheckWork(pblock, *pwallet, reservekey);
577 SetThreadPriority(THREAD_PRIORITY_LOWEST);
579 // In regression test mode, stop mining after a block is found. This
580 // allows developers to controllably generate a block on demand.
581 if (Params().NetworkID() == CChainParams::REGTEST)
582 throw boost::thread_interrupted();
589 static int64_t nHashCounter;
590 if (nHPSTimerStart == 0)
592 nHPSTimerStart = GetTimeMillis();
596 nHashCounter += nHashesDone;
597 if (GetTimeMillis() - nHPSTimerStart > 4000)
599 static CCriticalSection cs;
602 if (GetTimeMillis() - nHPSTimerStart > 4000)
604 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
605 nHPSTimerStart = GetTimeMillis();
607 static int64_t nLogTime;
608 if (GetTime() - nLogTime > 30 * 60)
610 nLogTime = GetTime();
611 LogPrintf("hashmeter %6.0f khash/s\n", dHashesPerSec/1000.0);
617 // Check for stop or if block needs to be rebuilt
618 boost::this_thread::interruption_point();
619 if (vNodes.empty() && Params().NetworkID() != CChainParams::REGTEST)
621 if (nBlockNonce >= 0xffff0000)
623 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
625 if (pindexPrev != chainActive.Tip())
628 // Update nTime every few seconds
629 UpdateTime(*pblock, pindexPrev);
630 nBlockTime = ByteReverse(pblock->nTime);
633 // Changing pblock->nTime can change work required on testnet:
634 nBlockBits = ByteReverse(pblock->nBits);
635 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
639 catch (boost::thread_interrupted)
641 LogPrintf("BitcoinMiner terminated\n");
646 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
648 static boost::thread_group* minerThreads = NULL;
651 if (Params().NetworkID() == CChainParams::REGTEST)
654 nThreads = boost::thread::hardware_concurrency();
657 if (minerThreads != NULL)
659 minerThreads->interrupt_all();
664 if (nThreads == 0 || !fGenerate)
667 minerThreads = new boost::thread_group();
668 for (int i = 0; i < nThreads; i++)
669 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));