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.
7 #include "pow/tromp/equi_miner.h"
10 #include "chainparams.h"
11 #include "consensus/consensus.h"
12 #include "consensus/validation.h"
18 #include "primitives/transaction.h"
22 #include "utilmoneystr.h"
24 #include "crypto/equihash.h"
25 #include "wallet/wallet.h"
31 #include <boost/thread.hpp>
32 #include <boost/tuple/tuple.hpp>
37 //////////////////////////////////////////////////////////////////////////////
43 // Unconfirmed transactions in the memory pool often depend on other
44 // transactions in the memory pool. When we select transactions from the
45 // pool, we select by highest priority or fee rate, so we might consider
46 // transactions that depend on transactions that aren't yet in the block.
47 // The COrphan class keeps track of these 'temporary orphans' while
48 // CreateBlock is figuring out which transactions to include.
53 const CTransaction* ptx;
54 set<uint256> setDependsOn;
58 COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
63 uint64_t nLastBlockTx = 0;
64 uint64_t nLastBlockSize = 0;
66 // We want to sort transactions by priority and fee rate, so:
67 typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
68 class TxPriorityCompare
73 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
75 bool operator()(const TxPriority& a, const TxPriority& b)
79 if (a.get<1>() == b.get<1>())
80 return a.get<0>() < b.get<0>();
81 return a.get<1>() < b.get<1>();
85 if (a.get<0>() == b.get<0>())
86 return a.get<1>() < b.get<1>();
87 return a.get<0>() < b.get<0>();
92 void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
94 pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
96 // Updating time can change work required on testnet:
97 if (consensusParams.fPowAllowMinDifficultyBlocks)
98 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
101 int32_t komodo_pax_opreturn(uint8_t *opret,int32_t maxsize);
102 void komodo_gateway_deposits(CMutableTransaction *txNew);
103 extern int32_t KOMODO_INITDONE,ASSETCHAINS_SHORTFLAG;
104 extern uint64_t KOMODO_DEPOSIT;
105 extern char ASSETCHAINS_SYMBOL[16];
107 CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
109 const CChainParams& chainparams = Params();
111 unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
112 if(!pblocktemplate.get())
114 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
115 while ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight > 10 && mempool.GetTotalTxSize() <= 0 )
118 if ( KOMODO_INITDONE == 0 || time(NULL) < KOMODO_INITDONE+60 )
120 if ( KOMODO_DEPOSIT != 0 )
122 printf("KOMODO_DEPOSIT %llu pblock->nHeight %d mempool.GetTotalTxSize(%d)\n",(long long)KOMODO_DEPOSIT,(int32_t)chainActive.Tip()->nHeight,(int32_t)mempool.GetTotalTxSize());
127 // -regtest only: allow overriding block.nVersion with
128 // -blockversion=N to test forking scenarios
129 if (Params().MineBlocksOnDemand())
130 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
132 // Add dummy coinbase tx as first transaction
133 pblock->vtx.push_back(CTransaction());
134 pblocktemplate->vTxFees.push_back(-1); // updated at end
135 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
137 // Largest block you're willing to create:
138 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
139 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
140 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
142 // How much of the block should be dedicated to high-priority transactions,
143 // included regardless of the fees they pay
144 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
145 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
147 // Minimum block size you want to create; block will be filled with free transactions
148 // until there are no more or the block reaches this size:
149 unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
150 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
152 // Collect memory pool transactions into the block
156 LOCK2(cs_main, mempool.cs);
157 CBlockIndex* pindexPrev = chainActive.Tip();
158 const int nHeight = pindexPrev->nHeight + 1;
159 pblock->nTime = GetAdjustedTime();
160 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
161 CCoinsViewCache view(pcoinsTip);
163 // Priority order to process transactions
164 list<COrphan> vOrphan; // list memory doesn't move
165 map<uint256, vector<COrphan*> > mapDependers;
166 bool fPrintPriority = GetBoolArg("-printpriority", false);
168 // This vector will be sorted into a priority queue:
169 vector<TxPriority> vecPriority;
170 vecPriority.reserve(mempool.mapTx.size());
171 for (map<uint256, CTxMemPoolEntry>::iterator mi = mempool.mapTx.begin();
172 mi != mempool.mapTx.end(); ++mi)
174 const CTransaction& tx = mi->second.GetTx();
176 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
178 : pblock->GetBlockTime();
180 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff))
183 COrphan* porphan = NULL;
184 double dPriority = 0;
185 CAmount nTotalIn = 0;
186 bool fMissingInputs = false;
187 BOOST_FOREACH(const CTxIn& txin, tx.vin)
189 // Read prev transaction
190 if (!view.HaveCoins(txin.prevout.hash))
192 // This should never happen; all transactions in the memory
193 // pool should connect to either transactions in the chain
194 // or other transactions in the memory pool.
195 if (!mempool.mapTx.count(txin.prevout.hash))
197 LogPrintf("ERROR: mempool transaction missing input\n");
198 if (fDebug) assert("mempool transaction missing input" == 0);
199 fMissingInputs = true;
205 // Has to wait for dependencies
208 // Use list for automatic deletion
209 vOrphan.push_back(COrphan(&tx));
210 porphan = &vOrphan.back();
212 mapDependers[txin.prevout.hash].push_back(porphan);
213 porphan->setDependsOn.insert(txin.prevout.hash);
214 nTotalIn += mempool.mapTx[txin.prevout.hash].GetTx().vout[txin.prevout.n].nValue;
217 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
220 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
221 nTotalIn += nValueIn;
223 int nConf = nHeight - coins->nHeight;
225 dPriority += (double)nValueIn * nConf;
227 if (fMissingInputs) continue;
229 // Priority is sum(valuein * age) / modified_txsize
230 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
231 dPriority = tx.ComputePriority(dPriority, nTxSize);
233 uint256 hash = tx.GetHash();
234 mempool.ApplyDeltas(hash, dPriority, nTotalIn);
236 CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
240 porphan->dPriority = dPriority;
241 porphan->feeRate = feeRate;
244 vecPriority.push_back(TxPriority(dPriority, feeRate, &mi->second.GetTx()));
247 // Collect transactions into block
248 uint64_t nBlockSize = 1000;
249 uint64_t nBlockTx = 0;
251 int nBlockSigOps = 100;
252 bool fSortedByFee = (nBlockPrioritySize <= 0);
254 TxPriorityCompare comparer(fSortedByFee);
255 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
257 while (!vecPriority.empty())
259 // Take highest priority transaction off the priority queue:
260 double dPriority = vecPriority.front().get<0>();
261 CFeeRate feeRate = vecPriority.front().get<1>();
262 const CTransaction& tx = *(vecPriority.front().get<2>());
264 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
265 vecPriority.pop_back();
268 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
269 if (nBlockSize + nTxSize >= nBlockMaxSize)
272 // Legacy limits on sigOps:
273 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
274 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
277 // Skip free transactions if we're past the minimum block size:
278 const uint256& hash = tx.GetHash();
279 double dPriorityDelta = 0;
280 CAmount nFeeDelta = 0;
281 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
282 if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
285 // Prioritise by fee once past the priority size or we run out of high-priority
288 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
291 comparer = TxPriorityCompare(fSortedByFee);
292 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
295 if (!view.HaveInputs(tx))
298 CAmount nTxFees = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime)-tx.GetValueOut();
300 nTxSigOps += GetP2SHSigOpCount(tx, view);
301 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
304 // Note that flags: we don't want to set mempool/IsStandard()
305 // policy here, but we still have to ensure that the block we
306 // create only contains transactions that are valid in new blocks.
307 CValidationState state;
308 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
311 UpdateCoins(tx, state, view, nHeight);
314 pblock->vtx.push_back(tx);
315 pblocktemplate->vTxFees.push_back(nTxFees);
316 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
317 nBlockSize += nTxSize;
319 nBlockSigOps += nTxSigOps;
324 LogPrintf("priority %.1f fee %s txid %s\n",
325 dPriority, feeRate.ToString(), tx.GetHash().ToString());
328 // Add transactions that depend on this one to the priority queue
329 if (mapDependers.count(hash))
331 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
333 if (!porphan->setDependsOn.empty())
335 porphan->setDependsOn.erase(hash);
336 if (porphan->setDependsOn.empty())
338 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
339 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
346 nLastBlockTx = nBlockTx;
347 nLastBlockSize = nBlockSize;
348 LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize);
350 // Create coinbase tx
351 CMutableTransaction txNew;
352 //txNew.nLockTime = (uint32_t)time(NULL) - 60;
354 txNew.vin[0].prevout.SetNull();
355 txNew.vout.resize(1);
356 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
357 txNew.vout[0].nValue = GetBlockSubsidy(nHeight,chainparams.GetConsensus());
359 txNew.vout[0].nValue += nFees;
360 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
361 if ( ASSETCHAINS_SYMBOL[0] == 0 )
363 int32_t i,opretlen; uint8_t opret[256],*ptr;
364 if ( (opretlen= komodo_pax_opreturn(opret,sizeof(opret))) > 0 )
366 txNew.vout.resize(2);
367 txNew.vout[1].scriptPubKey.resize(opretlen);
368 ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data();
369 for (i=0; i<opretlen; i++)
371 txNew.vout[1].nValue = 0;
372 //fprintf(stderr,"opretlen.%d\n",opretlen);
377 komodo_gateway_deposits(&txNew);
378 fprintf(stderr,"txNew numvouts.%d\n",(int32_t)txNew.vout.size());
381 pblock->vtx[0] = txNew;
382 pblocktemplate->vTxFees[0] = -nFees;
385 arith_uint256 nonce = UintToArith256(GetRandHash());
386 // Clear the top and bottom 16 bits (for local use as thread flags and counters)
389 pblock->nNonce = ArithToUint256(nonce);
392 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
393 pblock->hashReserved = uint256();
394 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
395 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
396 pblock->nSolution.clear();
397 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
399 CValidationState state;
400 if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false))
402 fprintf(stderr,"testblockvalidity failed\n");
403 //throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed");
407 return pblocktemplate.release();
410 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
412 // Update nExtraNonce
413 static uint256 hashPrevBlock;
414 if (hashPrevBlock != pblock->hashPrevBlock)
417 hashPrevBlock = pblock->hashPrevBlock;
420 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
421 CMutableTransaction txCoinbase(pblock->vtx[0]);
422 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
423 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
425 pblock->vtx[0] = txCoinbase;
426 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
430 //////////////////////////////////////////////////////////////////////////////
434 extern int32_t IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY;
435 extern std::string NOTARY_PUBKEY;
436 extern uint8_t NOTARY_PUBKEY33[33];
437 uint32_t Mining_start,Mining_height;
438 int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33);
440 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
442 CPubKey pubkey; CScript scriptPubKey; uint8_t *script,*ptr; int32_t i;
443 if ( USE_EXTERNAL_PUBKEY != 0 )
445 //fprintf(stderr,"use notary pubkey\n");
446 scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
450 if (!reservekey.GetReservedKey(pubkey))
452 scriptPubKey.resize(35);
453 ptr = (uint8_t *)pubkey.begin();
454 script = (uint8_t *)scriptPubKey.data();
457 script[i+1] = ptr[i];
458 script[34] = OP_CHECKSIG;
459 //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
461 return CreateNewBlock(scriptPubKey);
464 static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
466 LogPrintf("%s\n", pblock->ToString());
467 LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue));
472 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
473 return error("ZcashMiner: generated block is stale");
476 // Remove key from key pool
477 if ( IS_KOMODO_NOTARY == 0 )
478 reservekey.KeepKey();
480 // Track how many getdata requests this block gets
482 LOCK(wallet.cs_wallet);
483 wallet.mapRequestCount[pblock->GetHash()] = 0;
486 // Process this block the same as if we had received it from another node
487 CValidationState state;
488 if (!ProcessNewBlock(state, NULL, pblock, true, NULL))
489 return error("ZcashMiner: ProcessNewBlock, block not accepted");
491 minedBlocks.increment();
496 void static BitcoinMiner(CWallet *pwallet)
498 LogPrintf("ZcashMiner started\n");
499 SetThreadPriority(THREAD_PRIORITY_LOWEST);
500 RenameThread("zcash-miner");
501 const CChainParams& chainparams = Params();
503 // Each thread has its own key and counter
504 CReserveKey reservekey(pwallet);
505 unsigned int nExtraNonce = 0;
507 unsigned int n = chainparams.EquihashN();
508 unsigned int k = chainparams.EquihashK();
510 std::string solver = GetArg("-equihashsolver", "tromp");
511 assert(solver == "tromp" || solver == "default");
512 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
513 //fprintf(stderr,"Mining with %s\n",solver.c_str());
515 bool cancelSolver = false;
516 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
517 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
518 std::lock_guard<std::mutex> lock{m_cs};
526 if (ASSETCHAINS_SHORTFLAG == 0 && chainparams.MiningRequiresPeers())
528 // Busy-wait for the network to come online so we don't waste time mining
529 // on an obsolete chain. In regtest mode we expect to fly solo.
530 //fprintf(stderr,"Wait for peers...\n");
535 fvNodesEmpty = vNodes.empty();
537 if (!fvNodesEmpty && !IsInitialBlockDownload())
541 //fprintf(stderr,"Found peers\n");
543 //fprintf(stderr,"create new block\n");
547 Mining_start = (uint32_t)time(NULL);
548 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
549 CBlockIndex* pindexPrev = chainActive.Tip();
551 unique_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
552 if (!pblocktemplate.get())
554 LogPrintf("Error in ZcashMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
557 CBlock *pblock = &pblocktemplate->block;
558 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
559 LogPrintf("Running ZcashMiner with %u transactions in block (%u bytes)\n", pblock->vtx.size(),
560 ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
565 int32_t notaryid; uint32_t savebits; int64_t nStart = GetTime();
566 savebits = pblock->nBits;
567 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
568 if ( komodo_chosennotary(¬aryid,pindexPrev->nHeight+1,NOTARY_PUBKEY33) > 0 )
570 hashTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
571 Mining_start = (uint32_t)time(NULL);
572 //fprintf(stderr,"I am the chosen one for ht.%d\n",pindexPrev->nHeight+1);
573 } else Mining_start = 0;
574 Mining_height = pindexPrev->nHeight+1;
578 crypto_generichash_blake2b_state state;
579 EhInitialiseState(n, k, state);
580 // I = the block header minus nonce and solution.
581 CEquihashInput I{*pblock};
582 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
585 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
587 crypto_generichash_blake2b_state curr_state;
589 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
591 // (x_1, x_2, ...) = A(I, V, n, k)
592 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
594 std::function<bool(std::vector<unsigned char>)> validBlock =
595 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
596 (std::vector<unsigned char> soln) {
597 // Write the solution to the hash and compute the result.
598 LogPrint("pow", "- Checking solution against target\n");
599 pblock->nSolution = soln;
600 solutionTargetChecks.increment();
601 if ( UintToArith256(pblock->GetHash()) > hashTarget )
603 if ( Mining_start != 0 && time(NULL) < Mining_start+50 )
605 printf("Round robin diff sleep %d\n",(int32_t)(Mining_start+50-time(NULL)));
606 sleep(Mining_start+50-time(NULL));
609 SetThreadPriority(THREAD_PRIORITY_NORMAL);
610 LogPrintf("ZcashMiner:\n");
611 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
612 if (ProcessBlockFound(pblock, *pwallet, reservekey)) {
613 // Ignore chain updates caused by us
614 std::lock_guard<std::mutex> lock{m_cs};
615 cancelSolver = false;
617 fprintf(stderr,"%s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
618 SetThreadPriority(THREAD_PRIORITY_LOWEST);
619 // In regression test mode, stop mining after a block is found.
620 if (chainparams.MineBlocksOnDemand()) {
621 // Increment here because throwing skips the call below
622 ehSolverRuns.increment();
623 throw boost::thread_interrupted();
627 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
628 std::lock_guard<std::mutex> lock{m_cs};
632 // TODO: factor this out into a function with the same API for each solver.
633 if (solver == "tromp") {
634 // Create solver and initialize it.
636 eq.setstate(&curr_state);
638 // Intialization done, start algo driver.
640 eq.xfull = eq.bfull = eq.hfull = 0;
642 for (u32 r = 1; r < WK; r++) {
643 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
644 eq.xfull = eq.bfull = eq.hfull = 0;
648 ehSolverRuns.increment();
650 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
651 for (size_t s = 0; s < eq.nsols; s++) {
652 LogPrint("pow", "Checking solution %d\n", s+1);
653 std::vector<eh_index> index_vector(PROOFSIZE);
654 for (size_t i = 0; i < PROOFSIZE; i++) {
655 index_vector[i] = eq.sols[s][i];
657 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
659 if (validBlock(sol_char)) {
660 // If we find a POW solution, do not try other solutions
661 // because they become invalid as we created a new block in blockchain.
667 // If we find a valid block, we rebuild
668 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
669 ehSolverRuns.increment();
673 } catch (EhSolverCancelledException&) {
674 LogPrint("pow", "Equihash solver cancelled\n");
675 std::lock_guard<std::mutex> lock{m_cs};
676 cancelSolver = false;
680 // Check for stop or if block needs to be rebuilt
681 boost::this_thread::interruption_point();
682 // Regtest mode doesn't require peers
683 if (vNodes.empty() && chainparams.MiningRequiresPeers())
685 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
687 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
689 if (pindexPrev != chainActive.Tip())
692 // Update nNonce and nTime
693 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
694 pblock->nBits = savebits;
695 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
696 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
698 // Changing pblock->nTime can change work required on testnet:
699 hashTarget.SetCompact(pblock->nBits);
704 catch (const boost::thread_interrupted&)
706 LogPrintf("ZcashMiner terminated\n");
709 catch (const std::runtime_error &e)
711 LogPrintf("ZcashMiner runtime error: %s\n", e.what());
717 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
719 static boost::thread_group* minerThreads = NULL;
722 // In regtest threads defaults to 1
723 if (Params().DefaultMinerThreads())
724 nThreads = Params().DefaultMinerThreads();
726 nThreads = boost::thread::hardware_concurrency();
729 if (minerThreads != NULL)
731 minerThreads->interrupt_all();
736 if (nThreads == 0 || !fGenerate)
739 minerThreads = new boost::thread_group();
740 for (int i = 0; i < nThreads; i++)
741 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
744 #endif // ENABLE_WALLET