]> Git Repo - VerusCoin.git/blob - src/miner.cpp
Merge pull request #3411
[VerusCoin.git] / src / miner.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2013 The Bitcoin developers
3 // Distributed under the MIT/X11 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 "core.h"
9 #include "main.h"
10 #include "net.h"
11 #include "wallet.h"
12
13 //////////////////////////////////////////////////////////////////////////////
14 //
15 // BitcoinMiner
16 //
17
18 int static FormatHashBlocks(void* pbuffer, unsigned int len)
19 {
20     unsigned char* pdata = (unsigned char*)pbuffer;
21     unsigned int blocks = 1 + ((len + 8) / 64);
22     unsigned char* pend = pdata + 64 * blocks;
23     memset(pdata + len, 0, 64 * blocks - len);
24     pdata[len] = 0x80;
25     unsigned int bits = len * 8;
26     pend[-1] = (bits >> 0) & 0xff;
27     pend[-2] = (bits >> 8) & 0xff;
28     pend[-3] = (bits >> 16) & 0xff;
29     pend[-4] = (bits >> 24) & 0xff;
30     return blocks;
31 }
32
33 static const unsigned int pSHA256InitState[8] =
34 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
35
36 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
37 {
38     SHA256_CTX ctx;
39     unsigned char data[64];
40
41     SHA256_Init(&ctx);
42
43     for (int i = 0; i < 16; i++)
44         ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
45
46     for (int i = 0; i < 8; i++)
47         ctx.h[i] = ((uint32_t*)pinit)[i];
48
49     SHA256_Update(&ctx, data, sizeof(data));
50     for (int i = 0; i < 8; i++)
51         ((uint32_t*)pstate)[i] = ctx.h[i];
52 }
53
54 // Some explaining would be appreciated
55 class COrphan
56 {
57 public:
58     const CTransaction* ptx;
59     set<uint256> setDependsOn;
60     double dPriority;
61     double dFeePerKb;
62
63     COrphan(const CTransaction* ptxIn)
64     {
65         ptx = ptxIn;
66         dPriority = dFeePerKb = 0;
67     }
68
69     void print() const
70     {
71         LogPrintf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
72                ptx->GetHash().ToString().c_str(), dPriority, dFeePerKb);
73         BOOST_FOREACH(uint256 hash, setDependsOn)
74             LogPrintf("   setDependsOn %s\n", hash.ToString().c_str());
75     }
76 };
77
78
79 uint64_t nLastBlockTx = 0;
80 uint64_t nLastBlockSize = 0;
81
82 // We want to sort transactions by priority and fee, so:
83 typedef boost::tuple<double, double, const CTransaction*> TxPriority;
84 class TxPriorityCompare
85 {
86     bool byFee;
87 public:
88     TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
89     bool operator()(const TxPriority& a, const TxPriority& b)
90     {
91         if (byFee)
92         {
93             if (a.get<1>() == b.get<1>())
94                 return a.get<0>() < b.get<0>();
95             return a.get<1>() < b.get<1>();
96         }
97         else
98         {
99             if (a.get<0>() == b.get<0>())
100                 return a.get<1>() < b.get<1>();
101             return a.get<0>() < b.get<0>();
102         }
103     }
104 };
105
106 CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
107 {
108     // Create new block
109     auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
110     if(!pblocktemplate.get())
111         return NULL;
112     CBlock *pblock = &pblocktemplate->block; // pointer for convenience
113
114     // Create coinbase tx
115     CTransaction txNew;
116     txNew.vin.resize(1);
117     txNew.vin[0].prevout.SetNull();
118     txNew.vout.resize(1);
119     txNew.vout[0].scriptPubKey = scriptPubKeyIn;
120
121     // Add our coinbase tx as first transaction
122     pblock->vtx.push_back(txNew);
123     pblocktemplate->vTxFees.push_back(-1); // updated at end
124     pblocktemplate->vTxSigOps.push_back(-1); // updated at end
125
126     // Largest block you're willing to create:
127     unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
128     // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
129     nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
130
131     // How much of the block should be dedicated to high-priority transactions,
132     // included regardless of the fees they pay
133     unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
134     nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
135
136     // Minimum block size you want to create; block will be filled with free transactions
137     // until there are no more or the block reaches this size:
138     unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
139     nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
140
141     // Collect memory pool transactions into the block
142     int64_t nFees = 0;
143     {
144         LOCK2(cs_main, mempool.cs);
145         CBlockIndex* pindexPrev = chainActive.Tip();
146         CCoinsViewCache view(*pcoinsTip, true);
147
148         // Priority order to process transactions
149         list<COrphan> vOrphan; // list memory doesn't move
150         map<uint256, vector<COrphan*> > mapDependers;
151         bool fPrintPriority = GetBoolArg("-printpriority", false);
152
153         // This vector will be sorted into a priority queue:
154         vector<TxPriority> vecPriority;
155         vecPriority.reserve(mempool.mapTx.size());
156         for (map<uint256, CTxMemPoolEntry>::iterator mi = mempool.mapTx.begin();
157              mi != mempool.mapTx.end(); ++mi)
158         {
159             const CTransaction& tx = mi->second.GetTx();
160             if (tx.IsCoinBase() || !IsFinalTx(tx))
161                 continue;
162
163             COrphan* porphan = NULL;
164             double dPriority = 0;
165             int64_t nTotalIn = 0;
166             bool fMissingInputs = false;
167             BOOST_FOREACH(const CTxIn& txin, tx.vin)
168             {
169                 // Read prev transaction
170                 if (!view.HaveCoins(txin.prevout.hash))
171                 {
172                     // This should never happen; all transactions in the memory
173                     // pool should connect to either transactions in the chain
174                     // or other transactions in the memory pool.
175                     if (!mempool.mapTx.count(txin.prevout.hash))
176                     {
177                         LogPrintf("ERROR: mempool transaction missing input\n");
178                         if (fDebug) assert("mempool transaction missing input" == 0);
179                         fMissingInputs = true;
180                         if (porphan)
181                             vOrphan.pop_back();
182                         break;
183                     }
184
185                     // Has to wait for dependencies
186                     if (!porphan)
187                     {
188                         // Use list for automatic deletion
189                         vOrphan.push_back(COrphan(&tx));
190                         porphan = &vOrphan.back();
191                     }
192                     mapDependers[txin.prevout.hash].push_back(porphan);
193                     porphan->setDependsOn.insert(txin.prevout.hash);
194                     nTotalIn += mempool.mapTx[txin.prevout.hash].GetTx().vout[txin.prevout.n].nValue;
195                     continue;
196                 }
197                 const CCoins &coins = view.GetCoins(txin.prevout.hash);
198
199                 int64_t nValueIn = coins.vout[txin.prevout.n].nValue;
200                 nTotalIn += nValueIn;
201
202                 int nConf = pindexPrev->nHeight - coins.nHeight + 1;
203
204                 dPriority += (double)nValueIn * nConf;
205             }
206             if (fMissingInputs) continue;
207
208             // Priority is sum(valuein * age) / modified_txsize
209             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
210             dPriority = tx.ComputePriority(dPriority, nTxSize);
211
212             // This is a more accurate fee-per-kilobyte than is used by the client code, because the
213             // client code rounds up the size to the nearest 1K. That's good, because it gives an
214             // incentive to create smaller transactions.
215             double dFeePerKb =  double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
216
217             if (porphan)
218             {
219                 porphan->dPriority = dPriority;
220                 porphan->dFeePerKb = dFeePerKb;
221             }
222             else
223                 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &mi->second.GetTx()));
224         }
225
226         // Collect transactions into block
227         uint64_t nBlockSize = 1000;
228         uint64_t nBlockTx = 0;
229         int nBlockSigOps = 100;
230         bool fSortedByFee = (nBlockPrioritySize <= 0);
231
232         TxPriorityCompare comparer(fSortedByFee);
233         std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
234
235         while (!vecPriority.empty())
236         {
237             // Take highest priority transaction off the priority queue:
238             double dPriority = vecPriority.front().get<0>();
239             double dFeePerKb = vecPriority.front().get<1>();
240             const CTransaction& tx = *(vecPriority.front().get<2>());
241
242             std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
243             vecPriority.pop_back();
244
245             // Size limits
246             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
247             if (nBlockSize + nTxSize >= nBlockMaxSize)
248                 continue;
249
250             // Legacy limits on sigOps:
251             unsigned int nTxSigOps = GetLegacySigOpCount(tx);
252             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
253                 continue;
254
255             // Skip free transactions if we're past the minimum block size:
256             if (fSortedByFee && (dFeePerKb < CTransaction::nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
257                 continue;
258
259             // Prioritize by fee once past the priority size or we run out of high-priority
260             // transactions:
261             if (!fSortedByFee &&
262                 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
263             {
264                 fSortedByFee = true;
265                 comparer = TxPriorityCompare(fSortedByFee);
266                 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
267             }
268
269             if (!view.HaveInputs(tx))
270                 continue;
271
272             int64_t nTxFees = view.GetValueIn(tx)-tx.GetValueOut();
273
274             nTxSigOps += GetP2SHSigOpCount(tx, view);
275             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
276                 continue;
277
278             CValidationState state;
279             if (!CheckInputs(tx, state, view, true, SCRIPT_VERIFY_P2SH))
280                 continue;
281
282             CTxUndo txundo;
283             uint256 hash = tx.GetHash();
284             UpdateCoins(tx, state, view, txundo, pindexPrev->nHeight+1, hash);
285
286             // Added
287             pblock->vtx.push_back(tx);
288             pblocktemplate->vTxFees.push_back(nTxFees);
289             pblocktemplate->vTxSigOps.push_back(nTxSigOps);
290             nBlockSize += nTxSize;
291             ++nBlockTx;
292             nBlockSigOps += nTxSigOps;
293             nFees += nTxFees;
294
295             if (fPrintPriority)
296             {
297                 LogPrintf("priority %.1f feeperkb %.1f txid %s\n",
298                        dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
299             }
300
301             // Add transactions that depend on this one to the priority queue
302             if (mapDependers.count(hash))
303             {
304                 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
305                 {
306                     if (!porphan->setDependsOn.empty())
307                     {
308                         porphan->setDependsOn.erase(hash);
309                         if (porphan->setDependsOn.empty())
310                         {
311                             vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
312                             std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
313                         }
314                     }
315                 }
316             }
317         }
318
319         nLastBlockTx = nBlockTx;
320         nLastBlockSize = nBlockSize;
321         LogPrintf("CreateNewBlock(): total size %"PRIu64"\n", nBlockSize);
322
323         pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
324         pblocktemplate->vTxFees[0] = -nFees;
325
326         // Fill in header
327         pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
328         UpdateTime(*pblock, pindexPrev);
329         pblock->nBits          = GetNextWorkRequired(pindexPrev, pblock);
330         pblock->nNonce         = 0;
331         pblock->vtx[0].vin[0].scriptSig = CScript() << OP_0 << OP_0;
332         pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
333
334         CBlockIndex indexDummy(*pblock);
335         indexDummy.pprev = pindexPrev;
336         indexDummy.nHeight = pindexPrev->nHeight + 1;
337         CCoinsViewCache viewNew(*pcoinsTip, true);
338         CValidationState state;
339         if (!ConnectBlock(*pblock, state, &indexDummy, viewNew, true))
340             throw std::runtime_error("CreateNewBlock() : ConnectBlock failed");
341     }
342
343     return pblocktemplate.release();
344 }
345
346 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
347 {
348     // Update nExtraNonce
349     static uint256 hashPrevBlock;
350     if (hashPrevBlock != pblock->hashPrevBlock)
351     {
352         nExtraNonce = 0;
353         hashPrevBlock = pblock->hashPrevBlock;
354     }
355     ++nExtraNonce;
356     unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
357     pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
358     assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
359
360     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
361 }
362
363
364 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
365 {
366     //
367     // Pre-build hash buffers
368     //
369     struct
370     {
371         struct unnamed2
372         {
373             int nVersion;
374             uint256 hashPrevBlock;
375             uint256 hashMerkleRoot;
376             unsigned int nTime;
377             unsigned int nBits;
378             unsigned int nNonce;
379         }
380         block;
381         unsigned char pchPadding0[64];
382         uint256 hash1;
383         unsigned char pchPadding1[64];
384     }
385     tmp;
386     memset(&tmp, 0, sizeof(tmp));
387
388     tmp.block.nVersion       = pblock->nVersion;
389     tmp.block.hashPrevBlock  = pblock->hashPrevBlock;
390     tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
391     tmp.block.nTime          = pblock->nTime;
392     tmp.block.nBits          = pblock->nBits;
393     tmp.block.nNonce         = pblock->nNonce;
394
395     FormatHashBlocks(&tmp.block, sizeof(tmp.block));
396     FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
397
398     // Byte swap all the input buffer
399     for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
400         ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
401
402     // Precalc the first half of the first hash, which stays constant
403     SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
404
405     memcpy(pdata, &tmp.block, 128);
406     memcpy(phash1, &tmp.hash1, 64);
407 }
408
409 #ifdef ENABLE_WALLET
410 //////////////////////////////////////////////////////////////////////////////
411 //
412 // Internal miner
413 //
414 double dHashesPerSec = 0.0;
415 int64_t nHPSTimerStart = 0;
416
417 //
418 // ScanHash scans nonces looking for a hash with at least some zero bits.
419 // It operates on big endian data.  Caller does the byte reversing.
420 // All input buffers are 16-byte aligned.  nNonce is usually preserved
421 // between calls, but periodically or if nNonce is 0xffff0000 or above,
422 // the block is rebuilt and nNonce starts over at zero.
423 //
424 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
425 {
426     unsigned int& nNonce = *(unsigned int*)(pdata + 12);
427     for (;;)
428     {
429         // Crypto++ SHA256
430         // Hash pdata using pmidstate as the starting state into
431         // pre-formatted buffer phash1, then hash phash1 into phash
432         nNonce++;
433         SHA256Transform(phash1, pdata, pmidstate);
434         SHA256Transform(phash, phash1, pSHA256InitState);
435
436         // Return the nonce if the hash has at least some zero bits,
437         // caller will check if it has enough to reach the target
438         if (((unsigned short*)phash)[14] == 0)
439             return nNonce;
440
441         // If nothing found after trying for a while, return -1
442         if ((nNonce & 0xffff) == 0)
443         {
444             nHashesDone = 0xffff+1;
445             return (unsigned int) -1;
446         }
447         if ((nNonce & 0xfff) == 0)
448             boost::this_thread::interruption_point();
449     }
450 }
451
452 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
453 {
454     CPubKey pubkey;
455     if (!reservekey.GetReservedKey(pubkey))
456         return NULL;
457
458     CScript scriptPubKey = CScript() << pubkey << OP_CHECKSIG;
459     return CreateNewBlock(scriptPubKey);
460 }
461
462 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
463 {
464     uint256 hash = pblock->GetHash();
465     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
466
467     if (hash > hashTarget)
468         return false;
469
470     //// debug print
471     LogPrintf("BitcoinMiner:\n");
472     LogPrintf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
473     pblock->print();
474     LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
475
476     // Found a solution
477     {
478         LOCK(cs_main);
479         if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
480             return error("BitcoinMiner : generated block is stale");
481
482         // Remove key from key pool
483         reservekey.KeepKey();
484
485         // Track how many getdata requests this block gets
486         {
487             LOCK(wallet.cs_wallet);
488             wallet.mapRequestCount[pblock->GetHash()] = 0;
489         }
490
491         // Process this block the same as if we had received it from another node
492         CValidationState state;
493         if (!ProcessBlock(state, NULL, pblock))
494             return error("BitcoinMiner : ProcessBlock, block not accepted");
495     }
496
497     return true;
498 }
499
500 void static BitcoinMiner(CWallet *pwallet)
501 {
502     LogPrintf("BitcoinMiner started\n");
503     SetThreadPriority(THREAD_PRIORITY_LOWEST);
504     RenameThread("bitcoin-miner");
505
506     // Each thread has its own key and counter
507     CReserveKey reservekey(pwallet);
508     unsigned int nExtraNonce = 0;
509
510     try { while (true) {
511         if (Params().NetworkID() != CChainParams::REGTEST) {
512             // Busy-wait for the network to come online so we don't waste time mining
513             // on an obsolete chain. In regtest mode we expect to fly solo.
514             while (vNodes.empty())
515                 MilliSleep(1000);
516         }
517
518         //
519         // Create new block
520         //
521         unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
522         CBlockIndex* pindexPrev = chainActive.Tip();
523
524         auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
525         if (!pblocktemplate.get())
526             return;
527         CBlock *pblock = &pblocktemplate->block;
528         IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
529
530         LogPrintf("Running BitcoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
531                ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
532
533         //
534         // Pre-build hash buffers
535         //
536         char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
537         char pdatabuf[128+16];    char* pdata     = alignup<16>(pdatabuf);
538         char phash1buf[64+16];    char* phash1    = alignup<16>(phash1buf);
539
540         FormatHashBuffers(pblock, pmidstate, pdata, phash1);
541
542         unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
543         unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
544         unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
545
546
547         //
548         // Search
549         //
550         int64_t nStart = GetTime();
551         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
552         uint256 hashbuf[2];
553         uint256& hash = *alignup<16>(hashbuf);
554         while (true)
555         {
556             unsigned int nHashesDone = 0;
557             unsigned int nNonceFound;
558
559             // Crypto++ SHA256
560             nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
561                                             (char*)&hash, nHashesDone);
562
563             // Check if something found
564             if (nNonceFound != (unsigned int) -1)
565             {
566                 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
567                     ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
568
569                 if (hash <= hashTarget)
570                 {
571                     // Found a solution
572                     pblock->nNonce = ByteReverse(nNonceFound);
573                     assert(hash == pblock->GetHash());
574
575                     SetThreadPriority(THREAD_PRIORITY_NORMAL);
576                     CheckWork(pblock, *pwallet, reservekey);
577                     SetThreadPriority(THREAD_PRIORITY_LOWEST);
578
579                     // In regression test mode, stop mining after a block is found. This
580                     // allows developers to controllably generate a block on demand.
581                     if (Params().NetworkID() == CChainParams::REGTEST)
582                         throw boost::thread_interrupted();
583
584                     break;
585                 }
586             }
587
588             // Meter hashes/sec
589             static int64_t nHashCounter;
590             if (nHPSTimerStart == 0)
591             {
592                 nHPSTimerStart = GetTimeMillis();
593                 nHashCounter = 0;
594             }
595             else
596                 nHashCounter += nHashesDone;
597             if (GetTimeMillis() - nHPSTimerStart > 4000)
598             {
599                 static CCriticalSection cs;
600                 {
601                     LOCK(cs);
602                     if (GetTimeMillis() - nHPSTimerStart > 4000)
603                     {
604                         dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
605                         nHPSTimerStart = GetTimeMillis();
606                         nHashCounter = 0;
607                         static int64_t nLogTime;
608                         if (GetTime() - nLogTime > 30 * 60)
609                         {
610                             nLogTime = GetTime();
611                             LogPrintf("hashmeter %6.0f khash/s\n", dHashesPerSec/1000.0);
612                         }
613                     }
614                 }
615             }
616
617             // Check for stop or if block needs to be rebuilt
618             boost::this_thread::interruption_point();
619             if (vNodes.empty() && Params().NetworkID() != CChainParams::REGTEST)
620                 break;
621             if (nBlockNonce >= 0xffff0000)
622                 break;
623             if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
624                 break;
625             if (pindexPrev != chainActive.Tip())
626                 break;
627
628             // Update nTime every few seconds
629             UpdateTime(*pblock, pindexPrev);
630             nBlockTime = ByteReverse(pblock->nTime);
631             if (TestNet())
632             {
633                 // Changing pblock->nTime can change work required on testnet:
634                 nBlockBits = ByteReverse(pblock->nBits);
635                 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
636             }
637         }
638     } }
639     catch (boost::thread_interrupted)
640     {
641         LogPrintf("BitcoinMiner terminated\n");
642         throw;
643     }
644 }
645
646 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
647 {
648     static boost::thread_group* minerThreads = NULL;
649
650     if (nThreads < 0) {
651         if (Params().NetworkID() == CChainParams::REGTEST)
652             nThreads = 1;
653         else
654             nThreads = boost::thread::hardware_concurrency();
655     }
656
657     if (minerThreads != NULL)
658     {
659         minerThreads->interrupt_all();
660         delete minerThreads;
661         minerThreads = NULL;
662     }
663
664     if (nThreads == 0 || !fGenerate)
665         return;
666
667     minerThreads = new boost::thread_group();
668     for (int i = 0; i < nThreads; i++)
669         minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
670 }
671
672 #endif
673
This page took 0.06174 seconds and 4 git commands to generate.