Dogecoin Core  1.14.2
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 // 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 "consensus/consensus.h"
13 #include "consensus/merkle.h"
14 #include "consensus/validation.h"
15 #include "dogecoin.h"
16 #include "hash.h"
17 #include "validation.h"
18 #include "net.h"
19 #include "policy/policy.h"
20 #include "pow.h"
21 #include "primitives/transaction.h"
22 #include "script/standard.h"
23 #include "timedata.h"
24 #include "txmempool.h"
25 #include "util.h"
26 #include "utilmoneystr.h"
27 #include "validationinterface.h"
28 
29 #include <algorithm>
30 #include <boost/thread.hpp>
31 #include <boost/tuple/tuple.hpp>
32 #include <queue>
33 #include <utility>
34 
36 //
37 // BitcoinMiner
38 //
39 
40 //
41 // Unconfirmed transactions in the memory pool often depend on other
42 // transactions in the memory pool. When we select transactions from the
43 // pool, we select by highest priority or fee rate, so we might consider
44 // transactions that depend on transactions that aren't yet in the block.
45 
46 uint64_t nLastBlockTx = 0;
47 uint64_t nLastBlockSize = 0;
48 uint64_t nLastBlockWeight = 0;
49 
51 {
52 public:
54 
56  {
57  return CompareTxMemPoolEntryByScore()(*b,*a); // Convert to less than
58  }
59 };
60 
61 int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
62 {
63  int64_t nOldTime = pblock->nTime;
64  int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
65 
66  if (nOldTime < nNewTime)
67  pblock->nTime = nNewTime;
68 
69  // Updating time can change work required on testnet:
70  if (consensusParams.fPowAllowMinDifficultyBlocks)
71  pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
72 
73  return nNewTime - nOldTime;
74 }
75 
77  : chainparams(_chainparams)
78 {
79  // Block resource limits
80  // If neither -blockmaxsize or -blockmaxweight is given, limit to DEFAULT_BLOCK_MAX_*
81  // If only one is given, only restrict the specified resource.
82  // If both are given, restrict both.
83  nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT;
84  nBlockMaxSize = DEFAULT_BLOCK_MAX_SIZE;
85  bool fWeightSet = false;
86  if (IsArgSet("-blockmaxweight")) {
87  nBlockMaxWeight = GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
88  nBlockMaxSize = MAX_BLOCK_SERIALIZED_SIZE;
89  fWeightSet = true;
90  }
91  if (IsArgSet("-blockmaxsize")) {
92  nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
93  if (!fWeightSet) {
94  nBlockMaxWeight = nBlockMaxSize * WITNESS_SCALE_FACTOR;
95  }
96  }
97  if (IsArgSet("-blockmintxfee")) {
98  CAmount n = 0;
99  ParseMoney(GetArg("-blockmintxfee", ""), n);
101  } else {
102  blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
103  }
104 
105  // Limit weight to between 4K and MAX_BLOCK_WEIGHT-4K for sanity:
106  nBlockMaxWeight = std::max((unsigned int)4000, std::min((unsigned int)(MAX_BLOCK_WEIGHT-4000), nBlockMaxWeight));
107  // Limit size to between 1K and MAX_BLOCK_SERIALIZED_SIZE-1K for sanity:
108  nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SERIALIZED_SIZE-1000), nBlockMaxSize));
109  // Whether we need to account for byte usage (in addition to weight usage)
110  fNeedSizeAccounting = (nBlockMaxSize < MAX_BLOCK_SERIALIZED_SIZE-1000);
111 }
112 
114 {
115  inBlock.clear();
116 
117  // Reserve space for coinbase tx
118  nBlockSize = 1000;
119  nBlockWeight = 4000;
120  nBlockSigOpsCost = 400;
121  fIncludeWitness = false;
122 
123  // These counters do not include coinbase tx
124  nBlockTx = 0;
125  nFees = 0;
126 
127  lastFewTxs = 0;
128  blockFinished = false;
129 }
130 
131 std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn, bool fMineWitnessTx)
132 {
133  int64_t nTimeStart = GetTimeMicros();
134 
135  resetBlock();
136 
137  pblocktemplate.reset(new CBlockTemplate());
138 
139  if(!pblocktemplate.get())
140  return nullptr;
141  pblock = &pblocktemplate->block; // pointer for convenience
142 
143  // Add dummy coinbase tx as first transaction
144  pblock->vtx.emplace_back();
145  pblocktemplate->vTxFees.push_back(-1); // updated at end
146  pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end
147 
149  CBlockIndex* pindexPrev = chainActive.Tip();
150  nHeight = pindexPrev->nHeight + 1;
151 
153  const int32_t nChainId = consensus.nAuxpowChainId;
154  // FIXME: Active version bits after the always-auxpow fork!
155  // const int32_t nVersion = ComputeBlockVersion(pindexPrev, consensus);
156  const int32_t nVersion = VERSIONBITS_LAST_OLD_BLOCK_VERSION;
157  pblock->SetBaseVersion(nVersion, nChainId);
158  // -regtest only: allow overriding block.nVersion with
159  // -blockversion=N to test forking scenarios
161  pblock->SetBaseVersion(GetArg("-blockversion", pblock->GetBaseVersion()), nChainId);
162 
164  const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
165 
166  nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
167  ? nMedianTimePast
168  : pblock->GetBlockTime();
169 
170  // Decide whether to include witness transactions
171  // This is only needed in case the witness softfork activation is reverted
172  // (which would require a very deep reorganization) or when
173  // -promiscuousmempoolflags is used.
174  // TODO: replace this with a call to main to assess validity of a mempool
175  // transaction (which in most cases can be a no-op).
176  fIncludeWitness = IsWitnessEnabled(pindexPrev, consensus) && fMineWitnessTx;
177 
178  addPriorityTxs();
179  int nPackagesSelected = 0;
180  int nDescendantsUpdated = 0;
181  addPackageTxs(nPackagesSelected, nDescendantsUpdated);
182 
183  int64_t nTime1 = GetTimeMicros();
184 
188 
189  // Create coinbase transaction.
190  CMutableTransaction coinbaseTx;
191  coinbaseTx.vin.resize(1);
192  coinbaseTx.vin[0].prevout.SetNull();
193  coinbaseTx.vout.resize(1);
194  coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
195  coinbaseTx.vout[0].nValue = nFees + GetDogecoinBlockSubsidy(nHeight, consensus, pindexPrev->GetBlockHash(
196 ));
197  coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
198  pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
199  pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, consensus);
200  pblocktemplate->vTxFees[0] = -nFees;
201 
202  uint64_t nSerializeSize = GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION);
203  LogPrintf("CreateNewBlock(): total size: %u block weight: %u txs: %u fees: %ld sigops %d\n", nSerializeSize, GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
204 
205  // Fill in header
206  pblock->hashPrevBlock = pindexPrev->GetBlockHash();
207  UpdateTime(pblock, consensus, pindexPrev);
208  pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensus);
209  pblock->nNonce = 0;
210  pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]);
211 
212  CValidationState state;
213  if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
214  throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
215  }
216  int64_t nTime2 = GetTimeMicros();
217 
218  LogPrint("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));
219 
220  return std::move(pblocktemplate);
221 }
222 
224 {
225  BOOST_FOREACH(CTxMemPool::txiter parent, mempool.GetMemPoolParents(iter))
226  {
227  if (!inBlock.count(parent)) {
228  return true;
229  }
230  }
231  return false;
232 }
233 
235 {
236  for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
237  // Only test txs not already in the block
238  if (inBlock.count(*iit)) {
239  testSet.erase(iit++);
240  }
241  else {
242  iit++;
243  }
244  }
245 }
246 
247 bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost)
248 {
249  // TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
250  if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= nBlockMaxWeight)
251  return false;
252  if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST)
253  return false;
254  return true;
255 }
256 
257 // Perform transaction-level checks before adding to block:
258 // - transaction finality (locktime)
259 // - premature witness (in case segwit transactions are added to mempool before
260 // segwit activation)
261 // - serialized size (in case -blockmaxsize is in use)
263 {
264  uint64_t nPotentialBlockSize = nBlockSize; // only used with fNeedSizeAccounting
265  BOOST_FOREACH (const CTxMemPool::txiter it, package) {
266  if (!IsFinalTx(it->GetTx(), nHeight, nLockTimeCutoff))
267  return false;
268  if (!fIncludeWitness && it->GetTx().HasWitness())
269  return false;
270  if (fNeedSizeAccounting) {
271  uint64_t nTxSize = ::GetSerializeSize(it->GetTx(), SER_NETWORK, PROTOCOL_VERSION);
272  if (nPotentialBlockSize + nTxSize >= nBlockMaxSize) {
273  return false;
274  }
275  nPotentialBlockSize += nTxSize;
276  }
277  }
278  return true;
279 }
280 
282 {
283  if (nBlockWeight + iter->GetTxWeight() >= nBlockMaxWeight) {
284  // If the block is so close to full that no more txs will fit
285  // or if we've tried more than 50 times to fill remaining space
286  // then flag that the block is finished
287  if (nBlockWeight > nBlockMaxWeight - 400 || lastFewTxs > 50) {
288  blockFinished = true;
289  return false;
290  }
291  // Once we're within 4000 weight of a full block, only look at 50 more txs
292  // to try to fill the remaining space.
293  if (nBlockWeight > nBlockMaxWeight - 4000) {
294  lastFewTxs++;
295  }
296  return false;
297  }
298 
299  if (fNeedSizeAccounting) {
300  if (nBlockSize + ::GetSerializeSize(iter->GetTx(), SER_NETWORK, PROTOCOL_VERSION) >= nBlockMaxSize) {
301  if (nBlockSize > nBlockMaxSize - 100 || lastFewTxs > 50) {
302  blockFinished = true;
303  return false;
304  }
305  if (nBlockSize > nBlockMaxSize - 1000) {
306  lastFewTxs++;
307  }
308  return false;
309  }
310  }
311 
312  if (nBlockSigOpsCost + iter->GetSigOpCost() >= MAX_BLOCK_SIGOPS_COST) {
313  // If the block has room for no more sig ops then
314  // flag that the block is finished
315  if (nBlockSigOpsCost > MAX_BLOCK_SIGOPS_COST - 8) {
316  blockFinished = true;
317  return false;
318  }
319  // Otherwise attempt to find another tx with fewer sigops
320  // to put in the block.
321  return false;
322  }
323 
324  // Must check that lock times are still valid
325  // This can be removed once MTP is always enforced
326  // as long as reorgs keep the mempool consistent.
327  if (!IsFinalTx(iter->GetTx(), nHeight, nLockTimeCutoff))
328  return false;
329 
330  return true;
331 }
332 
334 {
335  pblock->vtx.emplace_back(iter->GetSharedTx());
336  pblocktemplate->vTxFees.push_back(iter->GetFee());
337  pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
338  if (fNeedSizeAccounting) {
339  nBlockSize += ::GetSerializeSize(iter->GetTx(), SER_NETWORK, PROTOCOL_VERSION);
340  }
341  nBlockWeight += iter->GetTxWeight();
342  ++nBlockTx;
343  nBlockSigOpsCost += iter->GetSigOpCost();
344  nFees += iter->GetFee();
345  inBlock.insert(iter);
346 
347  bool fPrintPriority = GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
348  if (fPrintPriority) {
349  double dPriority = iter->GetPriority(nHeight);
350  CAmount dummy;
351  mempool.ApplyDeltas(iter->GetTx().GetHash(), dPriority, dummy);
352  LogPrintf("priority %.1f fee %s txid %s\n",
353  dPriority,
354  CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
355  iter->GetTx().GetHash().ToString());
356  }
357 }
358 
360  indexed_modified_transaction_set &mapModifiedTx)
361 {
362  int nDescendantsUpdated = 0;
363  BOOST_FOREACH(const CTxMemPool::txiter it, alreadyAdded) {
364  CTxMemPool::setEntries descendants;
365  mempool.CalculateDescendants(it, descendants);
366  // Insert all descendants (not yet in block) into the modified set
367  BOOST_FOREACH(CTxMemPool::txiter desc, descendants) {
368  if (alreadyAdded.count(desc))
369  continue;
370  ++nDescendantsUpdated;
371  modtxiter mit = mapModifiedTx.find(desc);
372  if (mit == mapModifiedTx.end()) {
373  CTxMemPoolModifiedEntry modEntry(desc);
374  modEntry.nSizeWithAncestors -= it->GetTxSize();
375  modEntry.nModFeesWithAncestors -= it->GetModifiedFee();
376  modEntry.nSigOpCostWithAncestors -= it->GetSigOpCost();
377  mapModifiedTx.insert(modEntry);
378  } else {
379  mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
380  }
381  }
382  }
383  return nDescendantsUpdated;
384 }
385 
386 // Skip entries in mapTx that are already in a block or are present
387 // in mapModifiedTx (which implies that the mapTx ancestor state is
388 // stale due to ancestor inclusion in the block)
389 // Also skip transactions that we've already failed to add. This can happen if
390 // we consider a transaction in mapModifiedTx and it fails: we can then
391 // potentially consider it again while walking mapTx. It's currently
392 // guaranteed to fail again, but as a belt-and-suspenders check we put it in
393 // failedTx and avoid re-evaluation, since the re-evaluation would be using
394 // cached size/sigops/fee values that are not actually correct.
396 {
397  assert (it != mempool.mapTx.end());
398  if (mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it))
399  return true;
400  return false;
401 }
402 
403 void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, CTxMemPool::txiter entry, std::vector<CTxMemPool::txiter>& sortedEntries)
404 {
405  // Sort package by ancestor count
406  // If a transaction A depends on transaction B, then A's ancestor count
407  // must be greater than B's. So this is sufficient to validly order the
408  // transactions for block inclusion.
409  sortedEntries.clear();
410  sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
411  std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
412 }
413 
414 // This transaction selection algorithm orders the mempool based
415 // on feerate of a transaction including all unconfirmed ancestors.
416 // Since we don't remove transactions from the mempool as we select them
417 // for block inclusion, we need an alternate method of updating the feerate
418 // of a transaction with its not-yet-selected ancestors as we go.
419 // This is accomplished by walking the in-mempool descendants of selected
420 // transactions and storing a temporary modified state in mapModifiedTxs.
421 // Each time through the loop, we compare the best transaction in
422 // mapModifiedTxs with the next transaction in the mempool to decide what
423 // transaction package to work on next.
424 void BlockAssembler::addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated)
425 {
426  // mapModifiedTx will store sorted packages after they are modified
427  // because some of their txs are already in the block
428  indexed_modified_transaction_set mapModifiedTx;
429  // Keep track of entries that failed inclusion, to avoid duplicate work
430  CTxMemPool::setEntries failedTx;
431 
432  // Start by adding all descendants of previously added txs to mapModifiedTx
433  // and modifying them for their already included ancestors
434  UpdatePackagesForAdded(inBlock, mapModifiedTx);
435 
436  CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin();
437  CTxMemPool::txiter iter;
438 
439  // Limit the number of attempts to add transactions to the block when it is
440  // close to full; this is just a simple heuristic to finish quickly if the
441  // mempool has a lot of entries.
442  const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
443  int64_t nConsecutiveFailed = 0;
444 
445  while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty())
446  {
447  // First try to find a new transaction in mapTx to evaluate.
448  if (mi != mempool.mapTx.get<ancestor_score>().end() &&
449  SkipMapTxEntry(mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) {
450  ++mi;
451  continue;
452  }
453 
454  // Now that mi is not stale, determine which transaction to evaluate:
455  // the next entry from mapTx, or the best from mapModifiedTx?
456  bool fUsingModified = false;
457 
458  modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
459  if (mi == mempool.mapTx.get<ancestor_score>().end()) {
460  // We're out of entries in mapTx; use the entry from mapModifiedTx
461  iter = modit->iter;
462  fUsingModified = true;
463  } else {
464  // Try to compare the mapTx entry to the mapModifiedTx entry
465  iter = mempool.mapTx.project<0>(mi);
466  if (modit != mapModifiedTx.get<ancestor_score>().end() &&
468  // The best entry in mapModifiedTx has higher score
469  // than the one from mapTx.
470  // Switch which transaction (package) to consider
471  iter = modit->iter;
472  fUsingModified = true;
473  } else {
474  // Either no entry in mapModifiedTx, or it's worse than mapTx.
475  // Increment mi for the next loop iteration.
476  ++mi;
477  }
478  }
479 
480  // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
481  // contain anything that is inBlock.
482  assert(!inBlock.count(iter));
483 
484  uint64_t packageSize = iter->GetSizeWithAncestors();
485  CAmount packageFees = iter->GetModFeesWithAncestors();
486  int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
487  if (fUsingModified) {
488  packageSize = modit->nSizeWithAncestors;
489  packageFees = modit->nModFeesWithAncestors;
490  packageSigOpsCost = modit->nSigOpCostWithAncestors;
491  }
492 
493  if (packageFees < blockMinFeeRate.GetFee(packageSize)) {
494  // Everything else we might consider has a lower fee rate
495  return;
496  }
497 
498  if (!TestPackage(packageSize, packageSigOpsCost)) {
499  if (fUsingModified) {
500  // Since we always look at the best entry in mapModifiedTx,
501  // we must erase failed entries so that we can consider the
502  // next best entry on the next loop iteration
503  mapModifiedTx.get<ancestor_score>().erase(modit);
504  failedTx.insert(iter);
505  }
506 
507  ++nConsecutiveFailed;
508 
509  if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight >
510  nBlockMaxWeight - 4000) {
511  // Give up if we're close to full and haven't succeeded in a while
512  break;
513  }
514  continue;
515  }
516 
517  CTxMemPool::setEntries ancestors;
518  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
519  std::string dummy;
520  mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
521 
522  onlyUnconfirmed(ancestors);
523  ancestors.insert(iter);
524 
525  // Test if all tx's are Final
526  if (!TestPackageTransactions(ancestors)) {
527  if (fUsingModified) {
528  mapModifiedTx.get<ancestor_score>().erase(modit);
529  failedTx.insert(iter);
530  }
531  continue;
532  }
533 
534  // This transaction will make it in; reset the failed counter.
535  nConsecutiveFailed = 0;
536 
537  // Package can be added. Sort the entries in a valid order.
538  std::vector<CTxMemPool::txiter> sortedEntries;
539  SortForBlock(ancestors, iter, sortedEntries);
540 
541  for (size_t i=0; i<sortedEntries.size(); ++i) {
542  AddToBlock(sortedEntries[i]);
543  // Erase from the modified set, if present
544  mapModifiedTx.erase(sortedEntries[i]);
545  }
546 
547  ++nPackagesSelected;
548 
549  // Update transactions that depend on each of these
550  nDescendantsUpdated += UpdatePackagesForAdded(ancestors, mapModifiedTx);
551  }
552 }
553 
555 {
556  // How much of the block should be dedicated to high-priority transactions,
557  // included regardless of the fees they pay
558  unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
559  nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
560 
561  if (nBlockPrioritySize == 0) {
562  return;
563  }
564 
565  bool fSizeAccounting = fNeedSizeAccounting;
566  fNeedSizeAccounting = true;
567 
568  // This vector will be sorted into a priority queue:
569  std::vector<TxCoinAgePriority> vecPriority;
570  TxCoinAgePriorityCompare pricomparer;
571  std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash> waitPriMap;
572  typedef std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash>::iterator waitPriIter;
573  double actualPriority = -1;
574 
575  vecPriority.reserve(mempool.mapTx.size());
576  for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
577  mi != mempool.mapTx.end(); ++mi)
578  {
579  double dPriority = mi->GetPriority(nHeight);
580  CAmount dummy;
581  mempool.ApplyDeltas(mi->GetTx().GetHash(), dPriority, dummy);
582  vecPriority.push_back(TxCoinAgePriority(dPriority, mi));
583  }
584  std::make_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
585 
586  CTxMemPool::txiter iter;
587  while (!vecPriority.empty() && !blockFinished) { // add a tx from priority queue to fill the blockprioritysize
588  iter = vecPriority.front().second;
589  actualPriority = vecPriority.front().first;
590  std::pop_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
591  vecPriority.pop_back();
592 
593  // If tx already in block, skip
594  if (inBlock.count(iter)) {
595  assert(false); // shouldn't happen for priority txs
596  continue;
597  }
598 
599  // cannot accept witness transactions into a non-witness block
600  if (!fIncludeWitness && iter->GetTx().HasWitness())
601  continue;
602 
603  // If tx is dependent on other mempool txs which haven't yet been included
604  // then put it in the waitSet
605  if (isStillDependent(iter)) {
606  waitPriMap.insert(std::make_pair(iter, actualPriority));
607  continue;
608  }
609 
610  // If this tx fits in the block add it, otherwise keep looping
611  if (TestForBlock(iter)) {
612  AddToBlock(iter);
613 
614  // If now that this txs is added we've surpassed our desired priority size
615  // or have dropped below the AllowFreeThreshold, then we're done adding priority txs
616  if (nBlockSize >= nBlockPrioritySize || !AllowFree(actualPriority)) {
617  break;
618  }
619 
620  // This tx was successfully added, so
621  // add transactions that depend on this one to the priority queue to try again
622  BOOST_FOREACH(CTxMemPool::txiter child, mempool.GetMemPoolChildren(iter))
623  {
624  waitPriIter wpiter = waitPriMap.find(child);
625  if (wpiter != waitPriMap.end()) {
626  vecPriority.push_back(TxCoinAgePriority(wpiter->second,child));
627  std::push_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
628  waitPriMap.erase(wpiter);
629  }
630  }
631  }
632  }
633  fNeedSizeAccounting = fSizeAccounting;
634 }
635 
636 void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
637 {
638  // Update nExtraNonce
639  static uint256 hashPrevBlock;
640  if (hashPrevBlock != pblock->hashPrevBlock)
641  {
642  nExtraNonce = 0;
643  hashPrevBlock = pblock->hashPrevBlock;
644  }
645  ++nExtraNonce;
646  unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
647  CMutableTransaction txCoinbase(*pblock->vtx[0]);
648  txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
649  assert(txCoinbase.vin[0].scriptSig.size() <= 100);
650 
651  pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
652  pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
653 }
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:15
int64_t GetBlockWeight(const CBlock &block)
Compute the consensus-critical block weight (see BIP 141).
Definition: block.cpp:43
int64_t nLockTimeCutoff
Definition: miner.h:158
bool TestForBlock(CTxMemPool::txiter iter)
Test if tx will still "fit" in the block.
Definition: miner.cpp:281
uint64_t nBlockWeight
Definition: miner.h:149
void AddToBlock(CTxMemPool::txiter iter)
Add a tx to the block.
Definition: miner.cpp:333
CTxMemPool::setEntries inBlock
Definition: miner.h:154
bool isStillDependent(CTxMemPool::txiter iter)
Test if tx still has unconfirmed parents not yet in block.
Definition: miner.cpp:223
bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost)
Test if a new package would "fit" in the block.
Definition: miner.cpp:247
int lastFewTxs
Definition: miner.h:162
unsigned int nBlockMaxSize
Definition: miner.h:144
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:403
void onlyUnconfirmed(CTxMemPool::setEntries &testSet)
Remove confirmed (inBlock) entries from given set.
Definition: miner.cpp:234
CFeeRate blockMinFeeRate
Definition: miner.h:146
bool TestPackageTransactions(const CTxMemPool::setEntries &package)
Perform checks on each transaction in a package: locktime, premature-witness, serialized size (if nec...
Definition: miner.cpp:262
uint64_t nBlockTx
Definition: miner.h:151
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn, bool fMineWitnessTx)
Construct a new block template with coinbase to scriptPubKeyIn.
Definition: miner.cpp:131
uint64_t nBlockSize
Definition: miner.h:150
BlockAssembler(const CChainParams &chainparams)
Definition: miner.cpp:76
bool fNeedSizeAccounting
Definition: miner.h:145
bool fIncludeWitness
Definition: miner.h:143
CAmount nFees
Definition: miner.h:153
CBlock * pblock
Definition: miner.h:140
void resetBlock()
Clear the block's state and prepare for assembling a new block.
Definition: miner.cpp:113
std::unique_ptr< CBlockTemplate > pblocktemplate
Definition: miner.h:138
const CChainParams & chainparams
Definition: miner.h:159
bool blockFinished
Definition: miner.h:163
unsigned int nBlockMaxWeight
Definition: miner.h:144
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's cache...
Definition: miner.cpp:395
void addPriorityTxs()
Add transactions based on tx "priority".
Definition: miner.cpp:554
int nHeight
Definition: miner.h:157
void addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated)
Add transactions based on feerate including unconfirmed ancestors Increments nPackagesSelected / nDes...
Definition: miner.cpp:424
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:359
uint64_t nBlockSigOpsCost
Definition: miner.h:152
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:25
Definition: block.h:67
std::vector< CTransactionRef > vtx
Definition: block.h:70
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:158
uint256 GetBlockHash() const
Definition: chain.h:268
int64_t GetMedianTimePast() const
Definition: chain.h:285
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:170
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or NULL if none.
Definition: chain.h:443
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:47
bool MineBlocksOnDemand() const
Make miner stop after a block is found.
Definition: chainparams.h:76
const Consensus::Params & GetConsensus(uint32_t nTargetHeight) const
Definition: chainparams.h:59
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: amount.h:38
CAmount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
Definition: amount.cpp:23
std::string ToString() const
Definition: amount.cpp:45
uint32_t nNonce
Definition: pureheader.h:34
int32_t GetBaseVersion() const
Extract the base version (without modifiers and chain ID).
Definition: pureheader.h:88
uint256 hashPrevBlock
Definition: pureheader.h:30
uint32_t nTime
Definition: pureheader.h:32
void SetBaseVersion(int32_t nBaseVersion, int32_t nChainId)
Set the base version (apart from chain ID and auxpow flag) to the one given.
Definition: pureheader.cpp:13
int64_t GetBlockTime() const
Definition: pureheader.h:73
uint256 hashMerkleRoot
Definition: pureheader.h:31
uint32_t nBits
Definition: pureheader.h:33
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:377
const setEntries & GetMemPoolChildren(txiter entry) const
Definition: txmempool.cpp:1068
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:173
void ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta) const
Definition: txmempool.cpp:957
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:494
indexed_transaction_set::nth_index< 0 >::type::iterator txiter
Definition: txmempool.h:486
const setEntries & GetMemPoolParents(txiter entry) const
Definition: txmempool.cpp:1060
CCriticalSection cs
Definition: txmempool.h:483
indexed_transaction_set mapTx
Definition: txmempool.h:484
void CalculateDescendants(txiter it, setEntries &setDescendants)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:485
Capture information about block/transaction validation.
Definition: validation.h:22
Sort by score of entry ((fee+delta)/size) in descending order.
Definition: txmempool.h:267
bool operator()(const CTxMemPool::txiter a, const CTxMemPool::txiter b)
Definition: miner.cpp:55
ScoreCompare()
Definition: miner.cpp:53
256-bit opaque blob.
Definition: uint256.h:123
@ LOCKTIME_MEDIAN_TIME_PAST
Definition: consensus.h:26
CAmount GetDogecoinBlockSubsidy(int nHeight, const Consensus::Params &consensusParams, uint256 prevHash)
Definition: dogecoin.cpp:125
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:158
uint64_t nLastBlockTx
Definition: miner.cpp:46
void IncrementExtraNonce(CBlock *pblock, const CBlockIndex *pindexPrev, unsigned int &nExtraNonce)
Modify the extranonce in a block.
Definition: miner.cpp:636
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:61
uint64_t nLastBlockWeight
Definition: miner.cpp:48
uint64_t nLastBlockSize
Definition: miner.cpp:47
indexed_modified_transaction_set::nth_index< 0 >::type::iterator modtxiter
Definition: miner.h:116
indexed_modified_transaction_set::index< ancestor_score >::type::iterator modtxscoreiter
Definition: miner.h:117
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:114
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock, const Consensus::Params &params)
Definition: pow.cpp:32
@ OP_0
Definition: script.h:47
@ SER_NETWORK
Definition: serialize.h:146
size_t GetSerializeSize(const T &t, int nType, int nVersion=0)
Definition: serialize.h:948
A mutable version of CTransaction.
Definition: transaction.h:413
std::vector< CTxOut > vout
Definition: transaction.h:416
std::vector< CTxIn > vin
Definition: transaction.h:415
Definition: miner.h:37
uint64_t nSizeWithAncestors
Definition: miner.h:47
CAmount nModFeesWithAncestors
Definition: miner.h:48
int64_t nSigOpCostWithAncestors
Definition: miner.h:49
Definition: miner.h:75
Parameters that influence chain consensus.
Definition: params.h:39
int32_t nAuxpowChainId
Auxpow parameters.
Definition: params.h:79
bool fPowAllowMinDifficultyBlocks
Definition: params.h:64
#define LOCK2(cs1, cs2)
Definition: sync.h:178
int64_t GetAdjustedTime()
Definition: timedata.cpp:36
#define strprintf
Definition: tinyformat.h:1047
bool AllowFree(double dPriority)
Definition: txmempool.h:38
std::pair< double, CTxMemPool::txiter > TxCoinAgePriority
Definition: txmempool.h:724
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:395
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
Definition: util.cpp:411
bool IsArgSet(const std::string &strArg)
Return true if the given argument has been manually set.
Definition: util.cpp:389
#define LogPrint(category,...)
Definition: util.h:76
#define LogPrintf(...)
Definition: util.h:82
bool ParseMoney(const string &str, CAmount &nRet)
int64_t GetTimeMicros()
Definition: utiltime.cpp:41
CCriticalSection cs_main
Global state.
Definition: validation.cpp:61
CTxMemPool mempool(::minRelayTxFee)
CScript COINBASE_FLAGS
Constant stuff for coinbase transactions we create:
Definition: validation.cpp:99
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,...
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't call for mined blocks...
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
Definition: validation.cpp:567
bool IsWitnessEnabled(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Check whether witness commitments are required for block.
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Count ECDSA signature operations the old-fashioned (pre-0.6) way.
Definition: validation.cpp:454
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:64
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: validation.cpp:237