]> Git Repo - VerusCoin.git/blob - src/miner.cpp
Refactor: CTxMempool class to its own txmempool.{cpp,h}
[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 #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 = chainActive.Tip();
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) / modified_txsize
242             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
243             unsigned int nTxSizeMod = nTxSize;
244             // In order to avoid disincentivizing cleaning up the UTXO set we don't count
245             // the constant overhead for each txin and up to 110 bytes of scriptSig (which
246             // is enough to cover a compressed pubkey p2sh redemption) for priority.
247             // Providing any more cleanup incentive than making additional inputs free would
248             // risk encouraging people to create junk outputs to redeem later.
249             BOOST_FOREACH(const CTxIn& txin, tx.vin)
250             {
251                 unsigned int offset = 41U + min(110U, (unsigned int)txin.scriptSig.size());
252                 if (nTxSizeMod > offset)
253                     nTxSizeMod -= offset;
254             }
255             dPriority /= nTxSizeMod;
256
257             // This is a more accurate fee-per-kilobyte than is used by the client code, because the
258             // client code rounds up the size to the nearest 1K. That's good, because it gives an
259             // incentive to create smaller transactions.
260             double dFeePerKb =  double(nTotalIn-GetValueOut(tx)) / (double(nTxSize)/1000.0);
261
262             if (porphan)
263             {
264                 porphan->dPriority = dPriority;
265                 porphan->dFeePerKb = dFeePerKb;
266             }
267             else
268                 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
269         }
270
271         // Collect transactions into block
272         uint64 nBlockSize = 1000;
273         uint64 nBlockTx = 0;
274         int nBlockSigOps = 100;
275         bool fSortedByFee = (nBlockPrioritySize <= 0);
276
277         TxPriorityCompare comparer(fSortedByFee);
278         std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
279
280         while (!vecPriority.empty())
281         {
282             // Take highest priority transaction off the priority queue:
283             double dPriority = vecPriority.front().get<0>();
284             double dFeePerKb = vecPriority.front().get<1>();
285             CTransaction& tx = *(vecPriority.front().get<2>());
286
287             std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
288             vecPriority.pop_back();
289
290             // Size limits
291             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
292             if (nBlockSize + nTxSize >= nBlockMaxSize)
293                 continue;
294
295             // Legacy limits on sigOps:
296             unsigned int nTxSigOps = GetLegacySigOpCount(tx);
297             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
298                 continue;
299
300             // Skip free transactions if we're past the minimum block size:
301             if (fSortedByFee && (dFeePerKb < CTransaction::nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
302                 continue;
303
304             // Prioritize by fee once past the priority size or we run out of high-priority
305             // transactions:
306             if (!fSortedByFee &&
307                 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
308             {
309                 fSortedByFee = true;
310                 comparer = TxPriorityCompare(fSortedByFee);
311                 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
312             }
313
314             if (!view.HaveInputs(tx))
315                 continue;
316
317             int64 nTxFees = view.GetValueIn(tx)-GetValueOut(tx);
318
319             nTxSigOps += GetP2SHSigOpCount(tx, view);
320             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
321                 continue;
322
323             CValidationState state;
324             if (!CheckInputs(tx, state, view, true, SCRIPT_VERIFY_P2SH))
325                 continue;
326
327             CTxUndo txundo;
328             uint256 hash = tx.GetHash();
329             UpdateCoins(tx, state, view, txundo, pindexPrev->nHeight+1, hash);
330
331             // Added
332             pblock->vtx.push_back(tx);
333             pblocktemplate->vTxFees.push_back(nTxFees);
334             pblocktemplate->vTxSigOps.push_back(nTxSigOps);
335             nBlockSize += nTxSize;
336             ++nBlockTx;
337             nBlockSigOps += nTxSigOps;
338             nFees += nTxFees;
339
340             if (fPrintPriority)
341             {
342                 LogPrintf("priority %.1f feeperkb %.1f txid %s\n",
343                        dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
344             }
345
346             // Add transactions that depend on this one to the priority queue
347             if (mapDependers.count(hash))
348             {
349                 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
350                 {
351                     if (!porphan->setDependsOn.empty())
352                     {
353                         porphan->setDependsOn.erase(hash);
354                         if (porphan->setDependsOn.empty())
355                         {
356                             vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
357                             std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
358                         }
359                     }
360                 }
361             }
362         }
363
364         nLastBlockTx = nBlockTx;
365         nLastBlockSize = nBlockSize;
366         LogPrintf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
367
368         pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
369         pblocktemplate->vTxFees[0] = -nFees;
370
371         // Fill in header
372         pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
373         UpdateTime(*pblock, pindexPrev);
374         pblock->nBits          = GetNextWorkRequired(pindexPrev, pblock);
375         pblock->nNonce         = 0;
376         pblock->vtx[0].vin[0].scriptSig = CScript() << OP_0 << OP_0;
377         pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
378
379         CBlockIndex indexDummy(*pblock);
380         indexDummy.pprev = pindexPrev;
381         indexDummy.nHeight = pindexPrev->nHeight + 1;
382         CCoinsViewCache viewNew(*pcoinsTip, true);
383         CValidationState state;
384         if (!ConnectBlock(*pblock, state, &indexDummy, viewNew, true))
385             throw std::runtime_error("CreateNewBlock() : ConnectBlock failed");
386     }
387
388     return pblocktemplate.release();
389 }
390
391 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
392 {
393     CPubKey pubkey;
394     if (!reservekey.GetReservedKey(pubkey))
395         return NULL;
396
397     CScript scriptPubKey = CScript() << pubkey << OP_CHECKSIG;
398     return CreateNewBlock(scriptPubKey);
399 }
400
401 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
402 {
403     // Update nExtraNonce
404     static uint256 hashPrevBlock;
405     if (hashPrevBlock != pblock->hashPrevBlock)
406     {
407         nExtraNonce = 0;
408         hashPrevBlock = pblock->hashPrevBlock;
409     }
410     ++nExtraNonce;
411     unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
412     pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
413     assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
414
415     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
416 }
417
418
419 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
420 {
421     //
422     // Pre-build hash buffers
423     //
424     struct
425     {
426         struct unnamed2
427         {
428             int nVersion;
429             uint256 hashPrevBlock;
430             uint256 hashMerkleRoot;
431             unsigned int nTime;
432             unsigned int nBits;
433             unsigned int nNonce;
434         }
435         block;
436         unsigned char pchPadding0[64];
437         uint256 hash1;
438         unsigned char pchPadding1[64];
439     }
440     tmp;
441     memset(&tmp, 0, sizeof(tmp));
442
443     tmp.block.nVersion       = pblock->nVersion;
444     tmp.block.hashPrevBlock  = pblock->hashPrevBlock;
445     tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
446     tmp.block.nTime          = pblock->nTime;
447     tmp.block.nBits          = pblock->nBits;
448     tmp.block.nNonce         = pblock->nNonce;
449
450     FormatHashBlocks(&tmp.block, sizeof(tmp.block));
451     FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
452
453     // Byte swap all the input buffer
454     for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
455         ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
456
457     // Precalc the first half of the first hash, which stays constant
458     SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
459
460     memcpy(pdata, &tmp.block, 128);
461     memcpy(phash1, &tmp.hash1, 64);
462 }
463
464
465 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
466 {
467     uint256 hash = pblock->GetHash();
468     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
469
470     if (hash > hashTarget)
471         return false;
472
473     //// debug print
474     LogPrintf("BitcoinMiner:\n");
475     LogPrintf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
476     pblock->print();
477     LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
478
479     // Found a solution
480     {
481         LOCK(cs_main);
482         if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
483             return error("BitcoinMiner : generated block is stale");
484
485         // Remove key from key pool
486         reservekey.KeepKey();
487
488         // Track how many getdata requests this block gets
489         {
490             LOCK(wallet.cs_wallet);
491             wallet.mapRequestCount[pblock->GetHash()] = 0;
492         }
493
494         // Process this block the same as if we had received it from another node
495         CValidationState state;
496         if (!ProcessBlock(state, NULL, pblock))
497             return error("BitcoinMiner : ProcessBlock, block not accepted");
498     }
499
500     return true;
501 }
502
503 void static BitcoinMiner(CWallet *pwallet)
504 {
505     LogPrintf("BitcoinMiner started\n");
506     SetThreadPriority(THREAD_PRIORITY_LOWEST);
507     RenameThread("bitcoin-miner");
508
509     // Each thread has its own key and counter
510     CReserveKey reservekey(pwallet);
511     unsigned int nExtraNonce = 0;
512
513     try { while (true) {
514         if (Params().NetworkID() != CChainParams::REGTEST) {
515             // Busy-wait for the network to come online so we don't waste time mining
516             // on an obsolete chain. In regtest mode we expect to fly solo.
517             while (vNodes.empty())
518                 MilliSleep(1000);
519         }
520
521         //
522         // Create new block
523         //
524         unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
525         CBlockIndex* pindexPrev = chainActive.Tip();
526
527         auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
528         if (!pblocktemplate.get())
529             return;
530         CBlock *pblock = &pblocktemplate->block;
531         IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
532
533         LogPrintf("Running BitcoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
534                ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
535
536         //
537         // Pre-build hash buffers
538         //
539         char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
540         char pdatabuf[128+16];    char* pdata     = alignup<16>(pdatabuf);
541         char phash1buf[64+16];    char* phash1    = alignup<16>(phash1buf);
542
543         FormatHashBuffers(pblock, pmidstate, pdata, phash1);
544
545         unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
546         unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
547         unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
548
549
550         //
551         // Search
552         //
553         int64 nStart = GetTime();
554         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
555         uint256 hashbuf[2];
556         uint256& hash = *alignup<16>(hashbuf);
557         while (true)
558         {
559             unsigned int nHashesDone = 0;
560             unsigned int nNonceFound;
561
562             // Crypto++ SHA256
563             nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
564                                             (char*)&hash, nHashesDone);
565
566             // Check if something found
567             if (nNonceFound != (unsigned int) -1)
568             {
569                 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
570                     ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
571
572                 if (hash <= hashTarget)
573                 {
574                     // Found a solution
575                     pblock->nNonce = ByteReverse(nNonceFound);
576                     assert(hash == pblock->GetHash());
577
578                     SetThreadPriority(THREAD_PRIORITY_NORMAL);
579                     CheckWork(pblock, *pwallet, reservekey);
580                     SetThreadPriority(THREAD_PRIORITY_LOWEST);
581
582                     // In regression test mode, stop mining after a block is found. This
583                     // allows developers to controllably generate a block on demand.
584                     if (Params().NetworkID() == CChainParams::REGTEST)
585                         throw boost::thread_interrupted();
586
587                     break;
588                 }
589             }
590
591             // Meter hashes/sec
592             static int64 nHashCounter;
593             if (nHPSTimerStart == 0)
594             {
595                 nHPSTimerStart = GetTimeMillis();
596                 nHashCounter = 0;
597             }
598             else
599                 nHashCounter += nHashesDone;
600             if (GetTimeMillis() - nHPSTimerStart > 4000)
601             {
602                 static CCriticalSection cs;
603                 {
604                     LOCK(cs);
605                     if (GetTimeMillis() - nHPSTimerStart > 4000)
606                     {
607                         dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
608                         nHPSTimerStart = GetTimeMillis();
609                         nHashCounter = 0;
610                         static int64 nLogTime;
611                         if (GetTime() - nLogTime > 30 * 60)
612                         {
613                             nLogTime = GetTime();
614                             LogPrintf("hashmeter %6.0f khash/s\n", dHashesPerSec/1000.0);
615                         }
616                     }
617                 }
618             }
619
620             // Check for stop or if block needs to be rebuilt
621             boost::this_thread::interruption_point();
622             if (vNodes.empty() && Params().NetworkID() != CChainParams::REGTEST)
623                 break;
624             if (nBlockNonce >= 0xffff0000)
625                 break;
626             if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
627                 break;
628             if (pindexPrev != chainActive.Tip())
629                 break;
630
631             // Update nTime every few seconds
632             UpdateTime(*pblock, pindexPrev);
633             nBlockTime = ByteReverse(pblock->nTime);
634             if (TestNet())
635             {
636                 // Changing pblock->nTime can change work required on testnet:
637                 nBlockBits = ByteReverse(pblock->nBits);
638                 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
639             }
640         }
641     } }
642     catch (boost::thread_interrupted)
643     {
644         LogPrintf("BitcoinMiner terminated\n");
645         throw;
646     }
647 }
648
649 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
650 {
651     static boost::thread_group* minerThreads = NULL;
652
653     int nThreads = GetArg("-genproclimit", -1);
654     if (nThreads < 0) {
655         if (Params().NetworkID() == CChainParams::REGTEST)
656             nThreads = 1;
657         else
658             nThreads = boost::thread::hardware_concurrency();
659     }
660
661     if (minerThreads != NULL)
662     {
663         minerThreads->interrupt_all();
664         delete minerThreads;
665         minerThreads = NULL;
666     }
667
668     if (nThreads == 0 || !fGenerate)
669         return;
670
671     minerThreads = new boost::thread_group();
672     for (int i = 0; i < nThreads; i++)
673         minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
674 }
675
676
677
This page took 0.06043 seconds and 4 git commands to generate.