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.
8 #include "pow/tromp/equi_miner.h"
13 #include "chainparams.h"
14 #include "consensus/consensus.h"
15 #include "consensus/upgrades.h"
16 #include "consensus/validation.h"
18 #include "crypto/equihash.h"
25 #include "primitives/transaction.h"
28 #include "ui_interface.h"
30 #include "utilmoneystr.h"
32 #include "wallet/wallet.h"
37 #include <boost/thread.hpp>
38 #include <boost/tuple/tuple.hpp>
46 //////////////////////////////////////////////////////////////////////////////
52 // Unconfirmed transactions in the memory pool often depend on other
53 // transactions in the memory pool. When we select transactions from the
54 // pool, we select by highest priority or fee rate, so we might consider
55 // transactions that depend on transactions that aren't yet in the block.
56 // The COrphan class keeps track of these 'temporary orphans' while
57 // CreateBlock is figuring out which transactions to include.
62 const CTransaction* ptx;
63 set<uint256> setDependsOn;
67 COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
72 uint64_t nLastBlockTx = 0;
73 uint64_t nLastBlockSize = 0;
75 // We want to sort transactions by priority and fee rate, so:
76 typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
77 class TxPriorityCompare
82 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
84 bool operator()(const TxPriority& a, const TxPriority& b)
88 if (a.get<1>() == b.get<1>())
89 return a.get<0>() < b.get<0>();
90 return a.get<1>() < b.get<1>();
94 if (a.get<0>() == b.get<0>())
95 return a.get<1>() < b.get<1>();
96 return a.get<0>() < b.get<0>();
101 void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
103 pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
106 CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
108 const CChainParams& chainparams = Params();
110 std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
111 if(!pblocktemplate.get())
113 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
115 // -regtest only: allow overriding block.nVersion with
116 // -blockversion=N to test forking scenarios
117 if (Params().MineBlocksOnDemand())
118 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
120 // Add dummy coinbase tx as first transaction
121 pblock->vtx.push_back(CTransaction());
122 pblocktemplate->vTxFees.push_back(-1); // updated at end
123 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
125 // Largest block you're willing to create:
126 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
127 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
128 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
130 // How much of the block should be dedicated to high-priority transactions,
131 // included regardless of the fees they pay
132 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
133 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
135 // Minimum block size you want to create; block will be filled with free transactions
136 // until there are no more or the block reaches this size:
137 unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
138 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
140 // Collect memory pool transactions into the block
144 LOCK2(cs_main, mempool.cs);
145 CBlockIndex* pindexPrev = chainActive.Tip();
146 const int nHeight = pindexPrev->nHeight + 1;
147 uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, chainparams.GetConsensus());
148 pblock->nTime = GetAdjustedTime();
149 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
150 CCoinsViewCache view(pcoinsTip);
152 // Priority order to process transactions
153 list<COrphan> vOrphan; // list memory doesn't move
154 map<uint256, vector<COrphan*> > mapDependers;
155 bool fPrintPriority = GetBoolArg("-printpriority", false);
157 // This vector will be sorted into a priority queue:
158 vector<TxPriority> vecPriority;
159 vecPriority.reserve(mempool.mapTx.size());
160 for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
161 mi != mempool.mapTx.end(); ++mi)
163 const CTransaction& tx = mi->GetTx();
165 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
167 : pblock->GetBlockTime();
169 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight))
172 COrphan* porphan = NULL;
173 double dPriority = 0;
174 CAmount nTotalIn = 0;
175 bool fMissingInputs = false;
176 BOOST_FOREACH(const CTxIn& txin, tx.vin)
178 // Read prev transaction
179 if (!view.HaveCoins(txin.prevout.hash))
181 // This should never happen; all transactions in the memory
182 // pool should connect to either transactions in the chain
183 // or other transactions in the memory pool.
184 if (!mempool.mapTx.count(txin.prevout.hash))
186 LogPrintf("ERROR: mempool transaction missing input\n");
187 if (fDebug) assert("mempool transaction missing input" == 0);
188 fMissingInputs = true;
194 // Has to wait for dependencies
197 // Use list for automatic deletion
198 vOrphan.push_back(COrphan(&tx));
199 porphan = &vOrphan.back();
201 mapDependers[txin.prevout.hash].push_back(porphan);
202 porphan->setDependsOn.insert(txin.prevout.hash);
203 nTotalIn += mempool.mapTx.find(txin.prevout.hash)->GetTx().vout[txin.prevout.n].nValue;
206 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
209 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
210 nTotalIn += nValueIn;
212 int nConf = nHeight - coins->nHeight;
214 dPriority += (double)nValueIn * nConf;
216 nTotalIn += tx.GetJoinSplitValueIn();
218 if (fMissingInputs) continue;
220 // Priority is sum(valuein * age) / modified_txsize
221 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
222 dPriority = tx.ComputePriority(dPriority, nTxSize);
224 uint256 hash = tx.GetHash();
225 mempool.ApplyDeltas(hash, dPriority, nTotalIn);
227 CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
231 porphan->dPriority = dPriority;
232 porphan->feeRate = feeRate;
235 vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));
238 // Collect transactions into block
239 uint64_t nBlockSize = 1000;
240 uint64_t nBlockTx = 0;
241 int nBlockSigOps = 100;
242 bool fSortedByFee = (nBlockPrioritySize <= 0);
244 TxPriorityCompare comparer(fSortedByFee);
245 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
247 while (!vecPriority.empty())
249 // Take highest priority transaction off the priority queue:
250 double dPriority = vecPriority.front().get<0>();
251 CFeeRate feeRate = vecPriority.front().get<1>();
252 const CTransaction& tx = *(vecPriority.front().get<2>());
254 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
255 vecPriority.pop_back();
258 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
259 if (nBlockSize + nTxSize >= nBlockMaxSize)
262 // Legacy limits on sigOps:
263 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
264 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
267 // Skip free transactions if we're past the minimum block size:
268 const uint256& hash = tx.GetHash();
269 double dPriorityDelta = 0;
270 CAmount nFeeDelta = 0;
271 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
272 if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
275 // Prioritise by fee once past the priority size or we run out of high-priority
278 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
281 comparer = TxPriorityCompare(fSortedByFee);
282 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
285 if (!view.HaveInputs(tx))
288 CAmount nTxFees = view.GetValueIn(tx)-tx.GetValueOut();
290 nTxSigOps += GetP2SHSigOpCount(tx, view);
291 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
294 // Note that flags: we don't want to set mempool/IsStandard()
295 // policy here, but we still have to ensure that the block we
296 // create only contains transactions that are valid in new blocks.
297 CValidationState state;
298 PrecomputedTransactionData txdata(tx);
299 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
302 UpdateCoins(tx, view, nHeight);
305 pblock->vtx.push_back(tx);
306 pblocktemplate->vTxFees.push_back(nTxFees);
307 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
308 nBlockSize += nTxSize;
310 nBlockSigOps += nTxSigOps;
315 LogPrintf("priority %.1f fee %s txid %s\n",
316 dPriority, feeRate.ToString(), tx.GetHash().ToString());
319 // Add transactions that depend on this one to the priority queue
320 if (mapDependers.count(hash))
322 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
324 if (!porphan->setDependsOn.empty())
326 porphan->setDependsOn.erase(hash);
327 if (porphan->setDependsOn.empty())
329 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
330 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
337 nLastBlockTx = nBlockTx;
338 nLastBlockSize = nBlockSize;
339 LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize);
341 // Create coinbase tx
342 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(chainparams.GetConsensus(), nHeight);
344 txNew.vin[0].prevout.SetNull();
345 txNew.vout.resize(1);
346 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
347 txNew.vout[0].nValue = GetBlockSubsidy(nHeight, chainparams.GetConsensus());
348 // Set to 0 so expiry height does not apply to coinbase txs
349 txNew.nExpiryHeight = 0;
351 if ((nHeight > 0) && (nHeight <= chainparams.GetConsensus().GetLastFoundersRewardBlockHeight())) {
352 // Founders reward is 20% of the block subsidy
353 auto vFoundersReward = txNew.vout[0].nValue / 5;
354 // Take some reward away from us
355 txNew.vout[0].nValue -= vFoundersReward;
357 // And give it to the founders
358 txNew.vout.push_back(CTxOut(vFoundersReward, chainparams.GetFoundersRewardScriptAtHeight(nHeight)));
362 txNew.vout[0].nValue += nFees;
363 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
365 pblock->vtx[0] = txNew;
366 pblocktemplate->vTxFees[0] = -nFees;
369 arith_uint256 nonce = UintToArith256(GetRandHash());
370 // Clear the top and bottom 16 bits (for local use as thread flags and counters)
373 pblock->nNonce = ArithToUint256(nonce);
376 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
377 pblock->hashFinalSaplingRoot = uint256(); // TODO
378 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
379 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
380 pblock->nSolution.clear();
381 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
383 CValidationState state;
384 if (!TestBlockValidity(state, *pblock, pindexPrev, false, false))
385 throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed");
388 return pblocktemplate.release();
392 boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)
394 boost::optional<CScript> GetMinerScriptPubKey()
398 CTxDestination addr = DecodeDestination(GetArg("-mineraddress", ""));
399 if (IsValidDestination(addr)) {
400 keyID = boost::get<CKeyID>(addr);
404 if (!reservekey.GetReservedKey(pubkey)) {
405 return boost::optional<CScript>();
407 keyID = pubkey.GetID();
409 return boost::optional<CScript>();
413 CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
418 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
420 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);
422 CBlockTemplate* CreateNewBlockWithKey()
424 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();
430 return CreateNewBlock(*scriptPubKey);
433 //////////////////////////////////////////////////////////////////////////////
440 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
442 // Update nExtraNonce
443 static uint256 hashPrevBlock;
444 if (hashPrevBlock != pblock->hashPrevBlock)
447 hashPrevBlock = pblock->hashPrevBlock;
450 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
451 CMutableTransaction txCoinbase(pblock->vtx[0]);
452 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
453 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
455 pblock->vtx[0] = txCoinbase;
456 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
460 static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
462 static bool ProcessBlockFound(CBlock* pblock)
463 #endif // ENABLE_WALLET
465 LogPrintf("%s\n", pblock->ToString());
466 LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue));
471 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
472 return error("ZcashMiner: generated block is stale");
476 if (GetArg("-mineraddress", "").empty()) {
477 // Remove key from key pool
478 reservekey.KeepKey();
481 // Track how many getdata requests this block gets
483 LOCK(wallet.cs_wallet);
484 wallet.mapRequestCount[pblock->GetHash()] = 0;
488 // Process this block the same as if we had received it from another node
489 CValidationState state;
490 if (!ProcessNewBlock(state, NULL, pblock, true, NULL))
491 return error("ZcashMiner: ProcessNewBlock, block not accepted");
493 TrackMinedBlock(pblock->GetHash());
499 void static BitcoinMiner(CWallet *pwallet)
501 void static BitcoinMiner()
504 LogPrintf("ZcashMiner started\n");
505 SetThreadPriority(THREAD_PRIORITY_LOWEST);
506 RenameThread("zcash-miner");
507 const CChainParams& chainparams = Params();
510 // Each thread has its own key
511 CReserveKey reservekey(pwallet);
514 // Each thread has its own counter
515 unsigned int nExtraNonce = 0;
517 unsigned int n = chainparams.EquihashN();
518 unsigned int k = chainparams.EquihashK();
520 std::string solver = GetArg("-equihashsolver", "default");
521 assert(solver == "tromp" || solver == "default");
522 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
525 bool cancelSolver = false;
526 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
527 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
528 std::lock_guard<std::mutex> lock{m_cs};
536 if (chainparams.MiningRequiresPeers()) {
537 // Busy-wait for the network to come online so we don't waste time mining
538 // on an obsolete chain. In regtest mode we expect to fly solo.
544 fvNodesEmpty = vNodes.empty();
546 if (!fvNodesEmpty && !IsInitialBlockDownload())
556 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
557 CBlockIndex* pindexPrev = chainActive.Tip();
560 unique_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
562 unique_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey());
564 if (!pblocktemplate.get())
566 if (GetArg("-mineraddress", "").empty()) {
567 LogPrintf("Error in ZcashMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
569 // Should never reach here, because -mineraddress validity is checked in init.cpp
570 LogPrintf("Error in ZcashMiner: Invalid -mineraddress\n");
574 CBlock *pblock = &pblocktemplate->block;
575 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
577 LogPrintf("Running ZcashMiner with %u transactions in block (%u bytes)\n", pblock->vtx.size(),
578 ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
583 int64_t nStart = GetTime();
584 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
588 crypto_generichash_blake2b_state state;
589 EhInitialiseState(n, k, state);
591 // I = the block header minus nonce and solution.
592 CEquihashInput I{*pblock};
593 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
597 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
600 crypto_generichash_blake2b_state curr_state;
602 crypto_generichash_blake2b_update(&curr_state,
603 pblock->nNonce.begin(),
604 pblock->nNonce.size());
606 // (x_1, x_2, ...) = A(I, V, n, k)
607 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",
608 solver, pblock->nNonce.ToString());
610 std::function<bool(std::vector<unsigned char>)> validBlock =
612 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
614 [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
616 (std::vector<unsigned char> soln) {
617 // Write the solution to the hash and compute the result.
618 LogPrint("pow", "- Checking solution against target\n");
619 pblock->nSolution = soln;
620 solutionTargetChecks.increment();
622 if (UintToArith256(pblock->GetHash()) > hashTarget) {
627 SetThreadPriority(THREAD_PRIORITY_NORMAL);
628 LogPrintf("ZcashMiner:\n");
629 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
631 if (ProcessBlockFound(pblock, *pwallet, reservekey)) {
633 if (ProcessBlockFound(pblock)) {
635 // Ignore chain updates caused by us
636 std::lock_guard<std::mutex> lock{m_cs};
637 cancelSolver = false;
639 SetThreadPriority(THREAD_PRIORITY_LOWEST);
641 // In regression test mode, stop mining after a block is found.
642 if (chainparams.MineBlocksOnDemand()) {
643 // Increment here because throwing skips the call below
644 ehSolverRuns.increment();
645 throw boost::thread_interrupted();
650 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
651 std::lock_guard<std::mutex> lock{m_cs};
655 // TODO: factor this out into a function with the same API for each solver.
656 if (solver == "tromp") {
657 // Create solver and initialize it.
659 eq.setstate(&curr_state);
661 // Initialization done, start algo driver.
663 eq.xfull = eq.bfull = eq.hfull = 0;
665 for (u32 r = 1; r < WK; r++) {
666 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
667 eq.xfull = eq.bfull = eq.hfull = 0;
671 ehSolverRuns.increment();
673 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
674 for (size_t s = 0; s < eq.nsols; s++) {
675 LogPrint("pow", "Checking solution %d\n", s+1);
676 std::vector<eh_index> index_vector(PROOFSIZE);
677 for (size_t i = 0; i < PROOFSIZE; i++) {
678 index_vector[i] = eq.sols[s][i];
680 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
682 if (validBlock(sol_char)) {
683 // If we find a POW solution, do not try other solutions
684 // because they become invalid as we created a new block in blockchain.
690 // If we find a valid block, we rebuild
691 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
692 ehSolverRuns.increment();
696 } catch (EhSolverCancelledException&) {
697 LogPrint("pow", "Equihash solver cancelled\n");
698 std::lock_guard<std::mutex> lock{m_cs};
699 cancelSolver = false;
703 // Check for stop or if block needs to be rebuilt
704 boost::this_thread::interruption_point();
705 // Regtest mode doesn't require peers
706 if (vNodes.empty() && chainparams.MiningRequiresPeers())
708 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
710 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
712 if (pindexPrev != chainActive.Tip())
715 // Update nNonce and nTime
716 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
717 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
721 catch (const boost::thread_interrupted&)
725 LogPrintf("ZcashMiner terminated\n");
728 catch (const std::runtime_error &e)
732 LogPrintf("ZcashMiner runtime error: %s\n", e.what());
740 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
742 void GenerateBitcoins(bool fGenerate, int nThreads)
745 static boost::thread_group* minerThreads = NULL;
748 nThreads = GetNumCores();
750 if (minerThreads != NULL)
752 minerThreads->interrupt_all();
757 if (nThreads == 0 || !fGenerate)
760 minerThreads = new boost::thread_group();
761 for (int i = 0; i < nThreads; i++) {
763 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
765 minerThreads->create_thread(&BitcoinMiner);
770 #endif // ENABLE_MINING