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