Fabcoin Core  0.16.2
P2P Digital Currency
miner.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2017 The Bitcoin Core developers
3 // Distributed under the MIT 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 <amount.h>
9 #include <chain.h>
10 #include <chainparams.h>
11 #include <coins.h>
12 #include <./wallet/wallet.h>
13 #include <consensus/consensus.h>
14 #include <consensus/tx_verify.h>
15 #include <consensus/merkle.h>
16 #include <consensus/validation.h>
17 #include <crypto/equihash.h>
18 #include <hash.h>
19 #include <validation.h>
20 #include <net.h>
21 #include <policy/feerate.h>
22 #include <policy/policy.h>
23 #include <pow.h>
24 #include <primitives/transaction.h>
25 #include <script/standard.h>
26 #include <timedata.h>
27 #include <txmempool.h>
28 #include <util.h>
29 #include <utilmoneystr.h>
30 #include <validationinterface.h>
31 
32 #ifdef USE_CUDA
33 #include <cuda/eqcuda.hpp>
34 #endif
35 
36 #include <algorithm>
37 #include <queue>
38 #include <utility>
39 
40 #ifdef ENABLE_GPU
41 #include <libgpusolver/libgpusolver.h>
42 #endif
43 
44 #include <boost/thread.hpp>
45 #include <boost/tuple/tuple.hpp>
46 
47 std::mutex g_cs;
48 bool g_cancelSolver = false;
49 int g_nSols[128] = {0};
50 
52 //
53 // FabcoinMiner
54 //
55 
56 //
57 // Unconfirmed transactions in the memory pool often depend on other
58 // transactions in the memory pool. When we select transactions from the
59 // pool, we select by highest fee rate of a transaction combined with all
60 // its ancestors.
61 
62 uint64_t nLastBlockTx = 0;
63 uint64_t nLastBlockWeight = 0;
64 
65 int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
66 {
67  int64_t nOldTime = pblock->nTime;
68  int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
69 
70  if (nOldTime < nNewTime)
71  pblock->nTime = nNewTime;
72 
73  // Updating time can change work required on testnet:
74  if (consensusParams.fPowAllowMinDifficultyBlocks)
75  pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
76 
77  return nNewTime - nOldTime;
78 }
79 
80 bool IsBlockTooLate(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
81 {
82  if( GetAdjustedTime() > std::max(pblock->GetBlockTime(), pindexPrev->GetBlockTime()) + Params().GetnPowTargetSpacing(pindexPrev->nHeight+1) * consensusParams.MaxBlockInterval )
83  {
84  return true;
85  }
86  return false;
87 }
88 
90  blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
91  nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT;
92 }
93 
94 BlockAssembler::BlockAssembler(const CChainParams& params, const Options& options) : chainparams(params)
95 {
97  // Limit weight to between 4K and dgpMaxBlockWeight-4K for sanity:
98  //??? // Limit weight to between 4K and MAX_BLOCK_WEIGHT-4K for sanity:
99  nBlockMaxWeight = std::max<size_t>(4000, std::min<size_t>(dgpMaxBlockWeight - 4000, options.nBlockMaxWeight));
100  //??? nBlockMaxWeight = std::max<size_t>(4000, std::min<size_t>(MAX_BLOCK_WEIGHT - 4000, options.nBlockMaxWeight));
101 }
102 
103 static BlockAssembler::Options DefaultOptions(const CChainParams& params)
104 {
105  // Block resource limits
106  // If neither -blockmaxsize or -blockmaxweight is given, limit to DEFAULT_BLOCK_MAX_*
107  // If only one is given, only restrict the specified resource.
108  // If both are given, restrict both.
109  BlockAssembler::Options options;
110  options.nBlockMaxWeight = gArgs.GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
111  if (gArgs.IsArgSet("-blockmintxfee")) {
112  CAmount n = 0;
113  ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n);
114  options.blockMinFeeRate = CFeeRate(n);
115  } else {
116  options.blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
117  }
118  return options;
119 }
120 
121 BlockAssembler::BlockAssembler(const CChainParams& params) : BlockAssembler(params, DefaultOptions(params)) {}
122 
124 {
125  inBlock.clear();
126 
127  // Reserve space for coinbase tx
128  nBlockWeight = 4000;
129  nBlockSigOpsCost = 400;
130  fIncludeWitness = false;
131 
132  // These counters do not include coinbase tx
133  nBlockTx = 0;
134  nFees = 0;
135 }
136 
138  int refundtx=0; //0 for coinbase in PoW
139 
141  contrTx.vout[refundtx].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
142  contrTx.vout[refundtx].nValue -= bceResult.refundSender;
143  //note, this will need changed for MPoS
144  int i=contrTx.vout.size();
145  contrTx.vout.resize(contrTx.vout.size()+bceResult.refundOutputs.size());
146  for(CTxOut& vout : bceResult.refundOutputs){
147  contrTx.vout[i]=vout;
148  i++;
149  }
150  pblock->vtx[refundtx] = MakeTransactionRef(std::move(contrTx));
151 }
152 
153 std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn, bool fMineWitnessTx, int64_t* pTotalFees, int32_t txProofTime, int32_t nTimeLimit)
154 {
155  int64_t nTimeStart = GetTimeMicros();
156 
157  resetBlock();
158 
159  pblocktemplate.reset(new CBlockTemplate());
160 
161  if(!pblocktemplate.get())
162  return nullptr;
163  pblock = &pblocktemplate->block; // pointer for convenience
164 
165  this->nTimeLimit = nTimeLimit;
166 
167  // Add dummy coinbase tx as first transaction
168  pblock->vtx.emplace_back();
169  pblocktemplate->vTxFees.push_back(-1); // updated at end
170  pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end
171 
173  CBlockIndex* pindexPrev = chainActive.Tip();
174  nHeight = pindexPrev->nHeight + 1;
175 
177  // -regtest only: allow overriding block.nVersion with
178  // -blockversion=N to test forking scenarios
180  pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion);
181 
182  if ( txProofTime == 0 ) {
183  txProofTime = GetAdjustedTime();
184  }
185  pblock->nTime = txProofTime;
186  UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
188 
189  const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
190 
191  nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
192  ? nMedianTimePast
193  : pblock->GetBlockTime();
194 
195  // Decide whether to include witness transactions
196  // This is only needed in case the witness softfork activation is reverted
197  // (which would require a very deep reorganization) or when
198  // -promiscuousmempoolflags is used.
199  // TODO: replace this with a call to main to assess validity of a mempool
200  // transaction (which in most cases can be a no-op).
201  fIncludeWitness = IsWitnessEnabled(pindexPrev, chainparams.GetConsensus()) && fMineWitnessTx;
202 
203  int64_t nTime1 = GetTimeMicros();
204 
207 
208  // Create coinbase transaction.
209  CMutableTransaction coinbaseTx;
210  coinbaseTx.vin.resize(1);
211  coinbaseTx.vin[0].prevout.SetNull();
212  coinbaseTx.vout.resize(1);
213 
214  coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
215  coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
216  coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
217  originalRewardTx = coinbaseTx;
218  pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
219 
220 
221 
223  FascDGP fascDGP(globalState.get(), fGettingValuesDGP);
224  globalSealEngine->setFascSchedule(fascDGP.getGasSchedule(nHeight));
225  uint32_t blockSizeDGP = fascDGP.getBlockSize(nHeight);
226  minGasPrice = fascDGP.getMinGasPrice(nHeight);
227  if(gArgs.IsArgSet("-staker-min-tx-gas-price")) {
228  CAmount stakerMinGasPrice;
229  if(ParseMoney(gArgs.GetArg("-staker-min-tx-gas-price", ""), stakerMinGasPrice)) {
230  minGasPrice = std::max(minGasPrice, (uint64_t)stakerMinGasPrice);
231  }
232  }
233  hardBlockGasLimit = fascDGP.getBlockGasLimit(nHeight);
234  softBlockGasLimit = gArgs.GetArg("-staker-soft-block-gas-limit", hardBlockGasLimit);
236  txGasLimit = gArgs.GetArg("-staker-max-tx-gas-limit", softBlockGasLimit);
237 
238  nBlockMaxWeight = blockSizeDGP ? blockSizeDGP * WITNESS_SCALE_FACTOR : nBlockMaxWeight;
239 
240  dev::h256 oldHashStateRoot(globalState->rootHash());
241  dev::h256 oldHashUTXORoot(globalState->rootHashUTXO());
242  int nPackagesSelected = 0;
243  int nDescendantsUpdated = 0;
244  addPackageTxs(nPackagesSelected, nDescendantsUpdated, minGasPrice);
247  globalState->setRoot(oldHashStateRoot);
248  globalState->setRootUTXO(oldHashUTXORoot);
249 
250  //this should already be populated by AddBlock in case of contracts, but if no contracts
251  //then it won't get populated
254 
255  pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus());
256  pblocktemplate->vTxFees[0] = -nFees;
257 
259  uint64_t nSerializeSize = GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION );
260  LogPrintf("CreateNewBlock(): nHeight=%d total size: %u block weight: %u txs: %u fees: %ld sigops %d\n",
261  nHeight, nSerializeSize, GetBlockWeight(*pblock, chainparams.GetConsensus()), nBlockTx, nFees, nBlockSigOpsCost);
262 
263  // The total fee is the Fees minus the Refund
264  if (pTotalFees)
265  *pTotalFees = nFees - bceResult.refundSender;
266 
267  // Fill in header
268  pblock->hashPrevBlock = pindexPrev->GetBlockHash();
269  pblock->nHeight = pindexPrev->nHeight + 1;
270  memset(pblock->nReserved, 0, sizeof(pblock->nReserved));
272 
273  arith_uint256 nonce;
274  if ((uint32_t)nHeight >= (uint32_t)chainparams.GetConsensus().FABHeight) {
275  // Randomise nonce for new block foramt.
276  nonce = UintToArith256(GetRandHash());
277  // Clear the top and bottom 16 bits (for local use as thread flags and counters)
278  nonce >>= 32; //128;
279  nonce <<= 32;
280  }
281 
282  pblock->nNonce = ArithToUint256(nonce);
283  pblock->nSolution.clear();
284  pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]);
285 
286  CValidationState state;
287  if ( !TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
288  throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
289  }
290  int64_t nTime2 = GetTimeMicros();
291 
292  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));
293 
294  return std::move(pblocktemplate);
295 }
296 
297 
298 
300 {
301  for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
302  // Only test txs not already in the block
303  if (inBlock.count(*iit)) {
304  testSet.erase(iit++);
305  }
306  else {
307  iit++;
308  }
309  }
310 }
311 
312 bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost)
313 {
314  // TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
315  if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= nBlockMaxWeight)
316  return false;
317  if (nBlockSigOpsCost + packageSigOpsCost >= (uint64_t)dgpMaxBlockSigOps)
318  return false;
319  return true;
320 }
321 
322 // Perform transaction-level checks before adding to block:
323 // - transaction finality (locktime)
324 // - premature witness (in case segwit transactions are added to mempool before
325 // segwit activation)
327 {
328  for (const CTxMemPool::txiter it : package) {
329  if (!IsFinalTx(it->GetTx(), nHeight, nLockTimeCutoff))
330  return false;
331  if (!fIncludeWitness && it->GetTx().HasWitness())
332  return false;
333  }
334  return true;
335 }
336 
338  if (nTimeLimit != 0 && GetAdjustedTime() >= nTimeLimit - BYTECODE_TIME_BUFFER) {
339  return false;
340  }
341  if (gArgs.GetBoolArg("-disablecontractstaking", false))
342  {
343  return false;
344  }
345 
346  dev::h256 oldHashStateRoot(globalState->rootHash());
347  dev::h256 oldHashUTXORoot(globalState->rootHashUTXO());
348  // operate on local vars first, then later apply to `this`
349  uint64_t nBlockWeight = this->nBlockWeight;
350  uint64_t nBlockSigOpsCost = this->nBlockSigOpsCost;
351 
352  FascTxConverter convert(iter->GetTx(), NULL, &pblock->vtx);
353 
354  ExtractFascTX resultConverter;
355  if(!convert.extractionFascTransactions(resultConverter)){
356  //this check already happens when accepting txs into mempool
357  //therefore, this can only be triggered by using raw transactions on the staker itself
358  return false;
359  }
360  std::vector<FascTransaction> fascTransactions = resultConverter.first;
361  dev::u256 txGas = 0;
362  for(FascTransaction fascTransaction : fascTransactions){
363  txGas += fascTransaction.gas();
364  if(txGas > txGasLimit) {
365  // Limit the tx gas limit by the soft limit if such a limit has been specified.
366  return false;
367  }
368 
369  if(bceResult.usedGas + fascTransaction.gas() > softBlockGasLimit){
370  //if this transaction's gasLimit could cause block gas limit to be exceeded, then don't add it
371  return false;
372  }
373  if(fascTransaction.gasPrice() < minGasPrice){
374  //if this transaction's gasPrice is less than the current DGP minGasPrice don't add it
375  return false;
376  }
377  }
378  // We need to pass the DGP's block gas limit (not the soft limit) since it is consensus critical.
379  ByteCodeExec exec(*pblock, fascTransactions, hardBlockGasLimit);
380  if(!exec.performByteCode()){
381  //error, don't add contract
382  globalState->setRoot(oldHashStateRoot);
383  globalState->setRootUTXO(oldHashUTXORoot);
384  return false;
385  }
386 
387  ByteCodeExecResult testExecResult;
388  if(!exec.processingResults(testExecResult)){
389  globalState->setRoot(oldHashStateRoot);
390  globalState->setRootUTXO(oldHashUTXORoot);
391  return false;
392  }
393 
394  if(bceResult.usedGas + testExecResult.usedGas > softBlockGasLimit){
395  //if this transaction could cause block gas limit to be exceeded, then don't add it
396  globalState->setRoot(oldHashStateRoot);
397  globalState->setRootUTXO(oldHashUTXORoot);
398  return false;
399  }
400 
401  //apply contractTx costs to local state
402  nBlockWeight += iter->GetTxWeight();
403  nBlockSigOpsCost += iter->GetSigOpCost();
404  //apply value-transfer txs to local state
405  for (CTransaction &t : testExecResult.valueTransfers) {
406  nBlockWeight += GetTransactionWeight(t);
407  nBlockSigOpsCost += GetLegacySigOpCount(t);
408  }
409 
410  int proofTx = 0;
411 
412  //calculate sigops from new refund/proof tx
413 
414  //first, subtract old proof tx
415  nBlockSigOpsCost -= GetLegacySigOpCount(*pblock->vtx[proofTx]);
416 
417  // manually rebuild refundtx
418  CMutableTransaction contrTx(*pblock->vtx[proofTx]);
419  //note, this will need changed for MPoS
420  int i=contrTx.vout.size();
421  contrTx.vout.resize(contrTx.vout.size()+testExecResult.refundOutputs.size());
422  for(CTxOut& vout : testExecResult.refundOutputs){
423  contrTx.vout[i]=vout;
424  i++;
425  }
426  nBlockSigOpsCost += GetLegacySigOpCount(contrTx);
427  //all contract costs now applied to local state
428 
429  //Check if block will be too big or too expensive with this contract execution
430  if (nBlockSigOpsCost * WITNESS_SCALE_FACTOR > (uint64_t)dgpMaxBlockSigOps ||
431  nBlockWeight > dgpMaxBlockWeight) {
432  //contract will not be added to block, so revert state to before we tried
433  globalState->setRoot(oldHashStateRoot);
434  globalState->setRootUTXO(oldHashUTXORoot);
435  return false;
436  }
437 
438  //block is not too big, so apply the contract execution and it's results to the actual block
439 
440  //apply local bytecode to global bytecode state
441  bceResult.usedGas += testExecResult.usedGas;
442  bceResult.refundSender += testExecResult.refundSender;
443  bceResult.refundOutputs.insert(bceResult.refundOutputs.end(), testExecResult.refundOutputs.begin(), testExecResult.refundOutputs.end());
444  bceResult.valueTransfers = std::move(testExecResult.valueTransfers);
445 
446  pblock->vtx.emplace_back(iter->GetSharedTx());
447  pblocktemplate->vTxFees.push_back(iter->GetFee());
448  pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
449  this->nBlockWeight += iter->GetTxWeight();
450  ++nBlockTx;
451  this->nBlockSigOpsCost += iter->GetSigOpCost();
452  nFees += iter->GetFee();
453  inBlock.insert(iter);
454 
456  pblock->vtx.emplace_back(MakeTransactionRef(std::move(t)));
457  this->nBlockWeight += GetTransactionWeight(t);
458  this->nBlockSigOpsCost += GetLegacySigOpCount(t);
459  ++nBlockTx;
460  }
461  //calculate sigops from new refund/proof tx
462  this->nBlockSigOpsCost -= GetLegacySigOpCount(*pblock->vtx[proofTx]);
464  this->nBlockSigOpsCost += GetLegacySigOpCount(*pblock->vtx[proofTx]);
465 
466  bceResult.valueTransfers.clear();
467 
468  return true;
469 }
470 
471 
473 {
474  pblock->vtx.emplace_back(iter->GetSharedTx());
475  pblocktemplate->vTxFees.push_back(iter->GetFee());
476  pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
477  nBlockWeight += iter->GetTxWeight();
478  ++nBlockTx;
479  nBlockSigOpsCost += iter->GetSigOpCost();
480  nFees += iter->GetFee();
481  inBlock.insert(iter);
482 
483  bool fPrintPriority = gArgs.GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
484  if (fPrintPriority) {
485  LogPrintf("fee %s txid %s\n",
486  CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
487  iter->GetTx().GetHash().ToString());
488  }
489 }
490 
492  indexed_modified_transaction_set &mapModifiedTx)
493 {
494  int nDescendantsUpdated = 0;
495  for (const CTxMemPool::txiter it : alreadyAdded) {
496  CTxMemPool::setEntries descendants;
497  mempool.CalculateDescendants(it, descendants);
498  // Insert all descendants (not yet in block) into the modified set
499  for (CTxMemPool::txiter desc : descendants) {
500  if (alreadyAdded.count(desc))
501  continue;
502  ++nDescendantsUpdated;
503  modtxiter mit = mapModifiedTx.find(desc);
504  if (mit == mapModifiedTx.end()) {
505  CTxMemPoolModifiedEntry modEntry(desc);
506  modEntry.nSizeWithAncestors -= it->GetTxSize();
507  modEntry.nModFeesWithAncestors -= it->GetModifiedFee();
508  modEntry.nSigOpCostWithAncestors -= it->GetSigOpCost();
509  mapModifiedTx.insert(modEntry);
510  } else {
511  mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
512  }
513  }
514  }
515  return nDescendantsUpdated;
516 }
517 
518 // Skip entries in mapTx that are already in a block or are present
519 // in mapModifiedTx (which implies that the mapTx ancestor state is
520 // stale due to ancestor inclusion in the block)
521 // Also skip transactions that we've already failed to add. This can happen if
522 // we consider a transaction in mapModifiedTx and it fails: we can then
523 // potentially consider it again while walking mapTx. It's currently
524 // guaranteed to fail again, but as a belt-and-suspenders check we put it in
525 // failedTx and avoid re-evaluation, since the re-evaluation would be using
526 // cached size/sigops/fee values that are not actually correct.
528 {
529  assert (it != mempool.mapTx.end());
530  return mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it);
531 }
532 
533 void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, CTxMemPool::txiter entry, std::vector<CTxMemPool::txiter>& sortedEntries)
534 {
535  // Sort package by ancestor count
536  // If a transaction A depends on transaction B, then A's ancestor count
537  // must be greater than B's. So this is sufficient to validly order the
538  // transactions for block inclusion.
539  sortedEntries.clear();
540  sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
541  std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
542 }
543 
544 // This transaction selection algorithm orders the mempool based
545 // on feerate of a transaction including all unconfirmed ancestors.
546 // Since we don't remove transactions from the mempool as we select them
547 // for block inclusion, we need an alternate method of updating the feerate
548 // of a transaction with its not-yet-selected ancestors as we go.
549 // This is accomplished by walking the in-mempool descendants of selected
550 // transactions and storing a temporary modified state in mapModifiedTxs.
551 // Each time through the loop, we compare the best transaction in
552 // mapModifiedTxs with the next transaction in the mempool to decide what
553 // transaction package to work on next.
554 void BlockAssembler::addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated, uint64_t minGasPrice)
555 {
556  // mapModifiedTx will store sorted packages after they are modified
557  // because some of their txs are already in the block
558  indexed_modified_transaction_set mapModifiedTx;
559  // Keep track of entries that failed inclusion, to avoid duplicate work
560  CTxMemPool::setEntries failedTx;
561 
562  // Start by adding all descendants of previously added txs to mapModifiedTx
563  // and modifying them for their already included ancestors
564  UpdatePackagesForAdded(inBlock, mapModifiedTx);
565 
566  CTxMemPool::indexed_transaction_set::index<ancestor_score_or_gas_price>::type::iterator mi = mempool.mapTx.get<ancestor_score_or_gas_price>().begin();
567  CTxMemPool::txiter iter;
568 
569  // Limit the number of attempts to add transactions to the block when it is
570  // close to full; this is just a simple heuristic to finish quickly if the
571  // mempool has a lot of entries.
572  const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
573  int64_t nConsecutiveFailed = 0;
574 
575  while (mi != mempool.mapTx.get<ancestor_score_or_gas_price>().end() || !mapModifiedTx.empty())
576  {
577  if(nTimeLimit != 0 && GetAdjustedTime() >= nTimeLimit){
578  //no more time to add transactions, just exit
579  return;
580  }
581  // First try to find a new transaction in mapTx to evaluate.
582  if (mi != mempool.mapTx.get<ancestor_score_or_gas_price>().end() &&
583  SkipMapTxEntry(mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) {
584  ++mi;
585  continue;
586  }
587 
588  // Now that mi is not stale, determine which transaction to evaluate:
589  // the next entry from mapTx, or the best from mapModifiedTx?
590  bool fUsingModified = false;
591 
592  modtxscoreiter modit = mapModifiedTx.get<ancestor_score_or_gas_price>().begin();
593  if (mi == mempool.mapTx.get<ancestor_score_or_gas_price>().end()) {
594  // We're out of entries in mapTx; use the entry from mapModifiedTx
595  iter = modit->iter;
596  fUsingModified = true;
597  } else {
598  // Try to compare the mapTx entry to the mapModifiedTx entry
599  iter = mempool.mapTx.project<0>(mi);
600  if (modit != mapModifiedTx.get<ancestor_score_or_gas_price>().end() &&
602  // The best entry in mapModifiedTx has higher score
603  // than the one from mapTx.
604  // Switch which transaction (package) to consider
605  iter = modit->iter;
606  fUsingModified = true;
607  } else {
608  // Either no entry in mapModifiedTx, or it's worse than mapTx.
609  // Increment mi for the next loop iteration.
610  ++mi;
611  }
612  }
613 
614  // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
615  // contain anything that is inBlock.
616  assert(!inBlock.count(iter));
617 
618  uint64_t packageSize = iter->GetSizeWithAncestors();
619  CAmount packageFees = iter->GetModFeesWithAncestors();
620  int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
621  if (fUsingModified) {
622  packageSize = modit->nSizeWithAncestors;
623  packageFees = modit->nModFeesWithAncestors;
624  packageSigOpsCost = modit->nSigOpCostWithAncestors;
625  }
626 
627  if (packageFees < blockMinFeeRate.GetFee(packageSize)) {
628  // Everything else we might consider has a lower fee rate
629  return;
630  }
631 
632  if (!TestPackage(packageSize, packageSigOpsCost)) {
633  if (fUsingModified) {
634  // Since we always look at the best entry in mapModifiedTx,
635  // we must erase failed entries so that we can consider the
636  // next best entry on the next loop iteration
637  mapModifiedTx.get<ancestor_score_or_gas_price>().erase(modit);
638  failedTx.insert(iter);
639  }
640 
641  ++nConsecutiveFailed;
642 
643  if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight >
644  nBlockMaxWeight - 4000) {
645  // Give up if we're close to full and haven't succeeded in a while
646  break;
647  }
648  continue;
649  }
650 
651  CTxMemPool::setEntries ancestors;
652  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
653  std::string dummy;
654  mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
655 
656  onlyUnconfirmed(ancestors);
657  ancestors.insert(iter);
658 
659  // Test if all tx's are Final
660  if (!TestPackageTransactions(ancestors)) {
661  if (fUsingModified) {
662  mapModifiedTx.get<ancestor_score_or_gas_price>().erase(modit);
663  failedTx.insert(iter);
664  }
665  continue;
666  }
667 
668  // This transaction will make it in; reset the failed counter.
669  nConsecutiveFailed = 0;
670 
671  // Package can be added. Sort the entries in a valid order.
672  std::vector<CTxMemPool::txiter> sortedEntries;
673  SortForBlock(ancestors, iter, sortedEntries);
674 
675  bool wasAdded=true; // FABCOIN_INSERT_LINE
676  for (size_t i=0; i<sortedEntries.size(); ++i) {
677  if(!wasAdded || (nTimeLimit != 0 && GetAdjustedTime() >= nTimeLimit))
678  {
679  //if out of time, or earlier ancestor failed, then skip the rest of the transactions
680  mapModifiedTx.erase(sortedEntries[i]);
681  wasAdded=false;
682  continue;
683  }
684  const CTransaction& tx = sortedEntries[i]->GetTx();
685  if(wasAdded) {
686  if (tx.HasCreateOrCall()) {
687  wasAdded = AttemptToAddContractToBlock(sortedEntries[i], minGasPrice);
688  if(!wasAdded){
689  if(fUsingModified) {
690  //this only needs to be done once to mark the whole package (everything in sortedEntries) as failed
691  mapModifiedTx.get<ancestor_score_or_gas_price>().erase(modit);
692  failedTx.insert(iter);
693  }
694  }
695  } else {
696  AddToBlock(sortedEntries[i]);
697  }
698  }
699  // Erase from the modified set, if present
700  mapModifiedTx.erase(sortedEntries[i]);
701  }
702 
703  if(!wasAdded){
704  //skip UpdatePackages if a transaction failed to be added (match TestPackage logic)
705  continue;
706  }
707 
708  ++nPackagesSelected;
709 
710  // Update transactions that depend on each of these
711  nDescendantsUpdated += UpdatePackagesForAdded(ancestors, mapModifiedTx);
712  }
713 }
714 
715 void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
716 {
717  // Update nExtraNonce
718  static uint256 hashPrevBlock;
719  if (hashPrevBlock != pblock->hashPrevBlock)
720  {
721  nExtraNonce = 0;
722  hashPrevBlock = pblock->hashPrevBlock;
723  }
724  ++nExtraNonce;
725  unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
726  CMutableTransaction txCoinbase(*pblock->vtx[0]);
727  txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
728  assert(txCoinbase.vin[0].scriptSig.size() <= 100);
729 
730  pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
731  pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
732 }
733 
734 #ifdef ENABLE_WALLET
735 //
737 // Internal miner
738 //
739 #include <net.h>
740 //
741 // ScanHash scans nonces looking for a hash with at least some zero bits.
742 // The nonce is usually preserved between calls, but periodically or if the
743 // nonce is 0xffff0000 or above, the block is rebuilt and nNonce starts over at
744 // zero.
745 //
746 
747 static bool ProcessBlockFound(const CBlock* pblock, const CChainParams& chainparams)
748 {
749  LogPrintf("%s\n", pblock->ToString());
750  LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0]->vout[0].nValue));
751 
752  // Found a solution
753  {
754  LOCK(cs_main);
755  if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
756  return error("FabcoinMiner: generated block is stale");
757  }
758 
759  // Inform about the new block
760  GetMainSignals().BlockFound(pblock->GetHash());
761 
762  // Process this block the same as if we had received it from another node
763  bool fNewBlock = false;
764  std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock);
765  if (!ProcessNewBlock(chainparams, shared_pblock, true, &fNewBlock))
766  return error("FabcoinMiner: ProcessNewBlock, block not accepted");
767 
768  return true;
769 }
770 
771 void static FabcoinMiner(const CChainParams& chainparams, GPUConfig conf, int thr_id)
772 {
773  static const unsigned int nInnerLoopCount = 0x0FFFFFFF;
774  int nCounter = 0;
775  int headerlen = 0;
776 
777  if(conf.useGPU)
778  LogPrintf("FabcoinMiner thread(%d@%u-%u) started on GPU device. \n", thr_id, conf.currentPlatform, conf.currentDevice);
779  else
780  LogPrintf("FabcoinMiner thread(%d) started on CPU \n", thr_id);
781 
783  RenameThread("fabcoin-miner");
784 
785  unsigned int nExtraNonce = 0;
786  std::shared_ptr<CReserveScript> coinbaseScript;
787  if( ::vpwallets.size() > 0 )
788  {
789  GetMainSignals().ScriptForMining(coinbaseScript);
790  }
791 
792  unsigned int n = chainparams.EquihashN();
793  unsigned int k = chainparams.EquihashK();
794 
795 #ifdef ENABLE_GPU
796  uint8_t * header = NULL;
797  GPUSolver * g_solver = NULL;
798  if(conf.useGPU)
799  {
800  g_solver = new GPUSolver(conf.currentPlatform, conf.currentDevice, n, k);
801  LogPrint(BCLog::POW, "Using Equihash solver GPU with n = %u, k = %u\n", n, k);
802  header = (uint8_t *) calloc(CBlockHeader::HEADER_NEWSIZE, sizeof(uint8_t));
803  }
804 #endif
805 
806  std::mutex m_cs;
807  bool cancelSolver = false;
808  // boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
809  // [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
810  // std::lock_guard<std::mutex> lock{m_cs};
811  // cancelSolver = true;
812  // }
813  // );
814 
815  try {
816  // Throw an error if no script was provided. This can happen
817  // due to some internal error but also if the keypool is empty.
818  // In the latter case, already the pointer is NULL.
819  if (!coinbaseScript || coinbaseScript->reserveScript.empty())
820  throw std::runtime_error("No coinbase script available (mining requires a wallet)");
821 
822  while (true) {
823  if (chainparams.MiningRequiresPeers()) {
824  // Busy-wait for the network to come online so we don't waste time mining
825  // on an obsolete chain. In regtest mode we expect to fly solo.
826  do {
827  unsigned int nNodeCount = g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL);
828  if ( nNodeCount && !IsInitialBlockDownload())
829  break;
830  MilliSleep(1000);
831  } while (true);
832  }
833 
834  //
835  // Create new block
836  //
837  unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
838  CBlockIndex* pindexPrev = chainActive.Tip();
839 
840  std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(Params()).CreateNewBlock(coinbaseScript->reserveScript));
841  if (!pblocktemplate.get())
842  {
843  LogPrintf("Error in FabcoinMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
844  return;
845  }
846  CBlock *pblock = &pblocktemplate->block;
847  IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
848 
849  n = chainparams.EquihashN(pblock->nHeight);
850  k = chainparams.EquihashK(pblock->nHeight);
851 
852  LogPrintf("FabcoinMiner mining with %u transactions in block (%u bytes) @(%s) n=%d, k=%d\n", pblock->vtx.size(),
853  ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION), conf.useGPU?"GPU":"CPU", n, k );
854 
855  headerlen = (pblock->nHeight < (uint32_t)chainparams.GetConsensus().ContractHeight) ? CBlockHeader::HEADER_SIZE : CBlockHeader::HEADER_NEWSIZE;
856  //
857  // Search
858  //
859  int64_t nStart = GetTime();
860  arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
861  uint256 hash;
862 
863  nCounter = 0;
864  if (conf.useGPU)
865  LogPrint(BCLog::POW, "Equihash solver in GPU (%u, %u) with nNonce = %s hashTarget=%s\n", conf.currentPlatform, conf.currentDevice, pblock->nNonce.ToString(), hashTarget.GetHex());
866  else
867  LogPrint(BCLog::POW, "Equihash solver in CPU with nNonce = %s hashTarget=%s\n", pblock->nNonce.ToString(), hashTarget.GetHex());
868 
869  double secs, solps;
870  g_nSols[thr_id] = 0;
871  auto t = std::chrono::high_resolution_clock::now();
872  while (true)
873  {
874  // I = the block header minus nonce and solution.
875  CEquihashInput I{*pblock};
876  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
877  ss << I;
878 
879  // Hash state
880  crypto_generichash_blake2b_state state;
881  EhInitialiseState(n, k, state);
882 
883  // H(I||...
884  crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
885 
886  if(conf.useGPU)
887  {
888 #ifdef ENABLE_GPU
889  memcpy(header, &ss[0], ss.size());
890 #endif
891  }
892 
893  // H(I||V||...
894  crypto_generichash_blake2b_state curr_state;
895 
896  if(conf.useGPU)
897  {
898 #ifdef ENABLE_GPU
899  for (size_t i = 0; i < FABCOIN_NONCE_LEN; ++i)
900  header[headerlen-32 + i] = pblock->nNonce.begin()[i];
901 #endif
902  }
903 
904  curr_state = state;
905  crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
906 
907  // (x_1, x_2, ...) = A(I, V, n, k)
908  //LogPrint(BCLog::POW, "Running Equihash solver in %d@%u-%u with nNonce = %s\n", thr_id, conf.currentPlatform, conf.currentDevice, pblock->nNonce.ToString());
909 
910  std::function<bool(std::vector<unsigned char>)> validBlock =
911  [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams,thr_id](std::vector<unsigned char> soln)
912  {
913  // Write the solution to the hash and compute the result.
914  //LogPrint(BCLog::POW, "- Checking solution against target\n");
915 
916  g_nSols[thr_id] ++ ;
917 
918  pblock->nSolution = soln;
919 
920  if (UintToArith256(pblock->GetHash()) > hashTarget)
921  {
922  return false;
923  }
924 
925  // Found a solution
927 
928  if (ProcessBlockFound(pblock, chainparams))
929  {
930  // Ignore chain updates caused by us
931  std::lock_guard<std::mutex> lock{m_cs};
932  cancelSolver = false;
933  }
935 
936  // In regression test mode, stop mining after a block is found.
937  if (chainparams.MineBlocksOnDemand()) {
938  // Increment here because throwing skips the call below
939  throw boost::thread_interrupted();
940  }
941  return true;
942  };
943 
944 #ifdef ENABLE_GPU
945  std::function<bool(GPUSolverCancelCheck)> cancelledGPU = [&m_cs, &cancelSolver](GPUSolverCancelCheck pos) {
946  std::lock_guard<std::mutex> lock{m_cs};
947  return cancelSolver;
948  };
949 #endif
950  std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
951  std::lock_guard<std::mutex> lock{m_cs};
952  return cancelSolver;
953  };
954 
955  try {
956  if(!conf.useGPU)
957  {
958  // If we find a valid block, we rebuild
959  bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
960  if (found) {
961  break;
962  }
963  }
964  else
965  {
966 #ifdef ENABLE_GPU
967  if( g_solver )
968  {
969  std::pair<int,int> param = g_solver->getparam();
970  if( param.first != n || param.second != k )
971  {
972  delete g_solver;
973  g_solver = new GPUSolver(conf.currentPlatform, conf.currentDevice, n, k);
974  }
975  }
976  bool found = g_solver->run(n, k, header, headerlen, pblock->nNonce, validBlock, cancelledGPU, curr_state);
977  if (found)
978  break;
979 #endif
980  }
981  } catch (EhSolverCancelledException&) {
982  LogPrint(BCLog::POW, "Equihash solver cancelled\n");
983  std::lock_guard<std::mutex> lock{m_cs};
984  cancelSolver = false;
985  }
986 
987  // Check for stop or if block needs to be rebuilt
988  boost::this_thread::interruption_point();
989  // Regtest mode doesn't require peers
990  unsigned int nNodeCount = g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL);
991  if (nNodeCount == 0 && chainparams.MiningRequiresPeers())
992  break;
993  if ( nCounter == nInnerLoopCount )
994  break;
995  if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
996  break;
997  if (pindexPrev != chainActive.Tip())
998  break;
999 
1000  //LogPrint(BCLog::POW, "solver... nNonce = %s -> Hash = %s \n", pblock->nNonce.ToString(), pblock->GetHash().GetHex());
1001  // Update nNonce and nTime
1002  pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
1003  ++nCounter;
1004 
1005  // block.nTime is refered by solidity 'now', can't be updated once block is created
1006  // Update nTime every few seconds
1007  //if (UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev) < 0)
1008  // break; // Recreate the block if the clock has run backwards,
1009  // so that we can use the correct time.
1010 
1011 
1012  if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
1013  {
1014  // check if the new block will come too late. If so, create the block again to change block time
1015  if( IsBlockTooLate( pblock, chainparams.GetConsensus(), pindexPrev ) )
1016  {
1017  break;
1018  }
1019  }
1020 
1021  if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
1022  {
1023  // Changing pblock->nTime can change work required on testnet:
1024  hashTarget.SetCompact(pblock->nBits);
1025  }
1026  }
1027  // hashrate
1028  auto d = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - t);
1029  auto milis = std::chrono::duration_cast<std::chrono::milliseconds>(d).count();
1030  secs = (1.0 * milis)/1000;
1031  solps = (double)g_nSols[thr_id] / secs;
1032  LogPrintf("Thread(%d@%u-%u) - %d solutions in %.2f s (%.2f Sol/s)\n", thr_id, conf.currentPlatform, conf.currentDevice, g_nSols[thr_id], secs, solps);
1033  }
1034  }
1035  catch (const boost::thread_interrupted&)
1036  {
1037  LogPrintf("FabcoinMiner terminated\n");
1038 #ifdef ENABLE_GPU
1039  if(conf.useGPU)
1040  delete g_solver;
1041  free(header);
1042 #endif
1043  throw;
1044  }
1045  catch (const std::runtime_error &e)
1046  {
1047  LogPrintf("FabcoinMiner runtime error: %s\n", e.what());
1048 #ifdef ENABLE_GPU
1049  if(conf.useGPU)
1050  delete g_solver;
1051  free(header);
1052 #endif
1053  return;
1054  }
1055 
1056 #ifdef ENABLE_GPU
1057  if(conf.useGPU)
1058  delete g_solver;
1059  free(header);
1060 #endif
1061 
1062 // c.disconnect();
1063 }
1064 
1065 #if defined(ENABLE_GPU) && defined(USE_CUDA)
1066 
1067 static bool cb_cancel()
1068 {
1069  return g_cancelSolver;
1070 }
1071 
1072 static bool cb_validate(std::vector<unsigned char> sols, unsigned char *pblockdata, int thrid)
1073 {
1074  bool ret = false;
1075  CBlock *pblock = (CBlock *)pblockdata;
1076  g_nSols[thrid]++;
1077 
1078  g_cs.lock();
1079  do
1080  {
1081  pblock->nSolution = sols;
1082  CChainParams chainparams = Params();
1083  arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
1084  if (UintToArith256(pblock->GetHash()) > hashTarget)
1085  {
1086  break;
1087  }
1088  // Found a solution
1090  if (ProcessBlockFound(pblock, chainparams))
1091  {
1092  // Ignore chain updates caused by us
1093  g_cancelSolver = false;
1094  }
1096  ret = true;
1097  }while(0);
1098 
1099  g_cs.unlock();
1100  return ret;
1101 }
1102 
1103 void static FabcoinMinerCuda(const CChainParams& chainparams, GPUConfig conf, int thr_id)
1104 {
1105  static const unsigned int nInnerLoopCount = 0x0FFFFFFF;
1106  unsigned int nCounter = 0;
1107  int headerlen = 0;
1108 
1109  LogPrintf("FabcoinMiner thread(%d@%u-%u) started on GPU device(CUDA) \n", thr_id, conf.currentPlatform, conf.currentDevice);
1110 
1112  RenameThread("fabcoin-miner-cuda");
1113 
1114  unsigned int nExtraNonce = 0;
1115  std::shared_ptr<CReserveScript> coinbaseScript;
1116  if( ::vpwallets.size() > 0 )
1117  {
1118  GetMainSignals().ScriptForMining(coinbaseScript);
1119  }
1120 
1121  unsigned int n = chainparams.EquihashN();
1122  unsigned int k = chainparams.EquihashK();
1123 
1124  uint8_t * header = NULL;
1125  eq_cuda_context<CONFIG_MODE_1> *g_solver = NULL;
1126  eq_cuda_context1847 *g_solver184_7 = NULL;
1127  header = (uint8_t *) calloc(CBlockHeader::HEADER_NEWSIZE, sizeof(uint8_t));
1128 
1129  try {
1130  // Throw an error if no script was provided. This can happen
1131  // due to some internal error but also if the keypool is empty.
1132  // In the latter case, already the pointer is NULL.
1133  if (!coinbaseScript || coinbaseScript->reserveScript.empty())
1134  throw std::runtime_error("No coinbase script available (mining requires a wallet)");
1135 
1136  while (true) {
1137  if (chainparams.MiningRequiresPeers()) {
1138  // Busy-wait for the network to come online so we don't waste time mining
1139  // on an obsolete chain. In regtest mode we expect to fly solo.
1140  do {
1141  unsigned int nNodeCount = g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL);
1142  if ( nNodeCount && !IsInitialBlockDownload())
1143  break;
1144  MilliSleep(1000);
1145  } while (true);
1146  }
1147 
1148  //
1149  // Create new block
1150  //
1151  unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
1152  CBlockIndex* pindexPrev = chainActive.Tip();
1153 
1154  std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(Params()).CreateNewBlock(coinbaseScript->reserveScript));
1155  if (!pblocktemplate.get())
1156  {
1157  LogPrintf("Error in FabcoinMinerCuda: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
1158  return;
1159  }
1160  CBlock *pblock = &pblocktemplate->block;
1161  IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
1162  n = chainparams.EquihashN(pblock->nHeight );
1163  k = chainparams.EquihashK(pblock->nHeight );
1164  LogPrintf("FabcoinMiner mining with %u transactions in block (%u bytes) @(%s) n=%d, k=%d\n", pblock->vtx.size(),
1165  ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION), conf.useGPU?"GPU":"CPU", n, k );
1166 
1167  headerlen = (pblock->nHeight < (uint32_t)chainparams.GetConsensus().ContractHeight) ? CBlockHeader::HEADER_SIZE : CBlockHeader::HEADER_NEWSIZE;
1168 
1169  try
1170  {
1171  if ( pblock->nHeight < (uint32_t)chainparams.GetConsensus().EquihashFABHeight) // before fork
1172  {
1173  if( g_solver184_7 )
1174  {
1175  delete g_solver184_7;
1176  g_solver184_7 = NULL;
1177  }
1178 
1179  if( !g_solver )
1180  {
1181  g_solver = new eq_cuda_context<CONFIG_MODE_1>(thr_id, conf.currentDevice,&cb_validate, &cb_cancel);
1182  }
1183  }
1184  else // after fork
1185  {
1186  if( g_solver )
1187  {
1188  delete g_solver;
1189  g_solver = NULL;
1190  }
1191 
1192  if( !g_solver184_7 )
1193  {
1194  g_solver184_7 = new eq_cuda_context1847(thr_id, conf.currentDevice,&cb_validate, &cb_cancel);
1195  }
1196  }
1197  }
1198  catch (const std::runtime_error &e)
1199  {
1200  LogPrint(BCLog::POW, "failed to create cuda context\n");
1201  std::lock_guard<std::mutex> lock{g_cs};
1202  g_cancelSolver = false;
1203  return;
1204  }
1205 
1206  //
1207  // Search
1208  //
1209  int64_t nStart = GetTime();
1210  arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
1211  uint256 hash;
1212 
1213  nCounter = 0;
1214  LogPrint(BCLog::POW, "Equihash solver in CUDA(%d@%u-%u) with nNonce = %s hashTarget=%s\n", thr_id, conf.currentPlatform, conf.currentDevice, pblock->nNonce.ToString(), hashTarget.GetHex());
1215 
1216  double secs, solps;
1217  g_nSols[thr_id] = 0;
1218  auto t = std::chrono::high_resolution_clock::now();
1219  while (true)
1220  {
1221  // I = the block header minus nonce and solution.
1222  CEquihashInput I{*pblock};
1223  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
1224  ss << I;
1225 
1226  memcpy(header, &ss[0], ss.size());
1227  for (size_t i = 0; i < FABCOIN_NONCE_LEN; ++i)
1228  header[headerlen-32 + i] = pblock->nNonce.begin()[i];
1229 
1230  try {
1231  bool found = false;
1232 
1233  if ( pblock->nHeight < (uint32_t)chainparams.GetConsensus().EquihashFABHeight ) // before fork
1234  {
1235  if( g_solver )
1236  found = g_solver->solve((unsigned char *)pblock, header, headerlen);
1237  }
1238  else
1239  {
1240  if( g_solver184_7 )
1241  found = g_solver184_7->solve((unsigned char *)pblock, header, headerlen);
1242  }
1243  if (found)
1244  break;
1245  } catch (EhSolverCancelledException&) {
1246  LogPrint(BCLog::POW, "Equihash solver cancelled\n");
1247  std::lock_guard<std::mutex> lock{g_cs};
1248  g_cancelSolver = false;
1249  }
1250 
1251  // Check for stop or if block needs to be rebuilt
1252  boost::this_thread::interruption_point();
1253  // Regtest mode doesn't require peers
1254  unsigned int nNodeCount = g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL);
1255  if (nNodeCount == 0 && chainparams.MiningRequiresPeers())
1256  break;
1257  if ( nCounter == nInnerLoopCount )
1258  break;
1259  if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
1260  break;
1261  if (pindexPrev != chainActive.Tip())
1262  break;
1263 
1264  // Update nNonce and nTime
1265  pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
1266  ++nCounter;
1267 
1268  // block.nTime is refered by solidity 'now', can't be updated once block is created
1269  // Update nTime every few seconds
1270  //if (UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev) < 0)
1271  // break; // Recreate the block if the clock has run backwards,
1272  // so that we can use the correct time.
1273 
1274 
1275  if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
1276  {
1277  // check if the new block will come too late. If so, create the block again to change block time
1278  if( IsBlockTooLate( pblock, chainparams.GetConsensus(), pindexPrev ) )
1279  {
1280  break;
1281  }
1282  }
1283 
1284  if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
1285  {
1286  // Changing pblock->nTime can change work required on testnet:
1287  hashTarget.SetCompact(pblock->nBits);
1288  }
1289  }
1290  // hashrate
1291  auto d = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - t);
1292  auto milis = std::chrono::duration_cast<std::chrono::milliseconds>(d).count();
1293  secs = (1.0 * milis)/1000;
1294  solps = (double)g_nSols[thr_id] / secs;
1295  LogPrintf("Thread(%d@%u-%u) CUDA- %d solutions in %.2f s (%.2f Sol/s)\n", thr_id, conf.currentPlatform, conf.currentDevice, g_nSols[thr_id], secs, solps);
1296  }
1297  }
1298  catch (const boost::thread_interrupted&)
1299  {
1300  LogPrintf("FabcoinMiner terminated\n");
1301  if( g_solver)
1302  delete g_solver;
1303 
1304  if( g_solver184_7 )
1305  delete g_solver184_7;
1306 
1307  free(header);
1308  throw;
1309  }
1310  catch (const std::runtime_error &e)
1311  {
1312  LogPrintf("FabcoinMiner runtime error: %s\n", e.what());
1313  if( g_solver)
1314  delete g_solver;
1315 
1316  if( g_solver184_7 )
1317  delete g_solver184_7;
1318 
1319  free(header);
1320  return;
1321  }
1322 
1323  if( g_solver)
1324  delete g_solver;
1325 
1326  if( g_solver184_7 )
1327  delete g_solver184_7;
1328 
1329  free(header);
1330 }
1331 #endif
1332 
1333 static boost::thread_group* minerThreads = NULL;
1334 void GenerateFabcoins(bool fGenerate, int nThreads, const CChainParams& chainparams)
1335 {
1336 
1337  if (nThreads < 0)
1338  nThreads = GetNumCores();
1339 
1340  if (minerThreads != NULL)
1341  {
1342  minerThreads->interrupt_all();
1343  minerThreads->join_all();
1344  delete minerThreads;
1345  minerThreads = NULL;
1346  }
1347 
1348  if (nThreads == 0 || !fGenerate)
1349  return;
1350 }
1351 
1352 void GenerateFabcoins(bool fGenerate, int nThreads, const CChainParams& chainparams, GPUConfig conf)
1353 {
1354  if (nThreads < 0) {
1355  if(conf.useGPU) {
1356  nThreads = 16; // limit max GPU thread per device 16;
1357  }
1358  else nThreads = GetNumCores();
1359  }
1360 
1361  if (minerThreads != NULL)
1362  {
1363  minerThreads->interrupt_all();
1364  minerThreads->join_all();
1365  delete minerThreads;
1366  minerThreads = NULL;
1367  }
1368 
1369  if (nThreads == 0 || !fGenerate)
1370  return;
1371 
1372  minerThreads = new boost::thread_group();
1373  int thread_sequence = 0;
1374 
1375  // If using GPU
1376  if(conf.useGPU) {
1377 #ifdef ENABLE_GPU
1378  conf.currentPlatform = conf.sel_platform;
1379  conf.currentDevice = conf.selGPU;
1380 
1381  std::vector<cl::Platform> platforms = cl_gpuminer::getPlatforms();
1382 
1383  // use all available GPUs
1384  if(conf.allGPU) {
1385 
1386  int devicesFound = 0;
1387  unsigned numPlatforms = platforms.size();
1388 
1389  for(unsigned platform = 0; platform < numPlatforms; ++platform)
1390  {
1391  std::string info = cl_gpuminer::platform_info(platform);
1392  std::string infolow;
1393  bool bNvidiaDev = false;
1394 
1395  infolow.resize(info.size());
1396  std::transform(info.begin(),info.end(),infolow.begin(),::tolower);
1397  if( infolow.find("nvidia") != std::string::npos )
1398  bNvidiaDev = true;
1399 
1400 
1401  std::vector<cl::Device> devices = cl_gpuminer::getDevices(platforms, platform);
1402  unsigned noDevices = devices.size();
1403  devicesFound += noDevices;
1404 
1405 
1406  for(unsigned device = 0; device < noDevices; ++device) {
1407 
1408  conf.currentPlatform = platform;
1409  conf.currentDevice = device;
1410 
1411  cl_ulong result;
1412  devices[device].getInfo(CL_DEVICE_GLOBAL_MEM_SIZE, &result);
1413 
1414  int maxThreads = nThreads;
1415  CBlockIndex* pindexPrev = chainActive.Tip();
1416 
1417  if (!conf.forceGenProcLimit) {
1418 
1419  if( (pindexPrev->nHeight+1) < chainparams.GetConsensus().EquihashFABHeight )
1420  {
1421  if (result > 7500000000) {
1422  maxThreads = std::min(4, nThreads);
1423  } else if (result > 5500000000) {
1424  maxThreads = std::min(3, nThreads);
1425  } else if (result > 3500000000) {
1426  maxThreads = std::min(2, nThreads);
1427  } else {
1428  maxThreads = std::min(1, nThreads);
1429  }
1430  }
1431  else
1432  {
1433  if (result > 7500000000) {
1434  maxThreads = std::min(2, nThreads);
1435  } else {
1436  maxThreads = std::min(1, nThreads);
1437  }
1438  }
1439  }
1440 
1441  LogPrintf("GenerateFabcoins GPU (platform=%d device=%d) maxThread =%d.\n", conf.currentPlatform, conf.currentDevice, maxThreads );
1442 
1443  for (int i = 0; i < maxThreads; i++){
1444  if ( thread_sequence > 255 ){
1445  LogPrintf("GenerateFabcoins reached GPU threads limit 255.\n", conf.currentPlatform, conf.currentDevice, i);
1446  break;
1447  }
1448 
1449  thread_sequence ++;
1450  LogPrintf("GenerateFabcoins GPU (platform=%d device=%d) starting thread=%d...\n", conf.currentPlatform, conf.currentDevice, thread_sequence);
1451  if( bNvidiaDev && conf.useCUDA ){
1452 #ifdef USE_CUDA
1453  minerThreads->create_thread(boost::bind(&FabcoinMinerCuda, boost::cref(chainparams), conf, thread_sequence ));
1454 #endif
1455  }
1456  else
1457  minerThreads->create_thread(boost::bind(&FabcoinMiner, boost::cref(chainparams), conf, thread_sequence ));
1458  }
1459 
1460  }
1461  }
1462 
1463  if (devicesFound <= 0) {
1464  LogPrintf("GenerateFabcoins ERROR, No OpenCL devices found!\n");
1465  }
1466 
1467  }
1468  else
1469  {
1470  LogPrintf("GenerateFabcoins GPU @(platform=%d device=%d) only!\n", conf.currentPlatform, conf.currentDevice );
1471 
1472  std::string info = cl_gpuminer::platform_info(conf.currentPlatform);
1473  std::string infolow;
1474  bool bNvidiaDev = false;
1475 
1476  infolow.resize(info.size());
1477  std::transform(info.begin(),info.end(),infolow.begin(),::tolower);
1478  if( infolow.find("nvidia") != std::string::npos )
1479  bNvidiaDev = true;
1480 
1481  // mine on specified GPU device
1482  std::vector<cl::Device> devices = cl_gpuminer::getDevices(platforms, conf.currentPlatform);
1483 
1484  if (devices.size() > conf.currentDevice)
1485  {
1486 
1487  cl_ulong result;
1488  devices[conf.currentDevice].getInfo(CL_DEVICE_GLOBAL_MEM_SIZE, &result);
1489 
1490  int maxThreads = nThreads;
1491 
1492  if (!conf.forceGenProcLimit) {
1493  if (result > 7500000000) {
1494  maxThreads = std::min(4, nThreads);
1495  } else if (result > 5500000000) {
1496  maxThreads = std::min(3, nThreads);
1497  } else if (result > 3500000000) {
1498  maxThreads = std::min(2, nThreads);
1499  } else {
1500  maxThreads = std::min(1, nThreads);
1501  }
1502  }
1503 
1504 
1505  LogPrintf("GenerateFabcoins GPU (platform=%d device=%d) maxThread =%d!\n", conf.currentPlatform, conf.currentDevice, maxThreads );
1506 
1507  for (int i = 0; i < maxThreads; i++) {
1508 
1509  if ( thread_sequence > 255 ){
1510  LogPrintf("GenerateFabcoins reached GPU threads limit 255.\n", conf.currentPlatform, conf.currentDevice, i);
1511  break;
1512  }
1513 
1514  thread_sequence ++;
1515 
1516  LogPrintf("GenerateFabcoins GPU (platform=%d device=%d) starting thread=%d...\n", conf.currentPlatform, conf.currentDevice, thread_sequence);
1517  if( bNvidiaDev && conf.useCUDA ){
1518 #ifdef USE_CUDA
1519  minerThreads->create_thread(boost::bind(&FabcoinMinerCuda, boost::cref(chainparams), conf, thread_sequence ));
1520 #endif
1521  }
1522  else
1523  minerThreads->create_thread(boost::bind(&FabcoinMiner, boost::cref(chainparams), conf, thread_sequence ));
1524  }
1525  }
1526  else
1527  {
1528  LogPrintf("GenerateFabcoins ERROR, No OpenCL devices found!\n");
1529  }
1530  }
1531 #endif
1532  }
1533  else
1534  {
1535  for (int i = 0; i < nThreads; i++){
1536  LogPrintf("GenerateFabcoins CPU, thread=%d!\n", i);
1537  minerThreads->create_thread(boost::bind(&FabcoinMiner, boost::cref(chainparams), conf, i));
1538  }
1539  }
1540 }
1541 
1542 
1543 void Scan_nNonce_nSolution(CBlock *pblock, unsigned int n, unsigned int k )
1544 {
1545  bool cancelSolver = false;
1546  uint64_t nMaxTries = 0;
1547 
1548  //
1549  // Search
1550  //
1551  arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
1552  uint256 hash;
1553 
1554  while (true) {
1555  nMaxTries++;
1556  // Hash state
1557  crypto_generichash_blake2b_state state;
1558  EhInitialiseState(n, k, state);
1559 
1560  // I = the block header minus nonce and solution.
1561  CEquihashInput I{*pblock};
1562  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
1563  ss << I;
1564 
1565  // H(I||...
1566  crypto_generichash_blake2b_update(&state, (unsigned char*) &ss[0], ss.size());
1567 
1568  // H(I||V||...
1569  crypto_generichash_blake2b_state curr_state;
1570  curr_state = state;
1571  crypto_generichash_blake2b_update(&curr_state, pblock->nNonce.begin(), pblock->nNonce.size());
1572 
1573  // (x_1, x_2, ...) = A(I, V, n, k)
1574  // LogPrint(BCLog::POW, "Running Equihash solver \"%s\" with nNonce = %s\n",
1575  // solver, pblock->nNonce.ToString());
1576 
1577  std::function<bool(std::vector<unsigned char>) > validBlock =
1578  [&pblock, &hashTarget, &cancelSolver ](std::vector<unsigned char> soln) {
1579  // Write the solution to the hash and compute the result.
1580  LogPrint(BCLog::POW, "- Checking solution against target\n");
1581  pblock->nSolution = soln;
1582 
1583  if (UintToArith256(pblock->GetHash()) > hashTarget) {
1584  return false;
1585  }
1586 
1587  // Found a solution
1589  LogPrintf("Scan_nNonce:\n");
1590  LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
1591 
1592  return true;
1593  };
1594 
1595  std::function<bool(EhSolverCancelCheck) > cancelled = [ &cancelSolver](EhSolverCancelCheck pos) {
1596  return cancelSolver;
1597  };
1598 
1599  try {
1600  // If we find a valid block, we rebuild
1601  bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
1602  if (found) {
1603  LogPrintf("FabcoinMiner:\n");
1604  LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
1605  LogPrintf("Block ------------------ \n%s\n ----------------", pblock->ToString());
1606 
1607  break;
1608  }
1609  } catch (EhSolverCancelledException&) {
1610  LogPrint(BCLog::POW, "Equihash solver cancelled\n");
1611  cancelSolver = false;
1612  }
1613 
1614  // Update nNonce and nTime
1615  pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
1616  }
1617 }
1618 
1619 
1620 void creategenesisblock ( uint32_t nTime, uint32_t nBits )
1621 {
1622  const char* pszTimestamp = "Fabcoin1ff5c8707d920ee573f5f1d43e559dfa3e4cb3f97786e8cb1685c991786b2";
1623  const CScript genesisOutputScript = CScript() << ParseHex("0322fdc78866c654c11da2fac29f47b2936f2c75a569155017893607b9386a4861") << OP_CHECKSIG;
1624 
1625  CMutableTransaction txNew;
1626  txNew.nVersion = 1;
1627  txNew.vin.resize(1);
1628  txNew.vout.resize(1);
1629 
1630  txNew.vin[0].scriptSig = CScript() << 00 << 520617983 << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1631 
1632  txNew.vout[0].nValue = 25 * COIN;
1633  txNew.vout[0].scriptPubKey = genesisOutputScript;
1634 
1635  CBlock pblock;
1636  //pblock.nTime = GetAdjustedTime();
1637  pblock.nTime = nTime;
1638  pblock.nBits = nBits;
1639  pblock.nNonce = uint256();
1640  //pblock.nSolution = uint256();
1641  pblock.nVersion = 4;
1642  pblock.vtx.push_back(MakeTransactionRef(std::move(txNew)));
1643  pblock.hashPrevBlock.SetNull();
1644  pblock.nHeight = 0;
1645  pblock.hashMerkleRoot = BlockMerkleRoot(pblock);
1646 
1647  const size_t N = 48, K = 5;
1648  Scan_nNonce_nSolution ( & pblock, N, K );
1649 
1650  std::cerr << pblock.ToString() << std::endl;
1651 }
1652 #endif // ENABLE_WALLET
1653 
static std::string platform_info(unsigned _platformId=0, unsigned _deviceId=0)
std::pair< std::vector< FascTransaction >, std::vector< EthTransactionParams >> ExtractFascTX
Definition: validation.h:50
indexed_modified_transaction_set::nth_index< 0 >::type::iterator modtxiter
Definition: miner.h:169
bool TestPackageTransactions(const CTxMemPool::setEntries &package)
Perform checks on each transaction in a package: locktime, premature-witness, serialized size (if nec...
Definition: miner.cpp:326
bool forceGenProcLimit
Definition: gpuconfig.h:38
CTxMemPool mempool
bool error(const char *fmt, const Args &...args)
Definition: util.h:178
int32_t nTimeLimit
Definition: miner.h:237
CFeeRate blockMinFeeRate
Definition: miner.h:217
bool solve(unsigned char *pblock, unsigned char *header, unsigned int headerlen)
Definition: miner.h:48
std::vector< CWalletRef > vpwallets
Definition: wallet.cpp:41
bool MineBlocksOnDemand() const
Make miner stop after a block is found.
Definition: chainparams.h:76
unsigned int nBlockMaxWeight
Definition: miner.h:197
uint256 GetRandHash()
Definition: random.cpp:372
void addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated, uint64_t minGasPrice)
Add transactions based on feerate including unconfirmed ancestors Increments nPackagesSelected / nDes...
Definition: miner.cpp:554
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
void SetNull()
Definition: uint256.h:46
uint256 nNonce
Definition: block.h:53
void SetThreadPriority(int nPriority)
Definition: util.cpp:945
void MilliSleep(int64_t n)
Definition: utiltime.cpp:60
int64_t GetTransactionWeight(const CTransaction &tx)
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:533
void AddToBlock(CTxMemPool::txiter iter)
Add a tx to the block.
Definition: miner.cpp:472
bool IsArgSet(const std::string &strArg)
Return true if the given argument has been manually set.
Definition: util.cpp:498
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:65
bool performByteCode(dev::eth::Permanence type=dev::eth::Permanence::Committed)
Definition: block.h:155
bool useCUDA
Definition: gpuconfig.h:37
unsigned int EquihashN(uint32_t nHeight=0) const
Definition: chainparams.h:72
uint64_t hardBlockGasLimit
Definition: miner.h:228
uint64_t nBlockTx
Definition: miner.h:202
#define strprintf
Definition: tinyformat.h:1054
#define EhInitialiseState(n, k, base_state)
Definition: equihash.h:204
std::vector< CTxIn > vin
Definition: transaction.h:392
int g_nSols[128]
Definition: miner.cpp:49
size_t GetSerializeSize(const T &t, int nType, int nVersion=0)
Definition: serialize.h:989
void onlyUnconfirmed(CTxMemPool::setEntries &testSet)
Remove confirmed (inBlock) entries from given set.
Definition: miner.cpp:299
std::string GetHex() const
Definition: uint256.cpp:21
CMutableTransaction originalRewardTx
Definition: miner.h:234
unsigned selGPU
Definition: gpuconfig.h:35
size_t count
Definition: ExecStats.cpp:37
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:60
uint32_t nHeight
Definition: block.h:46
int64_t nLockTimeCutoff
Definition: miner.h:209
CCriticalSection cs_main
Definition: validation.cpp:77
CTxMemPool::setEntries inBlock
Definition: miner.h:205
std::unique_ptr< CBlockTemplate > pblocktemplate
Definition: miner.h:191
void BlockFound(const uint256 &)
bool fPowAllowMinDifficultyBlocks
Definition: params.h:79
uint32_t nReserved[7]
Definition: block.h:47
int64_t dgpMaxBlockSigOps
The maximum allowed number of signature check operations in a block (network rule) ...
Definition: consensus.cpp:15
bool run(unsigned int n, unsigned int k, uint8_t *header, size_t header_len, uint256 nonce, const std::function< bool(std::vector< unsigned char >)> validBlock, const std::function< bool(GPUSolverCancelCheck)> cancelled, crypto_generichash_blake2b_state base_state)
void GenerateFabcoins(bool fGenerate, int nThreads, const CChainParams &chainparams)
Run the miner threads.
CBlock * pblock
Definition: miner.h:193
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
Definition: util.cpp:520
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:534
std::mutex g_cs
Definition: miner.cpp:47
assert(len-trim+(2 *lenIndices)<=WIDTH)
int64_t GetTimeMicros()
Definition: utiltime.cpp:47
CChainParams defines various tweakable parameters of a given instance of the Fabcoin system...
Definition: chainparams.h:47
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn, bool fMineWitnessTx=true, int64_t *pTotalFees=0, int32_t nTime=0, int32_t nTimeLimit=0)
Construct a new block template with coinbase to scriptPubKeyIn.
Definition: miner.cpp:153
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:146
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Determine what nVersion a new block should use.
ExecStats::duration min
Definition: ExecStats.cpp:35
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > pblock, bool fForceProcessing, bool *fNewBlock)
Process an incoming block.
static std::vector< cl::Platform > getPlatforms()
#define FABCOIN_NONCE_LEN
Definition: libclwrapper.h:8
unsigned char * begin()
Definition: uint256.h:65
void RenameThread(const char *name)
Definition: util.cpp:888
uint32_t nTime
Definition: block.h:48
uint32_t FABHeight
Block height at which Fabcoin Equihash hard fork becomes active.
Definition: params.h:52
arith_uint256 UintToArith256(const uint256 &a)
uint64_t nLastBlockWeight
Definition: miner.cpp:63
std::string ToString() const
Definition: uint256.cpp:95
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:354
indexed_transaction_set mapTx
Definition: txmempool.h:524
int64_t CAmount
Amount in lius (Can be negative)
Definition: amount.h:15
bool solve(unsigned char *pblock, unsigned char *header, unsigned int headerlen)
int64_t GetnPowTargetSpacing(uint32_t nHeight=0) const
Definition: chainparams.h:74
#define THREAD_PRIORITY_NORMAL
Definition: compat.h:82
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_or_gas_price >, boost::multi_index::identity< CTxMemPoolModifiedEntry >, CompareModifiedEntry > >> indexed_modified_transaction_set
Definition: miner.h:167
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:512
#define LOCK2(cs1, cs2)
Definition: sync.h:176
void Scan_nNonce_nSolution(CBlock *pblock, unsigned int n, unsigned int k)
#define LogPrintf(...)
Definition: util.h:153
#define THREAD_PRIORITY_LOWEST
Definition: compat.h:80
bool EhOptimisedSolve(unsigned int n, unsigned int k, const eh_HashState &base_state, const std::function< bool(std::vector< unsigned char >)> validBlock, const std::function< bool(EhSolverCancelCheck)> cancelled)
Definition: equihash.h:245
uint256 hashMerkleRoot
Definition: block.h:45
std::pair< int, int > getparam()
Definition: libgpusolver.h:66
const CChainParams & chainparams
Definition: miner.h:210
int64_t GetBlockTime() const
Definition: block.h:127
#define LOCK(cs)
Definition: sync.h:175
size_type size() const
Definition: streams.h:237
ExecStats::duration max
Definition: ExecStats.cpp:36
uint64_t nLastBlockTx
Definition: miner.cpp:62
void CalculateDescendants(txiter it, setEntries &setDescendants)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:456
CAmount nFees
Definition: miner.h:204
GPUSolverCancelCheck
Definition: libgpusolver.h:57
uint32_t ContractHeight
Block height at which Fabcoin Smart Contract hard fork becomes active.
Definition: params.h:56
uint256 hashPrevBlock
Definition: block.h:44
size_t nBlockMaxWeight
Definition: miner.h:215
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
BlockAssembler(const CChainParams &params)
Definition: miner.cpp:121
CMainSignals & GetMainSignals()
Generate a new block, without valid proof-of-work.
Definition: miner.h:187
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:158
bool ParseMoney(const std::string &str, CAmount &nRet)
CAmount refundSender
Definition: validation.h:723
An output of a transaction.
Definition: transaction.h:131
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:80
boost::multiprecision::number< boost::multiprecision::cpp_int_backend< 256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void >> u256
Definition: Common.h:125
Parameters that influence chain consensus.
Definition: params.h:39
CScript COINBASE_FLAGS
Constant stuff for coinbase transactions we create:
Definition: validation.cpp:113
std::vector< unsigned char > nSolution
Definition: block.h:54
bool processingResults(ByteCodeExecResult &result)
uint64_t minGasPrice
Definition: miner.h:227
std::vector< CTxOut > vout
Definition: transaction.h:393
std::string GetHex() const
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:491
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
256-bit unsigned big integer.
indexed_transaction_set::nth_index< 0 >::type::iterator txiter
Definition: txmempool.h:526
CCriticalSection cs
Definition: txmempool.h:523
Custom serializer for CBlockHeader that omits the nonce and solution, for use as input to Equihash...
Definition: block.h:215
uint64_t softBlockGasLimit
Definition: miner.h:229
uint64_t nSizeWithAncestors
Definition: miner.h:58
uint8_t MaxBlockInterval
Definition: params.h:93
ByteCodeExecResult bceResult
Construct a new block template with coinbase to scriptPubKeyIn.
Definition: miner.h:226
std::string ToString() const
Definition: feerate.cpp:40
#define LogPrint(category,...)
Definition: util.h:164
void IncrementExtraNonce(CBlock *pblock, const CBlockIndex *pindexPrev, unsigned int &nExtraNonce)
Modify the extranonce in a block.
Definition: miner.cpp:715
std::string ToString() const
Definition: block.cpp:66
CAmount GetFee(size_t nBytes) const
Return the fee in liu for the given size in bytes.
Definition: feerate.cpp:23
bool allGPU
Definition: gpuconfig.h:36
uint64_t nBlockSigOpsCost
Definition: miner.h:203
Capture information about block/transaction validation.
Definition: validation.h:27
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:527
256-bit opaque blob.
Definition: uint256.h:132
CAmount nModFeesWithAncestors
Definition: miner.h:59
ArgsManager gArgs
Definition: util.cpp:94
void creategenesisblock(uint32_t nTime, uint32_t nBits)
uint256 ArithToUint256(const arith_uint256 &a)
std::vector< CTransactionRef > vtx
Definition: block.h:159
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
Definition: validation.cpp:407
uint256 GetHash() const
Definition: block.cpp:38
unsigned currentDevice
Definition: gpuconfig.h:40
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Auxiliary functions for transaction validation (ideally should not be exposed)
Definition: tx_verify.cpp:109
static const size_t HEADER_SIZE
Definition: block.h:39
bool useGPU
Definition: gpuconfig.h:33
CFeeRate blockMinFeeRate
Definition: miner.h:198
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:177
const CChainParams & Params()
Return the currently selected parameters.
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:504
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:417
void * memcpy(void *a, const void *b, size_t c)
bool AttemptToAddContractToBlock(CTxMemPool::txiter iter, uint64_t minGasPrice)
Definition: miner.cpp:337
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...
#define I(x, y, z)
Definition: Hash.cpp:82
int nHeight
Definition: miner.h:208
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...
unsigned int GetNextWorkRequired(const CBlockIndex *pindexPrev, const CBlockHeader *pblock, const Consensus::Params &params)
Definition: pow.cpp:18
bool HasCreateOrCall() const
int64_t nSigOpCostWithAncestors
Definition: miner.h:60
uint64_t nBlockWeight
Definition: miner.h:201
uint32_t EquihashFABHeight
Block height at which EquihashFAB (184,7) becomes active.
Definition: params.h:58
Fee rate in liu per kilobyte: CAmount / kB.
Definition: feerate.h:20
bool fIncludeWitness
Definition: miner.h:196
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:75
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.
EhSolverCancelCheck
Definition: equihash.h:135
#define e(i)
Definition: sha.cpp:733
void resetBlock()
Clear the block&#39;s state and prepare for assembling a new block.
Definition: miner.cpp:123
A mutable version of CTransaction.
Definition: transaction.h:390
uint256 hashStateRoot
Definition: block.h:50
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:19
uint64_t txGasLimit
Definition: miner.h:230
bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost)
Test if a new package would "fit" in the block.
Definition: miner.cpp:312
unsigned currentPlatform
Definition: gpuconfig.h:39
std::vector< CTxOut > refundOutputs
Definition: validation.h:724
dev::WithExisting max(dev::WithExisting _a, dev::WithExisting _b)
Definition: Common.h:326
#define d(i)
Definition: sha.cpp:732
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units...
Definition: utiltime.cpp:19
indexed_modified_transaction_set::index< ancestor_score_or_gas_price >::type::iterator modtxscoreiter
Definition: miner.h:170
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:275
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:193
int GetNumCores()
Return the number of physical cores available on the current system.
Definition: util.cpp:959
void ScriptForMining(std::shared_ptr< CReserveScript > &coinbaseScript)
bool MiningRequiresPeers() const
Make miner wait to have peers to avoid wasting work.
Definition: chainparams.h:66
unsigned sel_platform
Definition: gpuconfig.h:34
void RebuildRefundTransaction()
Rebuild the coinbase/coinstake transaction to account for new gas refunds.
Definition: miner.cpp:137
int64_t GetBlockTime() const
Definition: chain.h:329
uint256 hashUTXORoot
Definition: block.h:51
static const size_t HEADER_NEWSIZE
Definition: block.h:40
Definition: script.h:51
Definition: miner.h:86
int64_t GetMedianTimePast() const
Definition: chain.h:341
bool g_cancelSolver
Definition: miner.cpp:48
bool IsBlockTooLate(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:80
int32_t nVersion
Definition: block.h:43
unsigned int EquihashK(uint32_t nHeight=0) const
Definition: chainparams.h:73
static std::vector< cl::Device > getDevices(std::vector< cl::Platform > const &_platforms, unsigned _platformId)
std::unique_ptr< FascState > globalState
Global state.
Definition: validation.cpp:70
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:35
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:158
bool fGettingValuesDGP
Definition: validation.cpp:74
uint256 h256Touint(const dev::h256 &in)
Definition: uint256.h:178
std::shared_ptr< dev::eth::SealEngineFace > globalSealEngine
Definition: validation.cpp:71
uint256 GetBlockHash() const
Definition: chain.h:324
uint32_t nBits
Definition: block.h:49
unsigned int dgpMaxBlockWeight
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition: consensus.cpp:8
unsigned int size() const
Definition: uint256.h:85
std::vector< unsigned char > ParseHex(const char *psz)
std::vector< CTransaction > valueTransfers
Definition: validation.h:725