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.
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 = chainActive.Tip();
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) / modified_txsize
242 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
243 unsigned int nTxSizeMod = nTxSize;
244 // In order to avoid disincentivizing cleaning up the UTXO set we don't count
245 // the constant overhead for each txin and up to 110 bytes of scriptSig (which
246 // is enough to cover a compressed pubkey p2sh redemption) for priority.
247 // Providing any more cleanup incentive than making additional inputs free would
248 // risk encouraging people to create junk outputs to redeem later.
249 BOOST_FOREACH(const CTxIn& txin, tx.vin)
251 unsigned int offset = 41U + min(110U, (unsigned int)txin.scriptSig.size());
252 if (nTxSizeMod > offset)
253 nTxSizeMod -= offset;
255 dPriority /= nTxSizeMod;
257 // This is a more accurate fee-per-kilobyte than is used by the client code, because the
258 // client code rounds up the size to the nearest 1K. That's good, because it gives an
259 // incentive to create smaller transactions.
260 double dFeePerKb = double(nTotalIn-GetValueOut(tx)) / (double(nTxSize)/1000.0);
264 porphan->dPriority = dPriority;
265 porphan->dFeePerKb = dFeePerKb;
268 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
271 // Collect transactions into block
272 uint64 nBlockSize = 1000;
274 int nBlockSigOps = 100;
275 bool fSortedByFee = (nBlockPrioritySize <= 0);
277 TxPriorityCompare comparer(fSortedByFee);
278 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
280 while (!vecPriority.empty())
282 // Take highest priority transaction off the priority queue:
283 double dPriority = vecPriority.front().get<0>();
284 double dFeePerKb = vecPriority.front().get<1>();
285 CTransaction& tx = *(vecPriority.front().get<2>());
287 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
288 vecPriority.pop_back();
291 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
292 if (nBlockSize + nTxSize >= nBlockMaxSize)
295 // Legacy limits on sigOps:
296 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
297 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
300 // Skip free transactions if we're past the minimum block size:
301 if (fSortedByFee && (dFeePerKb < CTransaction::nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
304 // Prioritize by fee once past the priority size or we run out of high-priority
307 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
310 comparer = TxPriorityCompare(fSortedByFee);
311 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
314 if (!view.HaveInputs(tx))
317 int64 nTxFees = view.GetValueIn(tx)-GetValueOut(tx);
319 nTxSigOps += GetP2SHSigOpCount(tx, view);
320 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
323 CValidationState state;
324 if (!CheckInputs(tx, state, view, true, SCRIPT_VERIFY_P2SH))
328 uint256 hash = tx.GetHash();
329 UpdateCoins(tx, state, view, txundo, pindexPrev->nHeight+1, hash);
332 pblock->vtx.push_back(tx);
333 pblocktemplate->vTxFees.push_back(nTxFees);
334 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
335 nBlockSize += nTxSize;
337 nBlockSigOps += nTxSigOps;
342 LogPrintf("priority %.1f feeperkb %.1f txid %s\n",
343 dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
346 // Add transactions that depend on this one to the priority queue
347 if (mapDependers.count(hash))
349 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
351 if (!porphan->setDependsOn.empty())
353 porphan->setDependsOn.erase(hash);
354 if (porphan->setDependsOn.empty())
356 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
357 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
364 nLastBlockTx = nBlockTx;
365 nLastBlockSize = nBlockSize;
366 LogPrintf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
368 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
369 pblocktemplate->vTxFees[0] = -nFees;
372 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
373 UpdateTime(*pblock, pindexPrev);
374 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock);
376 pblock->vtx[0].vin[0].scriptSig = CScript() << OP_0 << OP_0;
377 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
379 CBlockIndex indexDummy(*pblock);
380 indexDummy.pprev = pindexPrev;
381 indexDummy.nHeight = pindexPrev->nHeight + 1;
382 CCoinsViewCache viewNew(*pcoinsTip, true);
383 CValidationState state;
384 if (!ConnectBlock(*pblock, state, &indexDummy, viewNew, true))
385 throw std::runtime_error("CreateNewBlock() : ConnectBlock failed");
388 return pblocktemplate.release();
391 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
394 if (!reservekey.GetReservedKey(pubkey))
397 CScript scriptPubKey = CScript() << pubkey << OP_CHECKSIG;
398 return CreateNewBlock(scriptPubKey);
401 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
403 // Update nExtraNonce
404 static uint256 hashPrevBlock;
405 if (hashPrevBlock != pblock->hashPrevBlock)
408 hashPrevBlock = pblock->hashPrevBlock;
411 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
412 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
413 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
415 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
419 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
422 // Pre-build hash buffers
429 uint256 hashPrevBlock;
430 uint256 hashMerkleRoot;
436 unsigned char pchPadding0[64];
438 unsigned char pchPadding1[64];
441 memset(&tmp, 0, sizeof(tmp));
443 tmp.block.nVersion = pblock->nVersion;
444 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
445 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
446 tmp.block.nTime = pblock->nTime;
447 tmp.block.nBits = pblock->nBits;
448 tmp.block.nNonce = pblock->nNonce;
450 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
451 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
453 // Byte swap all the input buffer
454 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
455 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
457 // Precalc the first half of the first hash, which stays constant
458 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
460 memcpy(pdata, &tmp.block, 128);
461 memcpy(phash1, &tmp.hash1, 64);
465 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
467 uint256 hash = pblock->GetHash();
468 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
470 if (hash > hashTarget)
474 LogPrintf("BitcoinMiner:\n");
475 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
477 LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
482 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
483 return error("BitcoinMiner : generated block is stale");
485 // Remove key from key pool
486 reservekey.KeepKey();
488 // Track how many getdata requests this block gets
490 LOCK(wallet.cs_wallet);
491 wallet.mapRequestCount[pblock->GetHash()] = 0;
494 // Process this block the same as if we had received it from another node
495 CValidationState state;
496 if (!ProcessBlock(state, NULL, pblock))
497 return error("BitcoinMiner : ProcessBlock, block not accepted");
503 void static BitcoinMiner(CWallet *pwallet)
505 LogPrintf("BitcoinMiner started\n");
506 SetThreadPriority(THREAD_PRIORITY_LOWEST);
507 RenameThread("bitcoin-miner");
509 // Each thread has its own key and counter
510 CReserveKey reservekey(pwallet);
511 unsigned int nExtraNonce = 0;
514 if (Params().NetworkID() != CChainParams::REGTEST) {
515 // Busy-wait for the network to come online so we don't waste time mining
516 // on an obsolete chain. In regtest mode we expect to fly solo.
517 while (vNodes.empty())
524 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
525 CBlockIndex* pindexPrev = chainActive.Tip();
527 auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
528 if (!pblocktemplate.get())
530 CBlock *pblock = &pblocktemplate->block;
531 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
533 LogPrintf("Running BitcoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
534 ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
537 // Pre-build hash buffers
539 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
540 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
541 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
543 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
545 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
546 unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
547 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
553 int64 nStart = GetTime();
554 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
556 uint256& hash = *alignup<16>(hashbuf);
559 unsigned int nHashesDone = 0;
560 unsigned int nNonceFound;
563 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
564 (char*)&hash, nHashesDone);
566 // Check if something found
567 if (nNonceFound != (unsigned int) -1)
569 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
570 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
572 if (hash <= hashTarget)
575 pblock->nNonce = ByteReverse(nNonceFound);
576 assert(hash == pblock->GetHash());
578 SetThreadPriority(THREAD_PRIORITY_NORMAL);
579 CheckWork(pblock, *pwallet, reservekey);
580 SetThreadPriority(THREAD_PRIORITY_LOWEST);
582 // In regression test mode, stop mining after a block is found. This
583 // allows developers to controllably generate a block on demand.
584 if (Params().NetworkID() == CChainParams::REGTEST)
585 throw boost::thread_interrupted();
592 static int64 nHashCounter;
593 if (nHPSTimerStart == 0)
595 nHPSTimerStart = GetTimeMillis();
599 nHashCounter += nHashesDone;
600 if (GetTimeMillis() - nHPSTimerStart > 4000)
602 static CCriticalSection cs;
605 if (GetTimeMillis() - nHPSTimerStart > 4000)
607 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
608 nHPSTimerStart = GetTimeMillis();
610 static int64 nLogTime;
611 if (GetTime() - nLogTime > 30 * 60)
613 nLogTime = GetTime();
614 LogPrintf("hashmeter %6.0f khash/s\n", dHashesPerSec/1000.0);
620 // Check for stop or if block needs to be rebuilt
621 boost::this_thread::interruption_point();
622 if (vNodes.empty() && Params().NetworkID() != CChainParams::REGTEST)
624 if (nBlockNonce >= 0xffff0000)
626 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
628 if (pindexPrev != chainActive.Tip())
631 // Update nTime every few seconds
632 UpdateTime(*pblock, pindexPrev);
633 nBlockTime = ByteReverse(pblock->nTime);
636 // Changing pblock->nTime can change work required on testnet:
637 nBlockBits = ByteReverse(pblock->nBits);
638 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
642 catch (boost::thread_interrupted)
644 LogPrintf("BitcoinMiner terminated\n");
649 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
651 static boost::thread_group* minerThreads = NULL;
653 int nThreads = GetArg("-genproclimit", -1);
655 if (Params().NetworkID() == CChainParams::REGTEST)
658 nThreads = boost::thread::hardware_concurrency();
661 if (minerThreads != NULL)
663 minerThreads->interrupt_all();
668 if (nThreads == 0 || !fGenerate)
671 minerThreads = new boost::thread_group();
672 for (int i = 0; i < nThreads; i++)
673 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));