1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
9 #include "chainparams.h"
10 #include "consensus/consensus.h"
11 #include "consensus/validation.h"
16 #include "primitives/transaction.h"
20 #include "utilmoneystr.h"
22 #include "crypto/equihash.h"
23 #include "wallet/wallet.h"
29 #include <boost/thread.hpp>
30 #include <boost/tuple/tuple.hpp>
35 //////////////////////////////////////////////////////////////////////////////
41 // Unconfirmed transactions in the memory pool often depend on other
42 // transactions in the memory pool. When we select transactions from the
43 // pool, we select by highest priority or fee rate, so we might consider
44 // transactions that depend on transactions that aren't yet in the block.
45 // The COrphan class keeps track of these 'temporary orphans' while
46 // CreateBlock is figuring out which transactions to include.
51 const CTransaction* ptx;
52 set<uint256> setDependsOn;
56 COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
61 uint64_t nLastBlockTx = 0;
62 uint64_t nLastBlockSize = 0;
64 // We want to sort transactions by priority and fee rate, so:
65 typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
66 class TxPriorityCompare
71 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
73 bool operator()(const TxPriority& a, const TxPriority& b)
77 if (a.get<1>() == b.get<1>())
78 return a.get<0>() < b.get<0>();
79 return a.get<1>() < b.get<1>();
83 if (a.get<0>() == b.get<0>())
84 return a.get<1>() < b.get<1>();
85 return a.get<0>() < b.get<0>();
90 void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
92 pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
94 // Updating time can change work required on testnet:
95 if (consensusParams.fPowAllowMinDifficultyBlocks)
96 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
99 CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
101 const CChainParams& chainparams = Params();
103 auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
104 if(!pblocktemplate.get())
106 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
108 // -regtest only: allow overriding block.nVersion with
109 // -blockversion=N to test forking scenarios
110 if (Params().MineBlocksOnDemand())
111 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
113 // Add dummy coinbase tx as first transaction
114 pblock->vtx.push_back(CTransaction());
115 pblocktemplate->vTxFees.push_back(-1); // updated at end
116 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
118 // Largest block you're willing to create:
119 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
120 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
121 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
123 // How much of the block should be dedicated to high-priority transactions,
124 // included regardless of the fees they pay
125 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
126 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
128 // Minimum block size you want to create; block will be filled with free transactions
129 // until there are no more or the block reaches this size:
130 unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
131 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
133 // Collect memory pool transactions into the block
137 LOCK2(cs_main, mempool.cs);
138 CBlockIndex* pindexPrev = chainActive.Tip();
139 const int nHeight = pindexPrev->nHeight + 1;
140 pblock->nTime = GetAdjustedTime();
141 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
142 CCoinsViewCache view(pcoinsTip);
144 // Priority order to process transactions
145 list<COrphan> vOrphan; // list memory doesn't move
146 map<uint256, vector<COrphan*> > mapDependers;
147 bool fPrintPriority = GetBoolArg("-printpriority", false);
149 // This vector will be sorted into a priority queue:
150 vector<TxPriority> vecPriority;
151 vecPriority.reserve(mempool.mapTx.size());
152 for (map<uint256, CTxMemPoolEntry>::iterator mi = mempool.mapTx.begin();
153 mi != mempool.mapTx.end(); ++mi)
155 const CTransaction& tx = mi->second.GetTx();
157 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
159 : pblock->GetBlockTime();
161 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff))
164 COrphan* porphan = NULL;
165 double dPriority = 0;
166 CAmount nTotalIn = 0;
167 bool fMissingInputs = false;
168 BOOST_FOREACH(const CTxIn& txin, tx.vin)
170 // Read prev transaction
171 if (!view.HaveCoins(txin.prevout.hash))
173 // This should never happen; all transactions in the memory
174 // pool should connect to either transactions in the chain
175 // or other transactions in the memory pool.
176 if (!mempool.mapTx.count(txin.prevout.hash))
178 LogPrintf("ERROR: mempool transaction missing input\n");
179 if (fDebug) assert("mempool transaction missing input" == 0);
180 fMissingInputs = true;
186 // Has to wait for dependencies
189 // Use list for automatic deletion
190 vOrphan.push_back(COrphan(&tx));
191 porphan = &vOrphan.back();
193 mapDependers[txin.prevout.hash].push_back(porphan);
194 porphan->setDependsOn.insert(txin.prevout.hash);
195 nTotalIn += mempool.mapTx[txin.prevout.hash].GetTx().vout[txin.prevout.n].nValue;
198 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
201 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
202 nTotalIn += nValueIn;
204 int nConf = nHeight - coins->nHeight;
206 dPriority += (double)nValueIn * nConf;
208 if (fMissingInputs) continue;
210 // Priority is sum(valuein * age) / modified_txsize
211 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
212 dPriority = tx.ComputePriority(dPriority, nTxSize);
214 uint256 hash = tx.GetHash();
215 mempool.ApplyDeltas(hash, dPriority, nTotalIn);
217 CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
221 porphan->dPriority = dPriority;
222 porphan->feeRate = feeRate;
225 vecPriority.push_back(TxPriority(dPriority, feeRate, &mi->second.GetTx()));
228 // Collect transactions into block
229 uint64_t nBlockSize = 1000;
230 uint64_t nBlockTx = 0;
231 int nBlockSigOps = 100;
232 bool fSortedByFee = (nBlockPrioritySize <= 0);
234 TxPriorityCompare comparer(fSortedByFee);
235 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
237 while (!vecPriority.empty())
239 // Take highest priority transaction off the priority queue:
240 double dPriority = vecPriority.front().get<0>();
241 CFeeRate feeRate = vecPriority.front().get<1>();
242 const CTransaction& tx = *(vecPriority.front().get<2>());
244 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
245 vecPriority.pop_back();
248 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
249 if (nBlockSize + nTxSize >= nBlockMaxSize)
252 // Legacy limits on sigOps:
253 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
254 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
257 // Skip free transactions if we're past the minimum block size:
258 const uint256& hash = tx.GetHash();
259 double dPriorityDelta = 0;
260 CAmount nFeeDelta = 0;
261 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
262 if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
265 // Prioritise by fee once past the priority size or we run out of high-priority
268 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
271 comparer = TxPriorityCompare(fSortedByFee);
272 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
275 if (!view.HaveInputs(tx))
278 CAmount nTxFees = view.GetValueIn(tx)-tx.GetValueOut();
280 nTxSigOps += GetP2SHSigOpCount(tx, view);
281 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
284 // Note that flags: we don't want to set mempool/IsStandard()
285 // policy here, but we still have to ensure that the block we
286 // create only contains transactions that are valid in new blocks.
287 CValidationState state;
288 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
291 UpdateCoins(tx, state, view, nHeight);
294 pblock->vtx.push_back(tx);
295 pblocktemplate->vTxFees.push_back(nTxFees);
296 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
297 nBlockSize += nTxSize;
299 nBlockSigOps += nTxSigOps;
304 LogPrintf("priority %.1f fee %s txid %s\n",
305 dPriority, feeRate.ToString(), tx.GetHash().ToString());
308 // Add transactions that depend on this one to the priority queue
309 if (mapDependers.count(hash))
311 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
313 if (!porphan->setDependsOn.empty())
315 porphan->setDependsOn.erase(hash);
316 if (porphan->setDependsOn.empty())
318 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
319 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
326 nLastBlockTx = nBlockTx;
327 nLastBlockSize = nBlockSize;
328 LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize);
330 // Create coinbase tx
331 CMutableTransaction txNew;
333 txNew.vin[0].prevout.SetNull();
334 txNew.vout.resize(1);
335 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
336 txNew.vout[0].nValue = GetBlockSubsidy(nHeight, chainparams.GetConsensus());
338 if ((nHeight > 0) && (nHeight < chainparams.GetConsensus().nSubsidyHalvingInterval)) {
339 // Founders reward is 20% of the block subsidy
340 auto vFoundersReward = txNew.vout[0].nValue / 5;
341 // Take some reward away from us
342 txNew.vout[0].nValue -= vFoundersReward;
344 auto rewardScript = ParseHex(FOUNDERS_REWARD_SCRIPT);
346 // And give it to the founders
347 txNew.vout.push_back(CTxOut(vFoundersReward, CScript(rewardScript.begin(),
348 rewardScript.end())));
352 txNew.vout[0].nValue += nFees;
353 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
355 pblock->vtx[0] = txNew;
356 pblocktemplate->vTxFees[0] = -nFees;
359 arith_uint256 nonce = UintToArith256(GetRandHash());
360 // Clear the top and bottom 16 bits (for local use as thread flags and counters)
363 pblock->nNonce = ArithToUint256(nonce);
366 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
367 pblock->hashReserved = uint256();
368 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
369 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
370 pblock->nSolution.clear();
371 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
373 CValidationState state;
374 if (!TestBlockValidity(state, *pblock, pindexPrev, false, false))
375 throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed");
378 return pblocktemplate.release();
381 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
383 // Update nExtraNonce
384 static uint256 hashPrevBlock;
385 if (hashPrevBlock != pblock->hashPrevBlock)
388 hashPrevBlock = pblock->hashPrevBlock;
391 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
392 CMutableTransaction txCoinbase(pblock->vtx[0]);
393 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
394 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
396 pblock->vtx[0] = txCoinbase;
397 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
401 //////////////////////////////////////////////////////////////////////////////
406 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
409 if (!reservekey.GetReservedKey(pubkey))
412 CScript scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
413 return CreateNewBlock(scriptPubKey);
416 static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
418 LogPrintf("%s\n", pblock->ToString());
419 LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue));
424 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
425 return error("ZcashMiner: generated block is stale");
428 // Remove key from key pool
429 reservekey.KeepKey();
431 // Track how many getdata requests this block gets
433 LOCK(wallet.cs_wallet);
434 wallet.mapRequestCount[pblock->GetHash()] = 0;
437 // Process this block the same as if we had received it from another node
438 CValidationState state;
439 if (!ProcessNewBlock(state, NULL, pblock, true, NULL))
440 return error("ZcashMiner: ProcessNewBlock, block not accepted");
445 void static BitcoinMiner(CWallet *pwallet)
447 LogPrintf("ZcashMiner started\n");
448 SetThreadPriority(THREAD_PRIORITY_LOWEST);
449 RenameThread("zcash-miner");
450 const CChainParams& chainparams = Params();
452 // Each thread has its own key and counter
453 CReserveKey reservekey(pwallet);
454 unsigned int nExtraNonce = 0;
456 unsigned int n = chainparams.EquihashN();
457 unsigned int k = chainparams.EquihashK();
460 bool cancelSolver = false;
461 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
462 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
463 std::lock_guard<std::mutex> lock{m_cs};
471 if (chainparams.MiningRequiresPeers())
473 // Busy-wait for the network to come online so we don't waste time mining
474 // on an obsolete chain. In regtest mode we expect to fly solo.
475 fprintf(stderr,"Wait for peers...\n");
480 fvNodesEmpty = vNodes.empty();
482 if (!fvNodesEmpty && !IsInitialBlockDownload())
486 fprintf(stderr,"Found peers\n");
492 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
493 CBlockIndex* pindexPrev = chainActive.Tip();
495 auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
496 if (!pblocktemplate.get())
498 LogPrintf("Error in ZcashMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
501 CBlock *pblock = &pblocktemplate->block;
502 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
504 LogPrintf("Running ZcashMiner with %u transactions in block (%u bytes)\n", pblock->vtx.size(),
505 ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
510 int64_t nStart = GetTime();
511 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
516 crypto_generichash_blake2b_state state;
517 EhInitialiseState(n, k, state);
519 // I = the block header minus nonce and solution.
520 CEquihashInput I{*pblock};
521 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
525 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
528 crypto_generichash_blake2b_state curr_state;
530 crypto_generichash_blake2b_update(&curr_state,
531 pblock->nNonce.begin(),
532 pblock->nNonce.size());
534 // (x_1, x_2, ...) = A(I, V, n, k)
535 LogPrint("pow", "Running Equihash solver with nNonce = %s\n",
536 pblock->nNonce.ToString());
538 std::function<bool(std::vector<unsigned char>)> validBlock =
539 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
540 (std::vector<unsigned char> soln) {
541 // Write the solution to the hash and compute the result.
542 LogPrint("pow", "- Checking solution against target\n");
543 pblock->nSolution = soln;
545 if (UintToArith256(pblock->GetHash()) > hashTarget) {
550 SetThreadPriority(THREAD_PRIORITY_NORMAL);
551 LogPrintf("ZcashMiner:\n");
552 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
553 if (ProcessBlockFound(pblock, *pwallet, reservekey)) {
554 // Ignore chain updates caused by us
555 std::lock_guard<std::mutex> lock{m_cs};
556 cancelSolver = false;
558 SetThreadPriority(THREAD_PRIORITY_LOWEST);
560 // In regression test mode, stop mining after a block is found.
561 if (chainparams.MineBlocksOnDemand())
562 throw boost::thread_interrupted();
566 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
567 std::lock_guard<std::mutex> lock{m_cs};
571 // If we find a valid block, we rebuild
572 if (EhOptimisedSolve(n, k, curr_state, validBlock, cancelled))
574 } catch (EhSolverCancelledException&) {
575 LogPrint("pow", "Equihash solver cancelled\n");
576 std::lock_guard<std::mutex> lock{m_cs};
577 cancelSolver = false;
580 // Check for stop or if block needs to be rebuilt
581 boost::this_thread::interruption_point();
582 // Regtest mode doesn't require peers
583 if (vNodes.empty() && chainparams.MiningRequiresPeers())
585 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
587 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
589 if (pindexPrev != chainActive.Tip())
592 // Update nNonce and nTime
593 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
594 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
595 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
597 // Changing pblock->nTime can change work required on testnet:
598 hashTarget.SetCompact(pblock->nBits);
603 catch (const boost::thread_interrupted&)
605 LogPrintf("ZcashMiner terminated\n");
608 catch (const std::runtime_error &e)
610 LogPrintf("ZcashMiner runtime error: %s\n", e.what());
616 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
618 static boost::thread_group* minerThreads = NULL;
621 // In regtest threads defaults to 1
622 if (Params().DefaultMinerThreads())
623 nThreads = Params().DefaultMinerThreads();
625 nThreads = boost::thread::hardware_concurrency();
628 if (minerThreads != NULL)
630 minerThreads->interrupt_all();
635 if (nThreads == 0 || !fGenerate)
638 minerThreads = new boost::thread_group();
639 for (int i = 0; i < nThreads; i++)
640 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
643 #endif // ENABLE_WALLET