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