]> Git Repo - VerusCoin.git/blame_incremental - src/miner.cpp
Report non-mandatory script failures correctly
[VerusCoin.git] / src / miner.cpp
... / ...
CommitLineData
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.
5
6#include "miner.h"
7#ifdef ENABLE_MINING
8#include "pow/tromp/equi_miner.h"
9#endif
10
11#include "amount.h"
12#include "base58.h"
13#include "chainparams.h"
14#include "consensus/consensus.h"
15#include "consensus/validation.h"
16#ifdef ENABLE_MINING
17#include "crypto/equihash.h"
18#endif
19#include "hash.h"
20#include "main.h"
21#include "metrics.h"
22#include "net.h"
23#include "pow.h"
24#include "primitives/transaction.h"
25#include "random.h"
26#include "timedata.h"
27#include "ui_interface.h"
28#include "util.h"
29#include "utilmoneystr.h"
30#ifdef ENABLE_WALLET
31#include "wallet/wallet.h"
32#endif
33
34#include "sodium.h"
35
36#include <boost/thread.hpp>
37#include <boost/tuple/tuple.hpp>
38#ifdef ENABLE_MINING
39#include <functional>
40#endif
41#include <mutex>
42
43using namespace std;
44
45//////////////////////////////////////////////////////////////////////////////
46//
47// BitcoinMiner
48//
49
50//
51// Unconfirmed transactions in the memory pool often depend on other
52// transactions in the memory pool. When we select transactions from the
53// pool, we select by highest priority or fee rate, so we might consider
54// transactions that depend on transactions that aren't yet in the block.
55// The COrphan class keeps track of these 'temporary orphans' while
56// CreateBlock is figuring out which transactions to include.
57//
58class COrphan
59{
60public:
61 const CTransaction* ptx;
62 set<uint256> setDependsOn;
63 CFeeRate feeRate;
64 double dPriority;
65
66 COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
67 {
68 }
69};
70
71uint64_t nLastBlockTx = 0;
72uint64_t nLastBlockSize = 0;
73
74// We want to sort transactions by priority and fee rate, so:
75typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
76class TxPriorityCompare
77{
78 bool byFee;
79
80public:
81 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
82
83 bool operator()(const TxPriority& a, const TxPriority& b)
84 {
85 if (byFee)
86 {
87 if (a.get<1>() == b.get<1>())
88 return a.get<0>() < b.get<0>();
89 return a.get<1>() < b.get<1>();
90 }
91 else
92 {
93 if (a.get<0>() == b.get<0>())
94 return a.get<1>() < b.get<1>();
95 return a.get<0>() < b.get<0>();
96 }
97 }
98};
99
100void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
101{
102 pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
103}
104
105CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
106{
107 const CChainParams& chainparams = Params();
108 // Create new block
109 std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
110 if(!pblocktemplate.get())
111 return NULL;
112 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
113
114 // -regtest only: allow overriding block.nVersion with
115 // -blockversion=N to test forking scenarios
116 if (Params().MineBlocksOnDemand())
117 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
118
119 // Add dummy coinbase tx as first transaction
120 pblock->vtx.push_back(CTransaction());
121 pblocktemplate->vTxFees.push_back(-1); // updated at end
122 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
123
124 // Largest block you're willing to create:
125 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
126 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
127 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
128
129 // How much of the block should be dedicated to high-priority transactions,
130 // included regardless of the fees they pay
131 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
132 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
133
134 // Minimum block size you want to create; block will be filled with free transactions
135 // until there are no more or the block reaches this size:
136 unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
137 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
138
139 // Collect memory pool transactions into the block
140 CAmount nFees = 0;
141
142 {
143 LOCK2(cs_main, mempool.cs);
144 CBlockIndex* pindexPrev = chainActive.Tip();
145 const int nHeight = pindexPrev->nHeight + 1;
146 pblock->nTime = GetAdjustedTime();
147 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
148 CCoinsViewCache view(pcoinsTip);
149
150 // Priority order to process transactions
151 list<COrphan> vOrphan; // list memory doesn't move
152 map<uint256, vector<COrphan*> > mapDependers;
153 bool fPrintPriority = GetBoolArg("-printpriority", false);
154
155 // This vector will be sorted into a priority queue:
156 vector<TxPriority> vecPriority;
157 vecPriority.reserve(mempool.mapTx.size());
158 for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
159 mi != mempool.mapTx.end(); ++mi)
160 {
161 const CTransaction& tx = mi->GetTx();
162
163 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
164 ? nMedianTimePast
165 : pblock->GetBlockTime();
166
167 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff))
168 continue;
169
170 COrphan* porphan = NULL;
171 double dPriority = 0;
172 CAmount nTotalIn = 0;
173 bool fMissingInputs = false;
174 BOOST_FOREACH(const CTxIn& txin, tx.vin)
175 {
176 // Read prev transaction
177 if (!view.HaveCoins(txin.prevout.hash))
178 {
179 // This should never happen; all transactions in the memory
180 // pool should connect to either transactions in the chain
181 // or other transactions in the memory pool.
182 if (!mempool.mapTx.count(txin.prevout.hash))
183 {
184 LogPrintf("ERROR: mempool transaction missing input\n");
185 if (fDebug) assert("mempool transaction missing input" == 0);
186 fMissingInputs = true;
187 if (porphan)
188 vOrphan.pop_back();
189 break;
190 }
191
192 // Has to wait for dependencies
193 if (!porphan)
194 {
195 // Use list for automatic deletion
196 vOrphan.push_back(COrphan(&tx));
197 porphan = &vOrphan.back();
198 }
199 mapDependers[txin.prevout.hash].push_back(porphan);
200 porphan->setDependsOn.insert(txin.prevout.hash);
201 nTotalIn += mempool.mapTx.find(txin.prevout.hash)->GetTx().vout[txin.prevout.n].nValue;
202 continue;
203 }
204 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
205 assert(coins);
206
207 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
208 nTotalIn += nValueIn;
209
210 int nConf = nHeight - coins->nHeight;
211
212 dPriority += (double)nValueIn * nConf;
213 }
214 nTotalIn += tx.GetJoinSplitValueIn();
215
216 if (fMissingInputs) continue;
217
218 // Priority is sum(valuein * age) / modified_txsize
219 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
220 dPriority = tx.ComputePriority(dPriority, nTxSize);
221
222 uint256 hash = tx.GetHash();
223 mempool.ApplyDeltas(hash, dPriority, nTotalIn);
224
225 CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
226
227 if (porphan)
228 {
229 porphan->dPriority = dPriority;
230 porphan->feeRate = feeRate;
231 }
232 else
233 vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));
234 }
235
236 // Collect transactions into block
237 uint64_t nBlockSize = 1000;
238 uint64_t nBlockTx = 0;
239 int nBlockSigOps = 100;
240 bool fSortedByFee = (nBlockPrioritySize <= 0);
241
242 TxPriorityCompare comparer(fSortedByFee);
243 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
244
245 while (!vecPriority.empty())
246 {
247 // Take highest priority transaction off the priority queue:
248 double dPriority = vecPriority.front().get<0>();
249 CFeeRate feeRate = vecPriority.front().get<1>();
250 const CTransaction& tx = *(vecPriority.front().get<2>());
251
252 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
253 vecPriority.pop_back();
254
255 // Size limits
256 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
257 if (nBlockSize + nTxSize >= nBlockMaxSize)
258 continue;
259
260 // Legacy limits on sigOps:
261 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
262 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
263 continue;
264
265 // Skip free transactions if we're past the minimum block size:
266 const uint256& hash = tx.GetHash();
267 double dPriorityDelta = 0;
268 CAmount nFeeDelta = 0;
269 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
270 if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
271 continue;
272
273 // Prioritise by fee once past the priority size or we run out of high-priority
274 // transactions:
275 if (!fSortedByFee &&
276 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
277 {
278 fSortedByFee = true;
279 comparer = TxPriorityCompare(fSortedByFee);
280 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
281 }
282
283 if (!view.HaveInputs(tx))
284 continue;
285
286 CAmount nTxFees = view.GetValueIn(tx)-tx.GetValueOut();
287
288 nTxSigOps += GetP2SHSigOpCount(tx, view);
289 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
290 continue;
291
292 // Note that flags: we don't want to set mempool/IsStandard()
293 // policy here, but we still have to ensure that the block we
294 // create only contains transactions that are valid in new blocks.
295 CValidationState state;
296 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
297 continue;
298
299 UpdateCoins(tx, state, view, nHeight);
300
301 // Added
302 pblock->vtx.push_back(tx);
303 pblocktemplate->vTxFees.push_back(nTxFees);
304 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
305 nBlockSize += nTxSize;
306 ++nBlockTx;
307 nBlockSigOps += nTxSigOps;
308 nFees += nTxFees;
309
310 if (fPrintPriority)
311 {
312 LogPrintf("priority %.1f fee %s txid %s\n",
313 dPriority, feeRate.ToString(), tx.GetHash().ToString());
314 }
315
316 // Add transactions that depend on this one to the priority queue
317 if (mapDependers.count(hash))
318 {
319 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
320 {
321 if (!porphan->setDependsOn.empty())
322 {
323 porphan->setDependsOn.erase(hash);
324 if (porphan->setDependsOn.empty())
325 {
326 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
327 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
328 }
329 }
330 }
331 }
332 }
333
334 nLastBlockTx = nBlockTx;
335 nLastBlockSize = nBlockSize;
336 LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize);
337
338 // Create coinbase tx
339 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(chainparams.GetConsensus(), nHeight);
340 txNew.vin.resize(1);
341 txNew.vin[0].prevout.SetNull();
342 txNew.vout.resize(1);
343 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
344 txNew.vout[0].nValue = GetBlockSubsidy(nHeight, chainparams.GetConsensus());
345
346 if ((nHeight > 0) && (nHeight <= chainparams.GetConsensus().GetLastFoundersRewardBlockHeight())) {
347 // Founders reward is 20% of the block subsidy
348 auto vFoundersReward = txNew.vout[0].nValue / 5;
349 // Take some reward away from us
350 txNew.vout[0].nValue -= vFoundersReward;
351
352 // And give it to the founders
353 txNew.vout.push_back(CTxOut(vFoundersReward, chainparams.GetFoundersRewardScriptAtHeight(nHeight)));
354 }
355
356 // Add fees
357 txNew.vout[0].nValue += nFees;
358 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
359
360 pblock->vtx[0] = txNew;
361 pblocktemplate->vTxFees[0] = -nFees;
362
363 // Randomise nonce
364 arith_uint256 nonce = UintToArith256(GetRandHash());
365 // Clear the top and bottom 16 bits (for local use as thread flags and counters)
366 nonce <<= 32;
367 nonce >>= 16;
368 pblock->nNonce = ArithToUint256(nonce);
369
370 // Fill in header
371 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
372 pblock->hashReserved = uint256();
373 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
374 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
375 pblock->nSolution.clear();
376 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
377
378 CValidationState state;
379 if (!TestBlockValidity(state, *pblock, pindexPrev, false, false))
380 throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed");
381 }
382
383 return pblocktemplate.release();
384}
385
386#ifdef ENABLE_WALLET
387boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)
388#else
389boost::optional<CScript> GetMinerScriptPubKey()
390#endif
391{
392 CKeyID keyID;
393 CBitcoinAddress addr;
394 if (addr.SetString(GetArg("-mineraddress", ""))) {
395 addr.GetKeyID(keyID);
396 } else {
397#ifdef ENABLE_WALLET
398 CPubKey pubkey;
399 if (!reservekey.GetReservedKey(pubkey)) {
400 return boost::optional<CScript>();
401 }
402 keyID = pubkey.GetID();
403#else
404 return boost::optional<CScript>();
405#endif
406 }
407
408 CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
409 return scriptPubKey;
410}
411
412#ifdef ENABLE_WALLET
413CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
414{
415 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);
416#else
417CBlockTemplate* CreateNewBlockWithKey()
418{
419 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();
420#endif
421
422 if (!scriptPubKey) {
423 return NULL;
424 }
425 return CreateNewBlock(*scriptPubKey);
426}
427
428//////////////////////////////////////////////////////////////////////////////
429//
430// Internal miner
431//
432
433#ifdef ENABLE_MINING
434
435void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
436{
437 // Update nExtraNonce
438 static uint256 hashPrevBlock;
439 if (hashPrevBlock != pblock->hashPrevBlock)
440 {
441 nExtraNonce = 0;
442 hashPrevBlock = pblock->hashPrevBlock;
443 }
444 ++nExtraNonce;
445 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
446 CMutableTransaction txCoinbase(pblock->vtx[0]);
447 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
448 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
449
450 pblock->vtx[0] = txCoinbase;
451 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
452}
453
454#ifdef ENABLE_WALLET
455static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
456#else
457static bool ProcessBlockFound(CBlock* pblock)
458#endif // ENABLE_WALLET
459{
460 LogPrintf("%s\n", pblock->ToString());
461 LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue));
462
463 // Found a solution
464 {
465 LOCK(cs_main);
466 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
467 return error("ZcashMiner: generated block is stale");
468 }
469
470#ifdef ENABLE_WALLET
471 if (GetArg("-mineraddress", "").empty()) {
472 // Remove key from key pool
473 reservekey.KeepKey();
474 }
475
476 // Track how many getdata requests this block gets
477 {
478 LOCK(wallet.cs_wallet);
479 wallet.mapRequestCount[pblock->GetHash()] = 0;
480 }
481#endif
482
483 // Process this block the same as if we had received it from another node
484 CValidationState state;
485 if (!ProcessNewBlock(state, NULL, pblock, true, NULL))
486 return error("ZcashMiner: ProcessNewBlock, block not accepted");
487
488 TrackMinedBlock(pblock->GetHash());
489
490 return true;
491}
492
493#ifdef ENABLE_WALLET
494void static BitcoinMiner(CWallet *pwallet)
495#else
496void static BitcoinMiner()
497#endif
498{
499 LogPrintf("ZcashMiner started\n");
500 SetThreadPriority(THREAD_PRIORITY_LOWEST);
501 RenameThread("zcash-miner");
502 const CChainParams& chainparams = Params();
503
504#ifdef ENABLE_WALLET
505 // Each thread has its own key
506 CReserveKey reservekey(pwallet);
507#endif
508
509 // Each thread has its own counter
510 unsigned int nExtraNonce = 0;
511
512 unsigned int n = chainparams.EquihashN();
513 unsigned int k = chainparams.EquihashK();
514
515 std::string solver = GetArg("-equihashsolver", "default");
516 assert(solver == "tromp" || solver == "default");
517 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
518
519 std::mutex m_cs;
520 bool cancelSolver = false;
521 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
522 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
523 std::lock_guard<std::mutex> lock{m_cs};
524 cancelSolver = true;
525 }
526 );
527 miningTimer.start();
528
529 try {
530 while (true) {
531 if (chainparams.MiningRequiresPeers()) {
532 // Busy-wait for the network to come online so we don't waste time mining
533 // on an obsolete chain. In regtest mode we expect to fly solo.
534 miningTimer.stop();
535 do {
536 bool fvNodesEmpty;
537 {
538 LOCK(cs_vNodes);
539 fvNodesEmpty = vNodes.empty();
540 }
541 if (!fvNodesEmpty && !IsInitialBlockDownload())
542 break;
543 MilliSleep(1000);
544 } while (true);
545 miningTimer.start();
546 }
547
548 //
549 // Create new block
550 //
551 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
552 CBlockIndex* pindexPrev = chainActive.Tip();
553
554#ifdef ENABLE_WALLET
555 unique_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
556#else
557 unique_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey());
558#endif
559 if (!pblocktemplate.get())
560 {
561 if (GetArg("-mineraddress", "").empty()) {
562 LogPrintf("Error in ZcashMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
563 } else {
564 // Should never reach here, because -mineraddress validity is checked in init.cpp
565 LogPrintf("Error in ZcashMiner: Invalid -mineraddress\n");
566 }
567 return;
568 }
569 CBlock *pblock = &pblocktemplate->block;
570 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
571
572 LogPrintf("Running ZcashMiner with %u transactions in block (%u bytes)\n", pblock->vtx.size(),
573 ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
574
575 //
576 // Search
577 //
578 int64_t nStart = GetTime();
579 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
580
581 while (true) {
582 // Hash state
583 crypto_generichash_blake2b_state state;
584 EhInitialiseState(n, k, state);
585
586 // I = the block header minus nonce and solution.
587 CEquihashInput I{*pblock};
588 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
589 ss << I;
590
591 // H(I||...
592 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
593
594 // H(I||V||...
595 crypto_generichash_blake2b_state curr_state;
596 curr_state = state;
597 crypto_generichash_blake2b_update(&curr_state,
598 pblock->nNonce.begin(),
599 pblock->nNonce.size());
600
601 // (x_1, x_2, ...) = A(I, V, n, k)
602 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",
603 solver, pblock->nNonce.ToString());
604
605 std::function<bool(std::vector<unsigned char>)> validBlock =
606#ifdef ENABLE_WALLET
607 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
608#else
609 [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
610#endif
611 (std::vector<unsigned char> soln) {
612 // Write the solution to the hash and compute the result.
613 LogPrint("pow", "- Checking solution against target\n");
614 pblock->nSolution = soln;
615 solutionTargetChecks.increment();
616
617 if (UintToArith256(pblock->GetHash()) > hashTarget) {
618 return false;
619 }
620
621 // Found a solution
622 SetThreadPriority(THREAD_PRIORITY_NORMAL);
623 LogPrintf("ZcashMiner:\n");
624 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
625#ifdef ENABLE_WALLET
626 if (ProcessBlockFound(pblock, *pwallet, reservekey)) {
627#else
628 if (ProcessBlockFound(pblock)) {
629#endif
630 // Ignore chain updates caused by us
631 std::lock_guard<std::mutex> lock{m_cs};
632 cancelSolver = false;
633 }
634 SetThreadPriority(THREAD_PRIORITY_LOWEST);
635
636 // In regression test mode, stop mining after a block is found.
637 if (chainparams.MineBlocksOnDemand()) {
638 // Increment here because throwing skips the call below
639 ehSolverRuns.increment();
640 throw boost::thread_interrupted();
641 }
642
643 return true;
644 };
645 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
646 std::lock_guard<std::mutex> lock{m_cs};
647 return cancelSolver;
648 };
649
650 // TODO: factor this out into a function with the same API for each solver.
651 if (solver == "tromp") {
652 // Create solver and initialize it.
653 equi eq(1);
654 eq.setstate(&curr_state);
655
656 // Intialization done, start algo driver.
657 eq.digit0(0);
658 eq.xfull = eq.bfull = eq.hfull = 0;
659 eq.showbsizes(0);
660 for (u32 r = 1; r < WK; r++) {
661 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
662 eq.xfull = eq.bfull = eq.hfull = 0;
663 eq.showbsizes(r);
664 }
665 eq.digitK(0);
666 ehSolverRuns.increment();
667
668 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
669 for (size_t s = 0; s < eq.nsols; s++) {
670 LogPrint("pow", "Checking solution %d\n", s+1);
671 std::vector<eh_index> index_vector(PROOFSIZE);
672 for (size_t i = 0; i < PROOFSIZE; i++) {
673 index_vector[i] = eq.sols[s][i];
674 }
675 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
676
677 if (validBlock(sol_char)) {
678 // If we find a POW solution, do not try other solutions
679 // because they become invalid as we created a new block in blockchain.
680 break;
681 }
682 }
683 } else {
684 try {
685 // If we find a valid block, we rebuild
686 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
687 ehSolverRuns.increment();
688 if (found) {
689 break;
690 }
691 } catch (EhSolverCancelledException&) {
692 LogPrint("pow", "Equihash solver cancelled\n");
693 std::lock_guard<std::mutex> lock{m_cs};
694 cancelSolver = false;
695 }
696 }
697
698 // Check for stop or if block needs to be rebuilt
699 boost::this_thread::interruption_point();
700 // Regtest mode doesn't require peers
701 if (vNodes.empty() && chainparams.MiningRequiresPeers())
702 break;
703 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
704 break;
705 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
706 break;
707 if (pindexPrev != chainActive.Tip())
708 break;
709
710 // Update nNonce and nTime
711 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
712 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
713 }
714 }
715 }
716 catch (const boost::thread_interrupted&)
717 {
718 miningTimer.stop();
719 c.disconnect();
720 LogPrintf("ZcashMiner terminated\n");
721 throw;
722 }
723 catch (const std::runtime_error &e)
724 {
725 miningTimer.stop();
726 c.disconnect();
727 LogPrintf("ZcashMiner runtime error: %s\n", e.what());
728 return;
729 }
730 miningTimer.stop();
731 c.disconnect();
732}
733
734#ifdef ENABLE_WALLET
735void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
736#else
737void GenerateBitcoins(bool fGenerate, int nThreads)
738#endif
739{
740 static boost::thread_group* minerThreads = NULL;
741
742 if (nThreads < 0)
743 nThreads = GetNumCores();
744
745 if (minerThreads != NULL)
746 {
747 minerThreads->interrupt_all();
748 delete minerThreads;
749 minerThreads = NULL;
750 }
751
752 if (nThreads == 0 || !fGenerate)
753 return;
754
755 minerThreads = new boost::thread_group();
756 for (int i = 0; i < nThreads; i++) {
757#ifdef ENABLE_WALLET
758 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
759#else
760 minerThreads->create_thread(&BitcoinMiner);
761#endif
762 }
763}
764
765#endif // ENABLE_MINING
This page took 0.029909 seconds and 4 git commands to generate.