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 double dHashesPerSec = 0.0;
14 int64_t nHPSTimerStart = 0;
16 //////////////////////////////////////////////////////////////////////////////
21 int static FormatHashBlocks(void* pbuffer, unsigned int len)
23 unsigned char* pdata = (unsigned char*)pbuffer;
24 unsigned int blocks = 1 + ((len + 8) / 64);
25 unsigned char* pend = pdata + 64 * blocks;
26 memset(pdata + len, 0, 64 * blocks - len);
28 unsigned int bits = len * 8;
29 pend[-1] = (bits >> 0) & 0xff;
30 pend[-2] = (bits >> 8) & 0xff;
31 pend[-3] = (bits >> 16) & 0xff;
32 pend[-4] = (bits >> 24) & 0xff;
36 static const unsigned int pSHA256InitState[8] =
37 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
39 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
42 unsigned char data[64];
46 for (int i = 0; i < 16; i++)
47 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
49 for (int i = 0; i < 8; i++)
50 ctx.h[i] = ((uint32_t*)pinit)[i];
52 SHA256_Update(&ctx, data, sizeof(data));
53 for (int i = 0; i < 8; i++)
54 ((uint32_t*)pstate)[i] = ctx.h[i];
58 // ScanHash scans nonces looking for a hash with at least some zero bits.
59 // It operates on big endian data. Caller does the byte reversing.
60 // All input buffers are 16-byte aligned. nNonce is usually preserved
61 // between calls, but periodically or if nNonce is 0xffff0000 or above,
62 // the block is rebuilt and nNonce starts over at zero.
64 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
66 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
70 // Hash pdata using pmidstate as the starting state into
71 // pre-formatted buffer phash1, then hash phash1 into phash
73 SHA256Transform(phash1, pdata, pmidstate);
74 SHA256Transform(phash, phash1, pSHA256InitState);
76 // Return the nonce if the hash has at least some zero bits,
77 // caller will check if it has enough to reach the target
78 if (((unsigned short*)phash)[14] == 0)
81 // If nothing found after trying for a while, return -1
82 if ((nNonce & 0xffff) == 0)
84 nHashesDone = 0xffff+1;
85 return (unsigned int) -1;
87 if ((nNonce & 0xfff) == 0)
88 boost::this_thread::interruption_point();
92 // Some explaining would be appreciated
97 set<uint256> setDependsOn;
101 COrphan(CTransaction* ptxIn)
104 dPriority = dFeePerKb = 0;
109 LogPrintf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
110 ptx->GetHash().ToString().c_str(), dPriority, dFeePerKb);
111 BOOST_FOREACH(uint256 hash, setDependsOn)
112 LogPrintf(" setDependsOn %s\n", hash.ToString().c_str());
117 uint64_t nLastBlockTx = 0;
118 uint64_t nLastBlockSize = 0;
120 // We want to sort transactions by priority and fee, so:
121 typedef boost::tuple<double, double, CTransaction*> TxPriority;
122 class TxPriorityCompare
126 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
127 bool operator()(const TxPriority& a, const TxPriority& b)
131 if (a.get<1>() == b.get<1>())
132 return a.get<0>() < b.get<0>();
133 return a.get<1>() < b.get<1>();
137 if (a.get<0>() == b.get<0>())
138 return a.get<1>() < b.get<1>();
139 return a.get<0>() < b.get<0>();
144 CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
147 auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
148 if(!pblocktemplate.get())
150 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
152 // Create coinbase tx
155 txNew.vin[0].prevout.SetNull();
156 txNew.vout.resize(1);
157 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
159 // Add our coinbase tx as first transaction
160 pblock->vtx.push_back(txNew);
161 pblocktemplate->vTxFees.push_back(-1); // updated at end
162 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
164 // Largest block you're willing to create:
165 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
166 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
167 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
169 // How much of the block should be dedicated to high-priority transactions,
170 // included regardless of the fees they pay
171 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
172 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
174 // Minimum block size you want to create; block will be filled with free transactions
175 // until there are no more or the block reaches this size:
176 unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
177 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
179 // Collect memory pool transactions into the block
182 LOCK2(cs_main, mempool.cs);
183 CBlockIndex* pindexPrev = chainActive.Tip();
184 CCoinsViewCache view(*pcoinsTip, true);
186 // Priority order to process transactions
187 list<COrphan> vOrphan; // list memory doesn't move
188 map<uint256, vector<COrphan*> > mapDependers;
189 bool fPrintPriority = GetBoolArg("-printpriority", false);
191 // This vector will be sorted into a priority queue:
192 vector<TxPriority> vecPriority;
193 vecPriority.reserve(mempool.mapTx.size());
194 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
196 CTransaction& tx = (*mi).second;
197 if (tx.IsCoinBase() || !IsFinalTx(tx))
200 COrphan* porphan = NULL;
201 double dPriority = 0;
202 int64_t nTotalIn = 0;
203 bool fMissingInputs = false;
204 BOOST_FOREACH(const CTxIn& txin, tx.vin)
206 // Read prev transaction
207 if (!view.HaveCoins(txin.prevout.hash))
209 // This should never happen; all transactions in the memory
210 // pool should connect to either transactions in the chain
211 // or other transactions in the memory pool.
212 if (!mempool.mapTx.count(txin.prevout.hash))
214 LogPrintf("ERROR: mempool transaction missing input\n");
215 if (fDebug) assert("mempool transaction missing input" == 0);
216 fMissingInputs = true;
222 // Has to wait for dependencies
225 // Use list for automatic deletion
226 vOrphan.push_back(COrphan(&tx));
227 porphan = &vOrphan.back();
229 mapDependers[txin.prevout.hash].push_back(porphan);
230 porphan->setDependsOn.insert(txin.prevout.hash);
231 nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
234 const CCoins &coins = view.GetCoins(txin.prevout.hash);
236 int64_t nValueIn = coins.vout[txin.prevout.n].nValue;
237 nTotalIn += nValueIn;
239 int nConf = pindexPrev->nHeight - coins.nHeight + 1;
241 dPriority += (double)nValueIn * nConf;
243 if (fMissingInputs) continue;
245 // Priority is sum(valuein * age) / modified_txsize
246 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
247 unsigned int nTxSizeMod = nTxSize;
248 // In order to avoid disincentivizing cleaning up the UTXO set we don't count
249 // the constant overhead for each txin and up to 110 bytes of scriptSig (which
250 // is enough to cover a compressed pubkey p2sh redemption) for priority.
251 // Providing any more cleanup incentive than making additional inputs free would
252 // risk encouraging people to create junk outputs to redeem later.
253 BOOST_FOREACH(const CTxIn& txin, tx.vin)
255 unsigned int offset = 41U + min(110U, (unsigned int)txin.scriptSig.size());
256 if (nTxSizeMod > offset)
257 nTxSizeMod -= offset;
259 dPriority /= nTxSizeMod;
261 // This is a more accurate fee-per-kilobyte than is used by the client code, because the
262 // client code rounds up the size to the nearest 1K. That's good, because it gives an
263 // incentive to create smaller transactions.
264 double dFeePerKb = double(nTotalIn-GetValueOut(tx)) / (double(nTxSize)/1000.0);
268 porphan->dPriority = dPriority;
269 porphan->dFeePerKb = dFeePerKb;
272 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
275 // Collect transactions into block
276 uint64_t nBlockSize = 1000;
277 uint64_t nBlockTx = 0;
278 int nBlockSigOps = 100;
279 bool fSortedByFee = (nBlockPrioritySize <= 0);
281 TxPriorityCompare comparer(fSortedByFee);
282 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
284 while (!vecPriority.empty())
286 // Take highest priority transaction off the priority queue:
287 double dPriority = vecPriority.front().get<0>();
288 double dFeePerKb = vecPriority.front().get<1>();
289 CTransaction& tx = *(vecPriority.front().get<2>());
291 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
292 vecPriority.pop_back();
295 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
296 if (nBlockSize + nTxSize >= nBlockMaxSize)
299 // Legacy limits on sigOps:
300 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
301 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
304 // Skip free transactions if we're past the minimum block size:
305 if (fSortedByFee && (dFeePerKb < CTransaction::nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
308 // Prioritize by fee once past the priority size or we run out of high-priority
311 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
314 comparer = TxPriorityCompare(fSortedByFee);
315 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
318 if (!view.HaveInputs(tx))
321 int64_t nTxFees = view.GetValueIn(tx)-GetValueOut(tx);
323 nTxSigOps += GetP2SHSigOpCount(tx, view);
324 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
327 CValidationState state;
328 if (!CheckInputs(tx, state, view, true, SCRIPT_VERIFY_P2SH))
332 uint256 hash = tx.GetHash();
333 UpdateCoins(tx, state, view, txundo, pindexPrev->nHeight+1, hash);
336 pblock->vtx.push_back(tx);
337 pblocktemplate->vTxFees.push_back(nTxFees);
338 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
339 nBlockSize += nTxSize;
341 nBlockSigOps += nTxSigOps;
346 LogPrintf("priority %.1f feeperkb %.1f txid %s\n",
347 dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
350 // Add transactions that depend on this one to the priority queue
351 if (mapDependers.count(hash))
353 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
355 if (!porphan->setDependsOn.empty())
357 porphan->setDependsOn.erase(hash);
358 if (porphan->setDependsOn.empty())
360 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
361 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
368 nLastBlockTx = nBlockTx;
369 nLastBlockSize = nBlockSize;
370 LogPrintf("CreateNewBlock(): total size %"PRIu64"\n", nBlockSize);
372 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
373 pblocktemplate->vTxFees[0] = -nFees;
376 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
377 UpdateTime(*pblock, pindexPrev);
378 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock);
380 pblock->vtx[0].vin[0].scriptSig = CScript() << OP_0 << OP_0;
381 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
383 CBlockIndex indexDummy(*pblock);
384 indexDummy.pprev = pindexPrev;
385 indexDummy.nHeight = pindexPrev->nHeight + 1;
386 CCoinsViewCache viewNew(*pcoinsTip, true);
387 CValidationState state;
388 if (!ConnectBlock(*pblock, state, &indexDummy, viewNew, true))
389 throw std::runtime_error("CreateNewBlock() : ConnectBlock failed");
392 return pblocktemplate.release();
395 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
398 if (!reservekey.GetReservedKey(pubkey))
401 CScript scriptPubKey = CScript() << pubkey << OP_CHECKSIG;
402 return CreateNewBlock(scriptPubKey);
405 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
407 // Update nExtraNonce
408 static uint256 hashPrevBlock;
409 if (hashPrevBlock != pblock->hashPrevBlock)
412 hashPrevBlock = pblock->hashPrevBlock;
415 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
416 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
417 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
419 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
423 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
426 // Pre-build hash buffers
433 uint256 hashPrevBlock;
434 uint256 hashMerkleRoot;
440 unsigned char pchPadding0[64];
442 unsigned char pchPadding1[64];
445 memset(&tmp, 0, sizeof(tmp));
447 tmp.block.nVersion = pblock->nVersion;
448 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
449 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
450 tmp.block.nTime = pblock->nTime;
451 tmp.block.nBits = pblock->nBits;
452 tmp.block.nNonce = pblock->nNonce;
454 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
455 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
457 // Byte swap all the input buffer
458 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
459 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
461 // Precalc the first half of the first hash, which stays constant
462 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
464 memcpy(pdata, &tmp.block, 128);
465 memcpy(phash1, &tmp.hash1, 64);
469 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
471 uint256 hash = pblock->GetHash();
472 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
474 if (hash > hashTarget)
478 LogPrintf("BitcoinMiner:\n");
479 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
481 LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
486 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
487 return error("BitcoinMiner : generated block is stale");
489 // Remove key from key pool
490 reservekey.KeepKey();
492 // Track how many getdata requests this block gets
494 LOCK(wallet.cs_wallet);
495 wallet.mapRequestCount[pblock->GetHash()] = 0;
498 // Process this block the same as if we had received it from another node
499 CValidationState state;
500 if (!ProcessBlock(state, NULL, pblock))
501 return error("BitcoinMiner : ProcessBlock, block not accepted");
507 void static BitcoinMiner(CWallet *pwallet)
509 LogPrintf("BitcoinMiner started\n");
510 SetThreadPriority(THREAD_PRIORITY_LOWEST);
511 RenameThread("bitcoin-miner");
513 // Each thread has its own key and counter
514 CReserveKey reservekey(pwallet);
515 unsigned int nExtraNonce = 0;
518 if (Params().NetworkID() != CChainParams::REGTEST) {
519 // Busy-wait for the network to come online so we don't waste time mining
520 // on an obsolete chain. In regtest mode we expect to fly solo.
521 while (vNodes.empty())
528 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
529 CBlockIndex* pindexPrev = chainActive.Tip();
531 auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
532 if (!pblocktemplate.get())
534 CBlock *pblock = &pblocktemplate->block;
535 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
537 LogPrintf("Running BitcoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
538 ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
541 // Pre-build hash buffers
543 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
544 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
545 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
547 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
549 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
550 unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
551 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
557 int64_t nStart = GetTime();
558 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
560 uint256& hash = *alignup<16>(hashbuf);
563 unsigned int nHashesDone = 0;
564 unsigned int nNonceFound;
567 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
568 (char*)&hash, nHashesDone);
570 // Check if something found
571 if (nNonceFound != (unsigned int) -1)
573 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
574 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
576 if (hash <= hashTarget)
579 pblock->nNonce = ByteReverse(nNonceFound);
580 assert(hash == pblock->GetHash());
582 SetThreadPriority(THREAD_PRIORITY_NORMAL);
583 CheckWork(pblock, *pwallet, reservekey);
584 SetThreadPriority(THREAD_PRIORITY_LOWEST);
586 // In regression test mode, stop mining after a block is found. This
587 // allows developers to controllably generate a block on demand.
588 if (Params().NetworkID() == CChainParams::REGTEST)
589 throw boost::thread_interrupted();
596 static int64_t nHashCounter;
597 if (nHPSTimerStart == 0)
599 nHPSTimerStart = GetTimeMillis();
603 nHashCounter += nHashesDone;
604 if (GetTimeMillis() - nHPSTimerStart > 4000)
606 static CCriticalSection cs;
609 if (GetTimeMillis() - nHPSTimerStart > 4000)
611 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
612 nHPSTimerStart = GetTimeMillis();
614 static int64_t nLogTime;
615 if (GetTime() - nLogTime > 30 * 60)
617 nLogTime = GetTime();
618 LogPrintf("hashmeter %6.0f khash/s\n", dHashesPerSec/1000.0);
624 // Check for stop or if block needs to be rebuilt
625 boost::this_thread::interruption_point();
626 if (vNodes.empty() && Params().NetworkID() != CChainParams::REGTEST)
628 if (nBlockNonce >= 0xffff0000)
630 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
632 if (pindexPrev != chainActive.Tip())
635 // Update nTime every few seconds
636 UpdateTime(*pblock, pindexPrev);
637 nBlockTime = ByteReverse(pblock->nTime);
640 // Changing pblock->nTime can change work required on testnet:
641 nBlockBits = ByteReverse(pblock->nBits);
642 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
646 catch (boost::thread_interrupted)
648 LogPrintf("BitcoinMiner terminated\n");
653 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
655 static boost::thread_group* minerThreads = NULL;
657 int nThreads = GetArg("-genproclimit", -1);
659 if (Params().NetworkID() == CChainParams::REGTEST)
662 nThreads = boost::thread::hardware_concurrency();
665 if (minerThreads != NULL)
667 minerThreads->interrupt_all();
672 if (nThreads == 0 || !fGenerate)
675 minerThreads = new boost::thread_group();
676 for (int i = 0; i < nThreads; i++)
677 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));