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