]> Git Repo - VerusCoin.git/blob - src/miner.cpp
41b54ad36e3641d592563efdeee190c247c87702
[VerusCoin.git] / src / miner.cpp
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/upgrades.h"
16 #include "consensus/validation.h"
17 #ifdef ENABLE_MINING
18 #include "crypto/equihash.h"
19 #endif
20 #include "hash.h"
21 #include "main.h"
22 #include "metrics.h"
23 #include "net.h"
24 #include "pow.h"
25 #include "primitives/transaction.h"
26 #include "random.h"
27 #include "timedata.h"
28 #include "ui_interface.h"
29 #include "util.h"
30 #include "utilmoneystr.h"
31 #ifdef ENABLE_WALLET
32 #include "wallet/wallet.h"
33 #endif
34
35 #include "sodium.h"
36
37 #include <boost/thread.hpp>
38 #include <boost/tuple/tuple.hpp>
39 #ifdef ENABLE_MINING
40 #include <functional>
41 #endif
42 #include <mutex>
43
44 using namespace std;
45
46 //////////////////////////////////////////////////////////////////////////////
47 //
48 // BitcoinMiner
49 //
50
51 //
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.
58 //
59 class COrphan
60 {
61 public:
62     const CTransaction* ptx;
63     set<uint256> setDependsOn;
64     CFeeRate feeRate;
65     double dPriority;
66
67     COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
68     {
69     }
70 };
71
72 uint64_t nLastBlockTx = 0;
73 uint64_t nLastBlockSize = 0;
74
75 // We want to sort transactions by priority and fee rate, so:
76 typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
77 class TxPriorityCompare
78 {
79     bool byFee;
80
81 public:
82     TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
83
84     bool operator()(const TxPriority& a, const TxPriority& b)
85     {
86         if (byFee)
87         {
88             if (a.get<1>() == b.get<1>())
89                 return a.get<0>() < b.get<0>();
90             return a.get<1>() < b.get<1>();
91         }
92         else
93         {
94             if (a.get<0>() == b.get<0>())
95                 return a.get<1>() < b.get<1>();
96             return a.get<0>() < b.get<0>();
97         }
98     }
99 };
100
101 void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
102 {
103     pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
104 }
105
106 CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
107 {
108     const CChainParams& chainparams = Params();
109     // Create new block
110     std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
111     if(!pblocktemplate.get())
112         return NULL;
113     CBlock *pblock = &pblocktemplate->block; // pointer for convenience
114
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);
119
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
124
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));
129
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);
134
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);
139
140     // Collect memory pool transactions into the block
141     CAmount nFees = 0;
142
143     {
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);
151
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);
156
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)
162         {
163             const CTransaction& tx = mi->GetTx();
164
165             int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
166                                     ? nMedianTimePast
167                                     : pblock->GetBlockTime();
168
169             if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight))
170                 continue;
171
172             COrphan* porphan = NULL;
173             double dPriority = 0;
174             CAmount nTotalIn = 0;
175             bool fMissingInputs = false;
176             BOOST_FOREACH(const CTxIn& txin, tx.vin)
177             {
178                 // Read prev transaction
179                 if (!view.HaveCoins(txin.prevout.hash))
180                 {
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))
185                     {
186                         LogPrintf("ERROR: mempool transaction missing input\n");
187                         if (fDebug) assert("mempool transaction missing input" == 0);
188                         fMissingInputs = true;
189                         if (porphan)
190                             vOrphan.pop_back();
191                         break;
192                     }
193
194                     // Has to wait for dependencies
195                     if (!porphan)
196                     {
197                         // Use list for automatic deletion
198                         vOrphan.push_back(COrphan(&tx));
199                         porphan = &vOrphan.back();
200                     }
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;
204                     continue;
205                 }
206                 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
207                 assert(coins);
208
209                 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
210                 nTotalIn += nValueIn;
211
212                 int nConf = nHeight - coins->nHeight;
213
214                 dPriority += (double)nValueIn * nConf;
215             }
216             nTotalIn += tx.GetJoinSplitValueIn();
217
218             if (fMissingInputs) continue;
219
220             // Priority is sum(valuein * age) / modified_txsize
221             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
222             dPriority = tx.ComputePriority(dPriority, nTxSize);
223
224             uint256 hash = tx.GetHash();
225             mempool.ApplyDeltas(hash, dPriority, nTotalIn);
226
227             CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
228
229             if (porphan)
230             {
231                 porphan->dPriority = dPriority;
232                 porphan->feeRate = feeRate;
233             }
234             else
235                 vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));
236         }
237
238         // Collect transactions into block
239         uint64_t nBlockSize = 1000;
240         uint64_t nBlockTx = 0;
241         int nBlockSigOps = 100;
242         bool fSortedByFee = (nBlockPrioritySize <= 0);
243
244         TxPriorityCompare comparer(fSortedByFee);
245         std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
246
247         while (!vecPriority.empty())
248         {
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>());
253
254             std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
255             vecPriority.pop_back();
256
257             // Size limits
258             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
259             if (nBlockSize + nTxSize >= nBlockMaxSize)
260                 continue;
261
262             // Legacy limits on sigOps:
263             unsigned int nTxSigOps = GetLegacySigOpCount(tx);
264             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
265                 continue;
266
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))
273                 continue;
274
275             // Prioritise by fee once past the priority size or we run out of high-priority
276             // transactions:
277             if (!fSortedByFee &&
278                 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
279             {
280                 fSortedByFee = true;
281                 comparer = TxPriorityCompare(fSortedByFee);
282                 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
283             }
284
285             if (!view.HaveInputs(tx))
286                 continue;
287
288             CAmount nTxFees = view.GetValueIn(tx)-tx.GetValueOut();
289
290             nTxSigOps += GetP2SHSigOpCount(tx, view);
291             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
292                 continue;
293
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))
300                 continue;
301
302             UpdateCoins(tx, view, nHeight);
303
304             // Added
305             pblock->vtx.push_back(tx);
306             pblocktemplate->vTxFees.push_back(nTxFees);
307             pblocktemplate->vTxSigOps.push_back(nTxSigOps);
308             nBlockSize += nTxSize;
309             ++nBlockTx;
310             nBlockSigOps += nTxSigOps;
311             nFees += nTxFees;
312
313             if (fPrintPriority)
314             {
315                 LogPrintf("priority %.1f fee %s txid %s\n",
316                     dPriority, feeRate.ToString(), tx.GetHash().ToString());
317             }
318
319             // Add transactions that depend on this one to the priority queue
320             if (mapDependers.count(hash))
321             {
322                 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
323                 {
324                     if (!porphan->setDependsOn.empty())
325                     {
326                         porphan->setDependsOn.erase(hash);
327                         if (porphan->setDependsOn.empty())
328                         {
329                             vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
330                             std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
331                         }
332                     }
333                 }
334             }
335         }
336
337         nLastBlockTx = nBlockTx;
338         nLastBlockSize = nBlockSize;
339         LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize);
340
341         // Create coinbase tx
342         CMutableTransaction txNew = CreateNewContextualCMutableTransaction(chainparams.GetConsensus(), nHeight);
343         txNew.vin.resize(1);
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;
350
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;
356
357             // And give it to the founders
358             txNew.vout.push_back(CTxOut(vFoundersReward, chainparams.GetFoundersRewardScriptAtHeight(nHeight)));
359         }
360
361         // Add fees
362         txNew.vout[0].nValue += nFees;
363         txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
364
365         pblock->vtx[0] = txNew;
366         pblocktemplate->vTxFees[0] = -nFees;
367
368         // Randomise nonce
369         arith_uint256 nonce = UintToArith256(GetRandHash());
370         // Clear the top and bottom 16 bits (for local use as thread flags and counters)
371         nonce <<= 32;
372         nonce >>= 16;
373         pblock->nNonce = ArithToUint256(nonce);
374
375         // Fill in header
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]);
382
383         CValidationState state;
384         if (!TestBlockValidity(state, *pblock, pindexPrev, false, false))
385             throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed");
386     }
387
388     return pblocktemplate.release();
389 }
390
391 #ifdef ENABLE_WALLET
392 boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)
393 #else
394 boost::optional<CScript> GetMinerScriptPubKey()
395 #endif
396 {
397     CKeyID keyID;
398     CTxDestination addr = DecodeDestination(GetArg("-mineraddress", ""));
399     if (IsValidDestination(addr)) {
400         keyID = boost::get<CKeyID>(addr);
401     } else {
402 #ifdef ENABLE_WALLET
403         CPubKey pubkey;
404         if (!reservekey.GetReservedKey(pubkey)) {
405             return boost::optional<CScript>();
406         }
407         keyID = pubkey.GetID();
408 #else
409         return boost::optional<CScript>();
410 #endif
411     }
412
413     CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
414     return scriptPubKey;
415 }
416
417 #ifdef ENABLE_WALLET
418 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
419 {
420     boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);
421 #else
422 CBlockTemplate* CreateNewBlockWithKey()
423 {
424     boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();
425 #endif
426
427     if (!scriptPubKey) {
428         return NULL;
429     }
430     return CreateNewBlock(*scriptPubKey);
431 }
432
433 //////////////////////////////////////////////////////////////////////////////
434 //
435 // Internal miner
436 //
437
438 #ifdef ENABLE_MINING
439
440 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
441 {
442     // Update nExtraNonce
443     static uint256 hashPrevBlock;
444     if (hashPrevBlock != pblock->hashPrevBlock)
445     {
446         nExtraNonce = 0;
447         hashPrevBlock = pblock->hashPrevBlock;
448     }
449     ++nExtraNonce;
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);
454
455     pblock->vtx[0] = txCoinbase;
456     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
457 }
458
459 #ifdef ENABLE_WALLET
460 static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
461 #else
462 static bool ProcessBlockFound(CBlock* pblock)
463 #endif // ENABLE_WALLET
464 {
465     LogPrintf("%s\n", pblock->ToString());
466     LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue));
467
468     // Found a solution
469     {
470         LOCK(cs_main);
471         if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
472             return error("ZcashMiner: generated block is stale");
473     }
474
475 #ifdef ENABLE_WALLET
476     if (GetArg("-mineraddress", "").empty()) {
477         // Remove key from key pool
478         reservekey.KeepKey();
479     }
480
481     // Track how many getdata requests this block gets
482     {
483         LOCK(wallet.cs_wallet);
484         wallet.mapRequestCount[pblock->GetHash()] = 0;
485     }
486 #endif
487
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");
492
493     TrackMinedBlock(pblock->GetHash());
494
495     return true;
496 }
497
498 #ifdef ENABLE_WALLET
499 void static BitcoinMiner(CWallet *pwallet)
500 #else
501 void static BitcoinMiner()
502 #endif
503 {
504     LogPrintf("ZcashMiner started\n");
505     SetThreadPriority(THREAD_PRIORITY_LOWEST);
506     RenameThread("zcash-miner");
507     const CChainParams& chainparams = Params();
508
509 #ifdef ENABLE_WALLET
510     // Each thread has its own key
511     CReserveKey reservekey(pwallet);
512 #endif
513
514     // Each thread has its own counter
515     unsigned int nExtraNonce = 0;
516
517     unsigned int n = chainparams.EquihashN();
518     unsigned int k = chainparams.EquihashK();
519
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);
523
524     std::mutex m_cs;
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};
529             cancelSolver = true;
530         }
531     );
532     miningTimer.start();
533
534     try {
535         while (true) {
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.
539                 miningTimer.stop();
540                 do {
541                     bool fvNodesEmpty;
542                     {
543                         LOCK(cs_vNodes);
544                         fvNodesEmpty = vNodes.empty();
545                     }
546                     if (!fvNodesEmpty && !IsInitialBlockDownload())
547                         break;
548                     MilliSleep(1000);
549                 } while (true);
550                 miningTimer.start();
551             }
552
553             //
554             // Create new block
555             //
556             unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
557             CBlockIndex* pindexPrev = chainActive.Tip();
558
559 #ifdef ENABLE_WALLET
560             unique_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
561 #else
562             unique_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey());
563 #endif
564             if (!pblocktemplate.get())
565             {
566                 if (GetArg("-mineraddress", "").empty()) {
567                     LogPrintf("Error in ZcashMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
568                 } else {
569                     // Should never reach here, because -mineraddress validity is checked in init.cpp
570                     LogPrintf("Error in ZcashMiner: Invalid -mineraddress\n");
571                 }
572                 return;
573             }
574             CBlock *pblock = &pblocktemplate->block;
575             IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
576
577             LogPrintf("Running ZcashMiner with %u transactions in block (%u bytes)\n", pblock->vtx.size(),
578                 ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
579
580             //
581             // Search
582             //
583             int64_t nStart = GetTime();
584             arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
585
586             while (true) {
587                 // Hash state
588                 crypto_generichash_blake2b_state state;
589                 EhInitialiseState(n, k, state);
590
591                 // I = the block header minus nonce and solution.
592                 CEquihashInput I{*pblock};
593                 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
594                 ss << I;
595
596                 // H(I||...
597                 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
598
599                 // H(I||V||...
600                 crypto_generichash_blake2b_state curr_state;
601                 curr_state = state;
602                 crypto_generichash_blake2b_update(&curr_state,
603                                                   pblock->nNonce.begin(),
604                                                   pblock->nNonce.size());
605
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());
609
610                 std::function<bool(std::vector<unsigned char>)> validBlock =
611 #ifdef ENABLE_WALLET
612                         [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
613 #else
614                         [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
615 #endif
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();
621
622                     if (UintToArith256(pblock->GetHash()) > hashTarget) {
623                         return false;
624                     }
625
626                     // Found a solution
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());
630 #ifdef ENABLE_WALLET
631                     if (ProcessBlockFound(pblock, *pwallet, reservekey)) {
632 #else
633                     if (ProcessBlockFound(pblock)) {
634 #endif
635                         // Ignore chain updates caused by us
636                         std::lock_guard<std::mutex> lock{m_cs};
637                         cancelSolver = false;
638                     }
639                     SetThreadPriority(THREAD_PRIORITY_LOWEST);
640
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();
646                     }
647
648                     return true;
649                 };
650                 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
651                     std::lock_guard<std::mutex> lock{m_cs};
652                     return cancelSolver;
653                 };
654
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.
658                     equi eq(1);
659                     eq.setstate(&curr_state);
660
661                     // Initialization done, start algo driver.
662                     eq.digit0(0);
663                     eq.xfull = eq.bfull = eq.hfull = 0;
664                     eq.showbsizes(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;
668                         eq.showbsizes(r);
669                     }
670                     eq.digitK(0);
671                     ehSolverRuns.increment();
672
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];
679                         }
680                         std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
681
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.
685                             break;
686                         }
687                     }
688                 } else {
689                     try {
690                         // If we find a valid block, we rebuild
691                         bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
692                         ehSolverRuns.increment();
693                         if (found) {
694                             break;
695                         }
696                     } catch (EhSolverCancelledException&) {
697                         LogPrint("pow", "Equihash solver cancelled\n");
698                         std::lock_guard<std::mutex> lock{m_cs};
699                         cancelSolver = false;
700                     }
701                 }
702
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())
707                     break;
708                 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
709                     break;
710                 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
711                     break;
712                 if (pindexPrev != chainActive.Tip())
713                     break;
714
715                 // Update nNonce and nTime
716                 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
717                 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
718             }
719         }
720     }
721     catch (const boost::thread_interrupted&)
722     {
723         miningTimer.stop();
724         c.disconnect();
725         LogPrintf("ZcashMiner terminated\n");
726         throw;
727     }
728     catch (const std::runtime_error &e)
729     {
730         miningTimer.stop();
731         c.disconnect();
732         LogPrintf("ZcashMiner runtime error: %s\n", e.what());
733         return;
734     }
735     miningTimer.stop();
736     c.disconnect();
737 }
738
739 #ifdef ENABLE_WALLET
740 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
741 #else
742 void GenerateBitcoins(bool fGenerate, int nThreads)
743 #endif
744 {
745     static boost::thread_group* minerThreads = NULL;
746
747     if (nThreads < 0)
748         nThreads = GetNumCores();
749
750     if (minerThreads != NULL)
751     {
752         minerThreads->interrupt_all();
753         delete minerThreads;
754         minerThreads = NULL;
755     }
756
757     if (nThreads == 0 || !fGenerate)
758         return;
759
760     minerThreads = new boost::thread_group();
761     for (int i = 0; i < nThreads; i++) {
762 #ifdef ENABLE_WALLET
763         minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
764 #else
765         minerThreads->create_thread(&BitcoinMiner);
766 #endif
767     }
768 }
769
770 #endif // ENABLE_MINING
This page took 0.06008 seconds and 2 git commands to generate.