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