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