BSHA3  0.17.99
P2P Blockchain, based on Bitcoin
miner.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 The Bitcoin Core developers
3 // Copyright (c) 2018 The Raven Core developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #include <miner.h>
8 
9 #include <amount.h>
10 #include <chain.h>
11 #include <chainparams.h>
12 #include <coins.h>
13 #include <consensus/consensus.h>
14 #include <consensus/tx_verify.h>
15 #include <consensus/merkle.h>
16 #include <consensus/validation.h>
17 #include <hash.h>
18 #include <net.h>
19 #include <policy/feerate.h>
20 #include <policy/policy.h>
21 #include <pow.h>
22 #include <primitives/transaction.h>
23 #include <script/standard.h>
24 #include <timedata.h>
25 #include <util.h>
26 #include <utilmoneystr.h>
27 #include <validationinterface.h>
28 #include <wallet/wallet.h>
29 
30 #include <algorithm>
31 #include <queue>
32 #include <utility>
33 
34 #include <boost/thread.hpp>
35 
36 // Unconfirmed transactions in the memory pool often depend on other
37 // transactions in the memory pool. When we select transactions from the
38 // pool, we select by highest fee rate of a transaction combined with all
39 // its ancestors.
40 
41 uint64_t nLastBlockTx = 0;
42 uint64_t nLastBlockWeight = 0;
43 uint64_t nMiningTimeStart = 0;
44 uint64_t nHashesDone = 0;
45 uint64_t nHashesPerSec = 0;
46 
47 int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
48 {
49  int64_t nOldTime = pblock->nTime;
50  int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
51 
52  if (nOldTime < nNewTime)
53  pblock->nTime = nNewTime;
54 
55  // Updating time can change work required on testnet:
56  if (consensusParams.fPowAllowMinDifficultyBlocks)
57  pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
58 
59  return nNewTime - nOldTime;
60 }
61 
63  blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
64  nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT;
65 }
66 
67 BlockAssembler::BlockAssembler(const CChainParams& params, const Options& options) : chainparams(params)
68 {
70  // Limit weight to between 4K and MAX_BLOCK_WEIGHT-4K for sanity:
71  nBlockMaxWeight = std::max<size_t>(4000, std::min<size_t>(MAX_BLOCK_WEIGHT - 4000, options.nBlockMaxWeight));
72 }
73 
74 static BlockAssembler::Options DefaultOptions()
75 {
76  // Block resource limits
77  // If -blockmaxweight is not given, limit to DEFAULT_BLOCK_MAX_WEIGHT
79  options.nBlockMaxWeight = gArgs.GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
80  if (gArgs.IsArgSet("-blockmintxfee")) {
81  CAmount n = 0;
82  ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n);
83  options.blockMinFeeRate = CFeeRate(n);
84  } else {
85  options.blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
86  }
87  return options;
88 }
89 
90 BlockAssembler::BlockAssembler(const CChainParams& params) : BlockAssembler(params, DefaultOptions()) {}
91 
93 {
94  inBlock.clear();
95 
96  // Reserve space for coinbase tx
97  nBlockWeight = 4000;
98  nBlockSigOpsCost = 400;
99  fIncludeWitness = false;
100 
101  // These counters do not include coinbase tx
102  nBlockTx = 0;
103  nFees = 0;
104 }
105 
106 std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn, bool fMineWitnessTx)
107 {
108  int64_t nTimeStart = GetTimeMicros();
109 
110  resetBlock();
111 
112  pblocktemplate.reset(new CBlockTemplate());
113 
114  if(!pblocktemplate.get())
115  return nullptr;
116  pblock = &pblocktemplate->block; // pointer for convenience
117 
118  // Add dummy coinbase tx as first transaction
119  pblock->vtx.emplace_back();
120  pblocktemplate->vTxFees.push_back(-1); // updated at end
121  pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end
122 
124  CBlockIndex* pindexPrev = chainActive.Tip();
125  assert(pindexPrev != nullptr);
126  nHeight = pindexPrev->nHeight + 1;
127 
129  // -regtest only: allow overriding block.nVersion with
130  // -blockversion=N to test forking scenarios
132  pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion);
133 
135  const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
136 
137  nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
138  ? nMedianTimePast
139  : pblock->GetBlockTime();
140 
141  // Decide whether to include witness transactions
142  // This is only needed in case the witness softfork activation is reverted
143  // (which would require a very deep reorganization).
144  // Note that the mempool would accept transactions with witness data before
145  // IsWitnessEnabled, but we would only ever mine blocks after IsWitnessEnabled
146  // unless there is a massive block reorganization with the witness softfork
147  // not activated.
148  // TODO: replace this with a call to main to assess validity of a mempool
149  // transaction (which in most cases can be a no-op).
150  fIncludeWitness = IsWitnessEnabled(pindexPrev, chainparams.GetConsensus()) && fMineWitnessTx;
151 
152  int nPackagesSelected = 0;
153  int nDescendantsUpdated = 0;
154  addPackageTxs(nPackagesSelected, nDescendantsUpdated);
155 
156  int64_t nTime1 = GetTimeMicros();
157 
160 
161  // Create coinbase transaction.
162  CMutableTransaction coinbaseTx;
163  coinbaseTx.vin.resize(1);
164  coinbaseTx.vin[0].prevout.SetNull();
165  coinbaseTx.vout.resize(1);
166  coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
167  coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
168  coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
169  pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
170  pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus());
171  pblocktemplate->vTxFees[0] = -nFees;
172 
173  LogPrintf("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
174 
175  // Fill in header
176  pblock->hashPrevBlock = pindexPrev->GetBlockHash();
177  UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
179  pblock->nNonce = 0;
180  pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]);
181 
182  CValidationState state;
183  if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
184  throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
185  }
186  int64_t nTime2 = GetTimeMicros();
187 
188  LogPrint(BCLog::BENCH, "CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n", 0.001 * (nTime1 - nTimeStart), nPackagesSelected, nDescendantsUpdated, 0.001 * (nTime2 - nTime1), 0.001 * (nTime2 - nTimeStart));
189 
190  return std::move(pblocktemplate);
191 }
192 
194 {
195  for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
196  // Only test txs not already in the block
197  if (inBlock.count(*iit)) {
198  testSet.erase(iit++);
199  }
200  else {
201  iit++;
202  }
203  }
204 }
205 
206 bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
207 {
208  // TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
209  if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= nBlockMaxWeight)
210  return false;
211  if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST)
212  return false;
213  return true;
214 }
215 
216 // Perform transaction-level checks before adding to block:
217 // - transaction finality (locktime)
218 // - premature witness (in case segwit transactions are added to mempool before
219 // segwit activation)
221 {
222  for (CTxMemPool::txiter it : package) {
223  if (!IsFinalTx(it->GetTx(), nHeight, nLockTimeCutoff))
224  return false;
225  if (!fIncludeWitness && it->GetTx().HasWitness())
226  return false;
227  }
228  return true;
229 }
230 
232 {
233  pblock->vtx.emplace_back(iter->GetSharedTx());
234  pblocktemplate->vTxFees.push_back(iter->GetFee());
235  pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
236  nBlockWeight += iter->GetTxWeight();
237  ++nBlockTx;
238  nBlockSigOpsCost += iter->GetSigOpCost();
239  nFees += iter->GetFee();
240  inBlock.insert(iter);
241 
242  bool fPrintPriority = gArgs.GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
243  if (fPrintPriority) {
244  LogPrintf("fee %s txid %s\n",
245  CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
246  iter->GetTx().GetHash().ToString());
247  }
248 }
249 
251  indexed_modified_transaction_set &mapModifiedTx)
252 {
253  int nDescendantsUpdated = 0;
254  for (CTxMemPool::txiter it : alreadyAdded) {
255  CTxMemPool::setEntries descendants;
256  mempool.CalculateDescendants(it, descendants);
257  // Insert all descendants (not yet in block) into the modified set
258  for (CTxMemPool::txiter desc : descendants) {
259  if (alreadyAdded.count(desc))
260  continue;
261  ++nDescendantsUpdated;
262  modtxiter mit = mapModifiedTx.find(desc);
263  if (mit == mapModifiedTx.end()) {
264  CTxMemPoolModifiedEntry modEntry(desc);
265  modEntry.nSizeWithAncestors -= it->GetTxSize();
266  modEntry.nModFeesWithAncestors -= it->GetModifiedFee();
267  modEntry.nSigOpCostWithAncestors -= it->GetSigOpCost();
268  mapModifiedTx.insert(modEntry);
269  } else {
270  mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
271  }
272  }
273  }
274  return nDescendantsUpdated;
275 }
276 
277 // Skip entries in mapTx that are already in a block or are present
278 // in mapModifiedTx (which implies that the mapTx ancestor state is
279 // stale due to ancestor inclusion in the block)
280 // Also skip transactions that we've already failed to add. This can happen if
281 // we consider a transaction in mapModifiedTx and it fails: we can then
282 // potentially consider it again while walking mapTx. It's currently
283 // guaranteed to fail again, but as a belt-and-suspenders check we put it in
284 // failedTx and avoid re-evaluation, since the re-evaluation would be using
285 // cached size/sigops/fee values that are not actually correct.
287 {
288  assert (it != mempool.mapTx.end());
289  return mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it);
290 }
291 
292 void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, std::vector<CTxMemPool::txiter>& sortedEntries)
293 {
294  // Sort package by ancestor count
295  // If a transaction A depends on transaction B, then A's ancestor count
296  // must be greater than B's. So this is sufficient to validly order the
297  // transactions for block inclusion.
298  sortedEntries.clear();
299  sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
300  std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
301 }
302 
303 // This transaction selection algorithm orders the mempool based
304 // on feerate of a transaction including all unconfirmed ancestors.
305 // Since we don't remove transactions from the mempool as we select them
306 // for block inclusion, we need an alternate method of updating the feerate
307 // of a transaction with its not-yet-selected ancestors as we go.
308 // This is accomplished by walking the in-mempool descendants of selected
309 // transactions and storing a temporary modified state in mapModifiedTxs.
310 // Each time through the loop, we compare the best transaction in
311 // mapModifiedTxs with the next transaction in the mempool to decide what
312 // transaction package to work on next.
313 void BlockAssembler::addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated)
314 {
315  // mapModifiedTx will store sorted packages after they are modified
316  // because some of their txs are already in the block
317  indexed_modified_transaction_set mapModifiedTx;
318  // Keep track of entries that failed inclusion, to avoid duplicate work
319  CTxMemPool::setEntries failedTx;
320 
321  // Start by adding all descendants of previously added txs to mapModifiedTx
322  // and modifying them for their already included ancestors
323  UpdatePackagesForAdded(inBlock, mapModifiedTx);
324 
325  CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin();
326  CTxMemPool::txiter iter;
327 
328  // Limit the number of attempts to add transactions to the block when it is
329  // close to full; this is just a simple heuristic to finish quickly if the
330  // mempool has a lot of entries.
331  const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
332  int64_t nConsecutiveFailed = 0;
333 
334  while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty())
335  {
336  // First try to find a new transaction in mapTx to evaluate.
337  if (mi != mempool.mapTx.get<ancestor_score>().end() &&
338  SkipMapTxEntry(mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) {
339  ++mi;
340  continue;
341  }
342 
343  // Now that mi is not stale, determine which transaction to evaluate:
344  // the next entry from mapTx, or the best from mapModifiedTx?
345  bool fUsingModified = false;
346 
347  modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
348  if (mi == mempool.mapTx.get<ancestor_score>().end()) {
349  // We're out of entries in mapTx; use the entry from mapModifiedTx
350  iter = modit->iter;
351  fUsingModified = true;
352  } else {
353  // Try to compare the mapTx entry to the mapModifiedTx entry
354  iter = mempool.mapTx.project<0>(mi);
355  if (modit != mapModifiedTx.get<ancestor_score>().end() &&
357  // The best entry in mapModifiedTx has higher score
358  // than the one from mapTx.
359  // Switch which transaction (package) to consider
360  iter = modit->iter;
361  fUsingModified = true;
362  } else {
363  // Either no entry in mapModifiedTx, or it's worse than mapTx.
364  // Increment mi for the next loop iteration.
365  ++mi;
366  }
367  }
368 
369  // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
370  // contain anything that is inBlock.
371  assert(!inBlock.count(iter));
372 
373  uint64_t packageSize = iter->GetSizeWithAncestors();
374  CAmount packageFees = iter->GetModFeesWithAncestors();
375  int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
376  if (fUsingModified) {
377  packageSize = modit->nSizeWithAncestors;
378  packageFees = modit->nModFeesWithAncestors;
379  packageSigOpsCost = modit->nSigOpCostWithAncestors;
380  }
381 
382  if (packageFees < blockMinFeeRate.GetFee(packageSize)) {
383  // Everything else we might consider has a lower fee rate
384  return;
385  }
386 
387  if (!TestPackage(packageSize, packageSigOpsCost)) {
388  if (fUsingModified) {
389  // Since we always look at the best entry in mapModifiedTx,
390  // we must erase failed entries so that we can consider the
391  // next best entry on the next loop iteration
392  mapModifiedTx.get<ancestor_score>().erase(modit);
393  failedTx.insert(iter);
394  }
395 
396  ++nConsecutiveFailed;
397 
398  if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight >
399  nBlockMaxWeight - 4000) {
400  // Give up if we're close to full and haven't succeeded in a while
401  break;
402  }
403  continue;
404  }
405 
406  CTxMemPool::setEntries ancestors;
407  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
408  std::string dummy;
409  mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
410 
411  onlyUnconfirmed(ancestors);
412  ancestors.insert(iter);
413 
414  // Test if all tx's are Final
415  if (!TestPackageTransactions(ancestors)) {
416  if (fUsingModified) {
417  mapModifiedTx.get<ancestor_score>().erase(modit);
418  failedTx.insert(iter);
419  }
420  continue;
421  }
422 
423  // This transaction will make it in; reset the failed counter.
424  nConsecutiveFailed = 0;
425 
426  // Package can be added. Sort the entries in a valid order.
427  std::vector<CTxMemPool::txiter> sortedEntries;
428  SortForBlock(ancestors, sortedEntries);
429 
430  for (size_t i=0; i<sortedEntries.size(); ++i) {
431  AddToBlock(sortedEntries[i]);
432  // Erase from the modified set, if present
433  mapModifiedTx.erase(sortedEntries[i]);
434  }
435 
436  ++nPackagesSelected;
437 
438  // Update transactions that depend on each of these
439  nDescendantsUpdated += UpdatePackagesForAdded(ancestors, mapModifiedTx);
440  }
441 }
442 
443 void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
444 {
445  // Update nExtraNonce
446  static uint256 hashPrevBlock;
447  if (hashPrevBlock != pblock->hashPrevBlock)
448  {
449  nExtraNonce = 0;
450  hashPrevBlock = pblock->hashPrevBlock;
451  }
452  ++nExtraNonce;
453  unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
454  CMutableTransaction txCoinbase(*pblock->vtx[0]);
455  txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
456  assert(txCoinbase.vin[0].scriptSig.size() <= 100);
457 
458  pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
459  pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
460 }
461 
462 static bool ProcessBlockFound(const CBlock* pblock, const CChainParams& chainparams)
463 {
464  LogPrintf("%s\n", pblock->ToString());
465  LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0]->vout[0].nValue));
466 
467  // Found a solution
468  {
469  LOCK(cs_main);
470  if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
471  return error("ProcessBlockFound -- generated block is stale");
472  }
473 
474  // Inform about the new block
475  GetMainSignals().BlockFound(pblock->GetHash());
476 
477  // Process this block the same as if we had received it from another node
478  //CValidationState state;
479  //std::shared_ptr<CBlock> shared_pblock = std::make_shared<CBlock>(pblock);
480  std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock);
481  if (!ProcessNewBlock(chainparams, shared_pblock, true, nullptr))
482  return error("ProcessBlockFound -- ProcessNewBlock() failed, block not accepted");
483 
484  return true;
485 }
486 
488  LOCK(cs_wallets);
489  while (vpwallets.size() == 0) {
490  MilliSleep(100);
491  }
492  if (vpwallets.size() == 0)
493  return nullptr;
494  return vpwallets[0].get();
495 }
496 
497 void static BSHA3Miner(const CChainParams& chainparams)
498 {
499  LogPrintf("BSHA3 Miner -- started\n");
501  RenameThread("bsha3-miner");
502 
503  unsigned int nExtraNonce = 0;
504 
505 
506  CWallet* pWallet = GetFirstWallet();
507 
508  if (!EnsureWalletIsAvailable(pWallet, false)) {
509  LogPrintf("BSHA3 Miner -- Wallet not available\n");
510  }
511 
512  if (pWallet == nullptr)
513  LogPrintf("pWallet is null\n");
514 
515 
516  std::shared_ptr<CReserveScript> coinbaseScript;
517 
518  pWallet->GetScriptForMining(coinbaseScript);
519 
520  // GetMainSignals().ScriptForMining(coinbaseScript);
521 
522  if (!coinbaseScript)
523  LogPrintf("coinbaseScript is null\n");
524 
525  if (coinbaseScript->reserveScript.empty())
526  LogPrintf("coinbaseScript is empty\n");
527 
528  try {
529  // Throw an error if no script was provided. This can happen
530  // due to some internal error but also if the keypool is empty.
531  // In the latter case, already the pointer is null.
532  if (!coinbaseScript || coinbaseScript->reserveScript.empty())
533  {
534  throw std::runtime_error("No coinbase script available (mining requires a wallet)");
535  }
536 
537 
538  while (true) {
539 
540  if (chainparams.MiningRequiresPeers()) {
541  // Busy-wait for the network to come online so we don't waste time mining
542  // on an obsolete chain. In regtest mode we expect to fly solo.
543  do {
544  if ((g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL) > 0) && !IsInitialBlockDownload()) {
545  break;
546  }
547 
548  MilliSleep(1000);
549  } while (true);
550  }
551 
552 
553  //
554  // Create new block
555  //
556  unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
557  CBlockIndex* pindexPrev = chainActive.Tip();
558  if(!pindexPrev) break;
559 
560 
561 
562  std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(Params()).CreateNewBlock(coinbaseScript->reserveScript));
563 
564  if (!pblocktemplate.get())
565  {
566  LogPrintf("BSHA3 Miner -- Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
567  return;
568  }
569  CBlock *pblock = &pblocktemplate->block;
570  IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
571 
572  LogPrintf("BSHA3 Miner -- Running miner with %u transactions in block (%u bytes)\n", pblock->vtx.size(),
573  ::GetSerializeSize(*pblock, PROTOCOL_VERSION));
574 
575  //
576  // Search
577  //
578  int64_t nStart = GetTime();
579  arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
580  while (true)
581  {
582 
583  uint256 hash;
584  while (true)
585  {
586  hash = pblock->GetHash();
587  if (UintToArith256(hash) <= hashTarget)
588  {
589  // Found a solution
591  LogPrintf("BSHA3 Miner:\n proof-of-work found\n hash: %s\n target: %s\n", hash.GetHex(), hashTarget.GetHex());
592  ProcessBlockFound(pblock, chainparams);
594  coinbaseScript->KeepScript();
595 
596  // In regression test mode, stop mining after a block is found. This
597  // allows developers to controllably generate a block on demand.
598  if (chainparams.MineBlocksOnDemand())
599  throw boost::thread_interrupted();
600 
601  break;
602  }
603  pblock->nNonce += 1;
604  nHashesDone += 1;
605  if (nHashesDone % 500000 == 0) { //Calculate hashing speed
606  nHashesPerSec = nHashesDone / (((GetTimeMicros() - nMiningTimeStart) / 1000000) + 1);
607  }
608  if ((pblock->nNonce & 0xFF) == 0)
609  break;
610  }
611 
612  // Check for stop or if block needs to be rebuilt
613  boost::this_thread::interruption_point();
614  // Regtest mode doesn't require peers
615  // if (vNodes.empty() && chainparams.MiningRequiresPeers())
616  // break;
617  if (pblock->nNonce >= 0xffff0000)
618  break;
619  if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
620  break;
621  if (pindexPrev != chainActive.Tip())
622  break;
623 
624  // Update nTime every few seconds
625  if (UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev) < 0)
626  break; // Recreate the block if the clock has run backwards,
627  // so that we can use the correct time.
628  if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
629  {
630  // Changing pblock->nTime can change work required on testnet:
631  hashTarget.SetCompact(pblock->nBits);
632  }
633  }
634  }
635  }
636  catch (const boost::thread_interrupted&)
637  {
638  LogPrintf("BSHA3 Miner -- terminated\n");
639  throw;
640  }
641  catch (const std::runtime_error &e)
642  {
643  LogPrintf("BSHA3 Miner -- runtime error: %s\n", e.what());
644  return;
645  }
646 }
647 
648 int GenerateBSHA3s(bool fGenerate, int nThreads, const CChainParams& chainparams)
649 {
650 
651  static boost::thread_group* minerThreads = nullptr;
652 
653  int numCores = GetNumCores();
654  if (nThreads < 0)
655  nThreads = numCores;
656 
657  if (minerThreads != nullptr)
658  {
659  minerThreads->interrupt_all();
660  delete minerThreads;
661  minerThreads = nullptr;
662  }
663 
664  if (nThreads == 0 || !fGenerate)
665  return numCores;
666 
667  minerThreads = new boost::thread_group();
668 
669  // Reset metrics
671  nHashesDone = 0;
672  nHashesPerSec = 0;
673 
674  for (int i = 0; i < nThreads; i++){
675  minerThreads->create_thread(boost::bind(&BSHA3Miner, boost::cref(chainparams)));
676  }
677 
678  return numCores;
679 }
uint32_t nNonce
Definition: block.h:29
indexed_modified_transaction_set::nth_index< 0 >::type::iterator modtxiter
Definition: miner.h:109
bool TestPackageTransactions(const CTxMemPool::setEntries &package)
Perform checks on each transaction in a package: locktime, premature-witness, serialized size (if nec...
Definition: miner.cpp:220
CTxMemPool mempool
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: util.cpp:502
CFeeRate blockMinFeeRate
Definition: miner.h:156
Definition: miner.h:39
unsigned int nBlockMaxWeight
Definition: miner.h:137
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
void SetThreadPriority(int nPriority)
Definition: util.cpp:1260
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:490
void MilliSleep(int64_t n)
Definition: utiltime.cpp:61
void AddToBlock(CTxMemPool::txiter iter)
Add a tx to the block.
Definition: miner.cpp:231
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:47
Definition: block.h:74
uint64_t nBlockTx
Definition: miner.h:142
#define strprintf
Definition: tinyformat.h:1066
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:437
bool EnsureWalletIsAvailable(CWallet *const pwallet, bool avoidException)
Definition: rpcwallet.cpp:73
std::vector< CTxIn > vin
Definition: transaction.h:362
void onlyUnconfirmed(CTxMemPool::setEntries &testSet)
Remove confirmed (inBlock) entries from given set.
Definition: miner.cpp:193
std::string ToString() const
Definition: block.cpp:18
int64_t nLockTimeCutoff
Definition: miner.h:149
CTxMemPool::setEntries inBlock
Definition: miner.h:145
std::unique_ptr< CBlockTemplate > pblocktemplate
Definition: miner.h:131
void BlockFound(const uint256 &)
bool fPowAllowMinDifficultyBlocks
Definition: params.h:58
CBlock * pblock
Definition: miner.h:133
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:498
CWallet * GetFirstWallet()
Definition: miner.cpp:487
int64_t GetTimeMicros()
Definition: utiltime.cpp:48
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:47
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: util.cpp:542
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Determine what nVersion a new block should use.
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > pblock, bool fForceProcessing, bool *fNewBlock)
Process an incoming block.
void RenameThread(const char *name)
Definition: util.cpp:1168
uint32_t nTime
Definition: block.h:27
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:981
arith_uint256 UintToArith256(const uint256 &a)
uint64_t nLastBlockWeight
Definition: miner.cpp:42
uint64_t nMiningTimeStart
Definition: miner.cpp:43
indexed_modified_transaction_set::index< ancestor_score >::type::iterator modtxscoreiter
Definition: miner.h:110
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
uint256 GetBlockHash() const
Definition: chain.h:292
uint64_t nHashesPerSec
Definition: miner.cpp:45
#define THREAD_PRIORITY_NORMAL
Definition: compat.h:84
#define LOCK2(cs1, cs2)
Definition: sync.h:182
uint64_t nHashesDone
Definition: miner.cpp:44
CCriticalSection cs_main
Definition: validation.cpp:216
#define THREAD_PRIORITY_LOWEST
Definition: compat.h:82
bool MineBlocksOnDemand() const
Make miner stop after a block is found.
Definition: chainparams.h:72
Definition: txmempool.h:277
uint256 hashMerkleRoot
Definition: block.h:26
const CChainParams & chainparams
Definition: miner.h:150
#define LOCK(cs)
Definition: sync.h:181
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock, const Consensus::Params &params)
Definition: pow.cpp:14
uint64_t nLastBlockTx
Definition: miner.cpp:41
boost::multi_index_container< CTxMemPoolModifiedEntry, boost::multi_index::indexed_by< boost::multi_index::ordered_unique< modifiedentry_iter, CompareCTxMemPoolIter >, boost::multi_index::ordered_non_unique< boost::multi_index::tag< ancestor_score >, boost::multi_index::identity< CTxMemPoolModifiedEntry >, CompareTxMemPoolEntryByAncestorFee > >> indexed_modified_transaction_set
Definition: miner.h:107
CAmount nFees
Definition: miner.h:144
uint256 hashPrevBlock
Definition: block.h:25
bool MiningRequiresPeers() const
Definition: chainparams.h:64
size_t nBlockMaxWeight
Definition: miner.h:155
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
BlockAssembler(const CChainParams &params)
Definition: miner.cpp:90
CMainSignals & GetMainSignals()
Generate a new block, without valid proof-of-work.
Definition: miner.h:127
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:66
bool ParseMoney(const std::string &str, CAmount &nRet)
void SortForBlock(const CTxMemPool::setEntries &package, std::vector< CTxMemPool::txiter > &sortedEntries)
Sort the package in an order that is valid to appear in a block.
Definition: miner.cpp:292
Parameters that influence chain consensus.
Definition: params.h:40
bool CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents=true) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Try to calculate all in-mempool ancestors of entry.
Definition: txmempool.cpp:149
CScript COINBASE_FLAGS
Constant stuff for coinbase transactions we create:
Definition: validation.cpp:249
int64_t GetBlockTime() const
Definition: block.h:67
std::vector< CTxOut > vout
Definition: transaction.h:363
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
256-bit unsigned big integer.
int64_t GetMedianTimePast() const
Definition: chain.h:309
void addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs)
Add transactions based on feerate including unconfirmed ancestors Increments nPackagesSelected / nDes...
Definition: miner.cpp:313
CCriticalSection cs
Definition: txmempool.h:487
uint64_t nSizeWithAncestors
Definition: miner.h:55
void IncrementExtraNonce(CBlock *pblock, const CBlockIndex *pindexPrev, unsigned int &nExtraNonce)
Modify the extranonce in a block.
Definition: miner.cpp:443
uint256 GetHash() const
Definition: block.cpp:13
uint64_t nBlockSigOpsCost
Definition: miner.h:143
Capture information about block/transaction validation.
Definition: validation.h:26
256-bit opaque blob.
Definition: uint256.h:122
CAmount nModFeesWithAncestors
Definition: miner.h:56
ArgsManager gArgs
Definition: util.cpp:88
void GetScriptForMining(std::shared_ptr< CReserveScript > &script)
Definition: wallet.cpp:3595
std::vector< CTransactionRef > vtx
Definition: block.h:78
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
Definition: validation.cpp:453
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Auxiliary functions for transaction validation (ideally should not be exposed)
Definition: tx_verify.cpp:107
CFeeRate blockMinFeeRate
Definition: miner.h:138
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:170
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:384
std::vector< unsigned char > GenerateCoinbaseCommitment(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Produce the necessary coinbase commitment for a block (modifies the hash, don&#39;t call for mined blocks...
int nHeight
Definition: miner.h:148
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: util.cpp:526
int64_t GetAdjustedTime()
Definition: timedata.cpp:35
bool TestBlockValidity(CValidationState &state, const CChainParams &chainparams, const CBlock &block, CBlockIndex *pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
Check a block is completely valid from start to finish (only works on top of our current best block) ...
bool SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs)
Return true if given transaction from mapTx has already been evaluated, or if the transaction&#39;s cache...
Definition: miner.cpp:286
CCriticalSection cs_wallets
Definition: wallet.cpp:40
int64_t nSigOpCostWithAncestors
Definition: miner.h:57
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:445
uint64_t nBlockWeight
Definition: miner.h:141
std::string GetHex() const
Definition: uint256.cpp:21
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
Definition: wallet.h:599
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:19
bool fIncludeWitness
Definition: miner.h:136
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:74
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:343
bool error(const char *fmt, const Args &... args)
Definition: util.h:59
arith_uint256 & SetCompact(uint32_t nCompact, bool *pfNegative=nullptr, bool *pfOverflow=nullptr)
The "compact" format is a representation of a whole number N using an unsigned 32bit number similar t...
bool IsWitnessEnabled(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Check whether witness commitments are required for block.
void resetBlock()
Clear the block&#39;s state and prepare for assembling a new block.
Definition: miner.cpp:92
A mutable version of CTransaction.
Definition: transaction.h:360
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:798
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
Check if transaction is final and can be included in a block with the specified height and time...
Definition: tx_verify.cpp:17
std::string GetHex() const
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units...
Definition: utiltime.cpp:20
std::string ToString() const
Definition: feerate.cpp:40
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:183
int GetNumCores()
Return the number of cores available on the current system.
Definition: util.cpp:1233
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:60
int GenerateBSHA3s(bool fGenerate, int nThreads, const CChainParams &chainparams)
Definition: miner.cpp:648
CChain & chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:219
int UpdatePackagesForAdded(const CTxMemPool::setEntries &alreadyAdded, indexed_modified_transaction_set &mapModifiedTx) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs)
Add descendants of given transactions to mapModifiedTx with ancestor state updated assuming given tra...
Definition: miner.cpp:250
Definition: script.h:51
bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
Test if a new package would "fit" in the block.
Definition: miner.cpp:206
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn, bool fMineWitnessTx=true)
Construct a new block template with coinbase to scriptPubKeyIn.
Definition: miner.cpp:106
int32_t nVersion
Definition: block.h:24
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:20
uint32_t nBits
Definition: block.h:28
CAmount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
Definition: feerate.cpp:23