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