Bitcoin ABC  0.22.12
P2P Digital Currency
miner.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 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 <config.h>
13 #include <consensus/activation.h>
14 #include <consensus/consensus.h>
15 #include <consensus/merkle.h>
16 #include <consensus/tx_verify.h>
17 #include <consensus/validation.h>
18 #include <minerfund.h>
19 #include <net.h>
20 #include <policy/policy.h>
21 #include <policy/settings.h>
22 #include <pow/pow.h>
23 #include <primitives/transaction.h>
24 #include <timedata.h>
25 #include <util/moneystr.h>
26 #include <util/system.h>
27 #include <validation.h>
28 
29 #include <algorithm>
30 #include <utility>
31 
32 int64_t UpdateTime(CBlockHeader *pblock, const CChainParams &chainParams,
33  const CBlockIndex *pindexPrev) {
34  int64_t nOldTime = pblock->nTime;
35  int64_t nNewTime =
36  std::max(pindexPrev->GetMedianTimePast() + 1, GetAdjustedTime());
37 
38  if (nOldTime < nNewTime) {
39  pblock->nTime = nNewTime;
40  }
41 
42  // Updating time can change work required on testnet:
43  if (chainParams.GetConsensus().fPowAllowMinDifficultyBlocks) {
44  pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainParams);
45  }
46 
47  return nNewTime - nOldTime;
48 }
49 
53 }
54 
56  : nExcessiveBlockSize(DEFAULT_MAX_BLOCK_SIZE),
57  nMaxGeneratedBlockSize(DEFAULT_MAX_GENERATED_BLOCK_SIZE),
58  blockMinFeeRate(DEFAULT_BLOCK_MIN_TX_FEE_PER_KB) {}
59 
61  const CTxMemPool &mempool,
62  const Options &options)
63  : chainParams(params), m_mempool(mempool) {
65  // Limit size to between 1K and options.nExcessiveBlockSize -1K for sanity:
66  nMaxGeneratedBlockSize = std::max<uint64_t>(
67  1000, std::min<uint64_t>(options.nExcessiveBlockSize - 1000,
68  options.nMaxGeneratedBlockSize));
69  // Calculate the max consensus sigchecks for this block.
70  auto nMaxBlockSigChecks = GetMaxBlockSigChecksCount(nMaxGeneratedBlockSize);
71  // Allow the full amount of signature check operations in lieu of a separate
72  // config option. (We are mining relayed transactions with validity cached
73  // by everyone else, and so the block will propagate quickly, regardless of
74  // how many sigchecks it contains.)
75  nMaxGeneratedBlockSigChecks = nMaxBlockSigChecks;
76 }
77 
79  // Block resource limits
80  // If -blockmaxsize is not given, limit to DEFAULT_MAX_GENERATED_BLOCK_SIZE
81  // If only one is given, only restrict the specified resource.
82  // If both are given, restrict both.
84 
85  options.nExcessiveBlockSize = config.GetMaxBlockSize();
86 
87  if (gArgs.IsArgSet("-blockmaxsize")) {
88  options.nMaxGeneratedBlockSize =
90  }
91 
92  Amount n = Amount::zero();
93  if (gArgs.IsArgSet("-blockmintxfee") &&
94  ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n)) {
95  options.blockMinFeeRate = CFeeRate(n);
96  }
97 
98  return options;
99 }
100 
101 BlockAssembler::BlockAssembler(const Config &config, const CTxMemPool &mempool)
102  : BlockAssembler(config.GetChainParams(), mempool, DefaultOptions(config)) {
103 }
104 
106  inBlock.clear();
107 
108  // Reserve space for coinbase tx.
109  nBlockSize = 1000;
110  nBlockSigOps = 100;
111 
112  // These counters do not include coinbase tx.
113  nBlockTx = 0;
114  nFees = Amount::zero();
115 }
116 
117 std::optional<int64_t> BlockAssembler::m_last_block_num_txs{std::nullopt};
118 std::optional<int64_t> BlockAssembler::m_last_block_size{std::nullopt};
119 
120 std::unique_ptr<CBlockTemplate>
121 BlockAssembler::CreateNewBlock(const CScript &scriptPubKeyIn) {
122  int64_t nTimeStart = GetTimeMicros();
123 
124  resetBlock();
125 
126  pblocktemplate.reset(new CBlockTemplate());
127  if (!pblocktemplate.get()) {
128  return nullptr;
129  }
130 
131  // Pointer for convenience.
132  pblock = &pblocktemplate->block;
133 
134  // Add dummy coinbase tx as first transaction. It is updated at the end.
135  pblocktemplate->entries.emplace_back(CTransactionRef(), -SATOSHI, -1);
136 
138  CBlockIndex *pindexPrev = ::ChainActive().Tip();
139  assert(pindexPrev != nullptr);
140  nHeight = pindexPrev->nHeight + 1;
141 
142  const Consensus::Params &consensusParams = chainParams.GetConsensus();
143 
144  pblock->nVersion = ComputeBlockVersion(pindexPrev, consensusParams);
145  // -regtest only: allow overriding block.nVersion with
146  // -blockversion=N to test forking scenarios
148  pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion);
149  }
150 
152  nMedianTimePast = pindexPrev->GetMedianTimePast();
156  : pblock->GetBlockTime();
157 
158  int nPackagesSelected = 0;
159  int nDescendantsUpdated = 0;
160  addPackageTxs(nPackagesSelected, nDescendantsUpdated);
161 
162  if (IsMagneticAnomalyEnabled(consensusParams, pindexPrev)) {
163  // If magnetic anomaly is enabled, we make sure transaction are
164  // canonically ordered.
165  std::sort(std::begin(pblocktemplate->entries) + 1,
166  std::end(pblocktemplate->entries),
167  [](const CBlockTemplateEntry &a, const CBlockTemplateEntry &b)
168  -> bool { return a.tx->GetId() < b.tx->GetId(); });
169  }
170 
171  // Copy all the transactions refs into the block
172  pblock->vtx.reserve(pblocktemplate->entries.size());
173  for (const CBlockTemplateEntry &entry : pblocktemplate->entries) {
174  pblock->vtx.push_back(entry.tx);
175  }
176 
177  int64_t nTime1 = GetTimeMicros();
178 
181 
182  // Create coinbase transaction.
183  CMutableTransaction coinbaseTx;
184  coinbaseTx.vin.resize(1);
185  coinbaseTx.vin[0].prevout = COutPoint();
186  coinbaseTx.vout.resize(1);
187  coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
188  coinbaseTx.vout[0].nValue =
189  nFees + GetBlockSubsidy(nHeight, consensusParams);
190  coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
191 
192  const std::vector<CTxDestination> whitelisted =
193  GetMinerFundWhitelist(consensusParams, pindexPrev);
194  if (!whitelisted.empty()) {
195  const Amount fund = GetMinerFundAmount(coinbaseTx.vout[0].nValue);
196  coinbaseTx.vout[0].nValue -= fund;
197  coinbaseTx.vout.emplace_back(fund,
198  GetScriptForDestination(whitelisted[0]));
199  }
200 
201  // Make sure the coinbase is big enough.
202  uint64_t coinbaseSize = ::GetSerializeSize(coinbaseTx, PROTOCOL_VERSION);
203  if (coinbaseSize < MIN_TX_SIZE) {
204  coinbaseTx.vin[0].scriptSig
205  << std::vector<uint8_t>(MIN_TX_SIZE - coinbaseSize - 1);
206  }
207 
208  pblocktemplate->entries[0].tx = MakeTransactionRef(coinbaseTx);
209  pblocktemplate->entries[0].fees = -1 * nFees;
210  pblock->vtx[0] = pblocktemplate->entries[0].tx;
211 
212  uint64_t nSerializeSize = GetSerializeSize(*pblock, PROTOCOL_VERSION);
213 
214  LogPrintf("CreateNewBlock(): total size: %u txs: %u fees: %ld sigops %d\n",
215  nSerializeSize, nBlockTx, nFees, nBlockSigOps);
216 
217  // Fill in header.
218  pblock->hashPrevBlock = pindexPrev->GetBlockHash();
219  UpdateTime(pblock, chainParams, pindexPrev);
221  pblock->nNonce = 0;
222  pblocktemplate->entries[0].sigOpCount = 0;
223 
224  BlockValidationState state;
225  if (!TestBlockValidity(state, chainParams, *pblock, pindexPrev,
227  .withCheckPoW(false)
228  .withCheckMerkleRoot(false))) {
229  throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s",
230  __func__, state.ToString()));
231  }
232  int64_t nTime2 = GetTimeMicros();
233 
235  "CreateNewBlock() packages: %.2fms (%d packages, %d updated "
236  "descendants), validity: %.2fms (total %.2fms)\n",
237  0.001 * (nTime1 - nTimeStart), nPackagesSelected,
238  nDescendantsUpdated, 0.001 * (nTime2 - nTime1),
239  0.001 * (nTime2 - nTimeStart));
240 
241  return std::move(pblocktemplate);
242 }
243 
245  for (CTxMemPool::setEntries::iterator iit = testSet.begin();
246  iit != testSet.end();) {
247  // Only test txs not already in the block.
248  if (inBlock.count(*iit)) {
249  testSet.erase(iit++);
250  } else {
251  iit++;
252  }
253  }
254 }
255 
256 bool BlockAssembler::TestPackage(uint64_t packageSize,
257  int64_t packageSigOps) const {
258  auto blockSizeWithPackage = nBlockSize + packageSize;
259  if (blockSizeWithPackage >= nMaxGeneratedBlockSize) {
260  return false;
261  }
262 
263  if (nBlockSigOps + packageSigOps >= nMaxGeneratedBlockSigChecks) {
264  return false;
265  }
266 
267  return true;
268 }
269 
276  const CTxMemPool::setEntries &package) {
277  uint64_t nPotentialBlockSize = nBlockSize;
278  for (CTxMemPool::txiter it : package) {
279  TxValidationState state;
281  state, nHeight, nLockTimeCutoff,
282  nMedianTimePast)) {
283  return false;
284  }
285 
286  uint64_t nTxSize = ::GetSerializeSize(it->GetTx(), PROTOCOL_VERSION);
287  if (nPotentialBlockSize + nTxSize >= nMaxGeneratedBlockSize) {
288  return false;
289  }
290 
291  nPotentialBlockSize += nTxSize;
292  }
293 
294  return true;
295 }
296 
298  pblocktemplate->entries.emplace_back(iter->GetSharedTx(), iter->GetFee(),
299  iter->GetSigOpCount());
300  nBlockSize += iter->GetTxSize();
301  ++nBlockTx;
302  nBlockSigOps += iter->GetSigOpCount();
303  nFees += iter->GetFee();
304  inBlock.insert(iter);
305 
306  bool fPrintPriority =
307  gArgs.GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
308  if (fPrintPriority) {
309  LogPrintf(
310  "fee %s txid %s\n",
311  CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
312  iter->GetTx().GetId().ToString());
313  }
314 }
315 
317  const CTxMemPool::setEntries &alreadyAdded,
318  indexed_modified_transaction_set &mapModifiedTx) {
319  int nDescendantsUpdated = 0;
320  for (CTxMemPool::txiter it : alreadyAdded) {
321  CTxMemPool::setEntries descendants;
322  m_mempool.CalculateDescendants(it, descendants);
323  // Insert all descendants (not yet in block) into the modified set.
324  for (CTxMemPool::txiter desc : descendants) {
325  if (alreadyAdded.count(desc)) {
326  continue;
327  }
328 
329  ++nDescendantsUpdated;
330  modtxiter mit = mapModifiedTx.find(desc);
331  if (mit == mapModifiedTx.end()) {
332  CTxMemPoolModifiedEntry modEntry(desc);
333  modEntry.nSizeWithAncestors -= it->GetTxSize();
334  modEntry.nModFeesWithAncestors -= it->GetModifiedFee();
335  modEntry.nSigOpCountWithAncestors -= it->GetSigOpCount();
336  mapModifiedTx.insert(modEntry);
337  } else {
338  mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
339  }
340  }
341  }
342 
343  return nDescendantsUpdated;
344 }
345 
346 // Skip entries in mapTx that are already in a block or are present in
347 // mapModifiedTx (which implies that the mapTx ancestor state is stale due to
348 // ancestor inclusion in the block). Also skip transactions that we've already
349 // failed to add. This can happen if we consider a transaction in mapModifiedTx
350 // and it fails: we can then potentially consider it again while walking mapTx.
351 // It's currently guaranteed to fail again, but as a belt-and-suspenders check
352 // we put it in failedTx and avoid re-evaluation, since the re-evaluation would
353 // be using cached size/sigops/fee values that are not actually correct.
356  CTxMemPool::setEntries &failedTx) {
357  assert(it != m_mempool.mapTx.end());
358  return mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it);
359 }
360 
362  const CTxMemPool::setEntries &package,
363  std::vector<CTxMemPool::txiter> &sortedEntries) {
364  // Sort package by ancestor count. If a transaction A depends on transaction
365  // B, then A's ancestor count must be greater than B's. So this is
366  // sufficient to validly order the transactions for block inclusion.
367  sortedEntries.clear();
368  sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
369  std::sort(sortedEntries.begin(), sortedEntries.end(),
371 }
372 
380 void BlockAssembler::addPackageTxs(int &nPackagesSelected,
381  int &nDescendantsUpdated) {
382  // selection algorithm orders the mempool based on feerate of a
383  // transaction including all unconfirmed ancestors. Since we don't remove
384  // transactions from the mempool as we select them for block inclusion, we
385  // need an alternate method of updating the feerate of a transaction with
386  // its not-yet-selected ancestors as we go. This is accomplished by
387  // walking the in-mempool descendants of selected transactions and storing
388  // a temporary modified state in mapModifiedTxs. Each time through the
389  // loop, we compare the best transaction in mapModifiedTxs with the next
390  // transaction in the mempool to decide what transaction package to work
391  // on next.
392 
393  // mapModifiedTx will store sorted packages after they are modified because
394  // some of their txs are already in the block.
395  indexed_modified_transaction_set mapModifiedTx;
396  // Keep track of entries that failed inclusion, to avoid duplicate work.
397  CTxMemPool::setEntries failedTx;
398 
399  // Start by adding all descendants of previously added txs to mapModifiedTx
400  // and modifying them for their already included ancestors.
401  UpdatePackagesForAdded(inBlock, mapModifiedTx);
402 
403  CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator
404  mi = m_mempool.mapTx.get<ancestor_score>().begin();
405  CTxMemPool::txiter iter;
406 
407  // Limit the number of attempts to add transactions to the block when it is
408  // close to full; this is just a simple heuristic to finish quickly if the
409  // mempool has a lot of entries.
410  const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
411  int64_t nConsecutiveFailed = 0;
412 
413  while (mi != m_mempool.mapTx.get<ancestor_score>().end() ||
414  !mapModifiedTx.empty()) {
415  // First try to find a new transaction in mapTx to evaluate.
416  if (mi != m_mempool.mapTx.get<ancestor_score>().end() &&
417  SkipMapTxEntry(m_mempool.mapTx.project<0>(mi), mapModifiedTx,
418  failedTx)) {
419  ++mi;
420  continue;
421  }
422 
423  // Now that mi is not stale, determine which transaction to evaluate:
424  // the next entry from mapTx, or the best from mapModifiedTx?
425  bool fUsingModified = false;
426 
427  modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
428  if (mi == m_mempool.mapTx.get<ancestor_score>().end()) {
429  // We're out of entries in mapTx; use the entry from mapModifiedTx
430  iter = modit->iter;
431  fUsingModified = true;
432  } else {
433  // Try to compare the mapTx entry to the mapModifiedTx entry.
434  iter = m_mempool.mapTx.project<0>(mi);
435  if (modit != mapModifiedTx.get<ancestor_score>().end() &&
437  *modit, CTxMemPoolModifiedEntry(iter))) {
438  // The best entry in mapModifiedTx has higher score than the one
439  // from mapTx. Switch which transaction (package) to consider
440  iter = modit->iter;
441  fUsingModified = true;
442  } else {
443  // Either no entry in mapModifiedTx, or it's worse than mapTx.
444  // Increment mi for the next loop iteration.
445  ++mi;
446  }
447  }
448 
449  // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
450  // contain anything that is inBlock.
451  assert(!inBlock.count(iter));
452 
453  uint64_t packageSize = iter->GetSizeWithAncestors();
454  Amount packageFees = iter->GetModFeesWithAncestors();
455  int64_t packageSigOps = iter->GetSigOpCountWithAncestors();
456  if (fUsingModified) {
457  packageSize = modit->nSizeWithAncestors;
458  packageFees = modit->nModFeesWithAncestors;
459  packageSigOps = modit->nSigOpCountWithAncestors;
460  }
461 
462  if (packageFees < blockMinFeeRate.GetFee(packageSize)) {
463  // Don't include this package, but don't stop yet because something
464  // else we might consider may have a sufficient fee rate (since txes
465  // are ordered by virtualsize feerate, not actual feerate).
466  if (fUsingModified) {
467  // Since we always look at the best entry in mapModifiedTx, we
468  // must erase failed entries so that we can consider the next
469  // best entry on the next loop iteration
470  mapModifiedTx.get<ancestor_score>().erase(modit);
471  failedTx.insert(iter);
472  }
473  continue;
474  }
475 
476  // The following must not use virtual size since TestPackage relies on
477  // having an accurate call to
478  // GetMaxBlockSigOpsCount(blockSizeWithPackage).
479  if (!TestPackage(packageSize, packageSigOps)) {
480  if (fUsingModified) {
481  // Since we always look at the best entry in mapModifiedTx, we
482  // must erase failed entries so that we can consider the next
483  // best entry on the next loop iteration
484  mapModifiedTx.get<ancestor_score>().erase(modit);
485  failedTx.insert(iter);
486  }
487 
488  ++nConsecutiveFailed;
489 
490  if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES &&
492  // Give up if we're close to full and haven't succeeded in a
493  // while.
494  break;
495  }
496 
497  continue;
498  }
499 
500  CTxMemPool::setEntries ancestors;
501  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
502  std::string dummy;
503  m_mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit,
504  nNoLimit, nNoLimit, nNoLimit, dummy,
505  false);
506 
507  onlyUnconfirmed(ancestors);
508  ancestors.insert(iter);
509 
510  // Test if all tx's are Final.
511  if (!TestPackageTransactions(ancestors)) {
512  if (fUsingModified) {
513  mapModifiedTx.get<ancestor_score>().erase(modit);
514  failedTx.insert(iter);
515  }
516  continue;
517  }
518 
519  // This transaction will make it in; reset the failed counter.
520  nConsecutiveFailed = 0;
521 
522  // Package can be added. Sort the entries in a valid order.
523  std::vector<CTxMemPool::txiter> sortedEntries;
524  SortForBlock(ancestors, sortedEntries);
525 
526  for (auto &entry : sortedEntries) {
527  AddToBlock(entry);
528  // Erase from the modified set, if present
529  mapModifiedTx.erase(entry);
530  }
531 
532  ++nPackagesSelected;
533 
534  // Update transactions that depend on each of these
535  nDescendantsUpdated += UpdatePackagesForAdded(ancestors, mapModifiedTx);
536  }
537 }
538 
539 static const std::vector<uint8_t>
540 getExcessiveBlockSizeSig(uint64_t nExcessiveBlockSize) {
541  std::string cbmsg = "/EB" + getSubVersionEB(nExcessiveBlockSize) + "/";
542  std::vector<uint8_t> vec(cbmsg.begin(), cbmsg.end());
543  return vec;
544 }
545 
546 void IncrementExtraNonce(CBlock *pblock, const CBlockIndex *pindexPrev,
547  uint64_t nExcessiveBlockSize,
548  unsigned int &nExtraNonce) {
549  // Update nExtraNonce
550  static uint256 hashPrevBlock;
551  if (hashPrevBlock != pblock->hashPrevBlock) {
552  nExtraNonce = 0;
553  hashPrevBlock = pblock->hashPrevBlock;
554  }
555 
556  ++nExtraNonce;
557  // Height first in coinbase required for block.version=2
558  unsigned int nHeight = pindexPrev->nHeight + 1;
559  CMutableTransaction txCoinbase(*pblock->vtx[0]);
560  txCoinbase.vin[0].scriptSig =
561  (CScript() << nHeight << CScriptNum(nExtraNonce)
562  << getExcessiveBlockSizeSig(nExcessiveBlockSize));
563 
564  // Make sure the coinbase is big enough.
565  uint64_t coinbaseSize = ::GetSerializeSize(txCoinbase, PROTOCOL_VERSION);
566  if (coinbaseSize < MIN_TX_SIZE) {
567  txCoinbase.vin[0].scriptSig
568  << std::vector<uint8_t>(MIN_TX_SIZE - coinbaseSize - 1);
569  }
570 
571  assert(txCoinbase.vin[0].scriptSig.size() <= MAX_COINBASE_SCRIPTSIG_SIZE);
572  assert(::GetSerializeSize(txCoinbase, PROTOCOL_VERSION) >= MIN_TX_SIZE);
573 
574  pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
575  pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
576 }
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:338
uint32_t nNonce
Definition: block.h:30
indexed_modified_transaction_set::nth_index< 0 >::type::iterator modtxiter
Definition: miner.h:115
bool TestPackageTransactions(const CTxMemPool::setEntries &package)
Perform checks on each transaction in a package: locktime, serialized size (if necessary).
Definition: miner.cpp:275
CTransactionRef get(const TxId &txid) const
Definition: txmempool.cpp:918
std::string getSubVersionEB(uint64_t MaxBlockSize)
This function convert MaxBlockSize from byte to MB with a decimal precision one digit rounded down E...
Definition: net.cpp:3150
uint64_t nBlockSize
Definition: miner.h:145
Definition: miner.h:29
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:390
CFeeRate blockMinFeeRate
Definition: miner.h:164
Definition: miner.h:46
static constexpr Amount zero()
Definition: amount.h:35
#define LogPrint(category,...)
Definition: logging.h:189
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:548
void AddToBlock(CTxMemPool::txiter iter)
Add a tx to the block.
Definition: miner.cpp:297
int UpdatePackagesForAdded(const CTxMemPool::setEntries &alreadyAdded, indexed_modified_transaction_set &mapModifiedTx) EXCLUSIVE_LOCKS_REQUIRED(m_mempool.cs)
Add descendants of given transactions to mapModifiedTx with ancestor state updated assuming given tra...
Definition: miner.cpp:316
Definition: block.h:62
uint64_t nExcessiveBlockSize
Definition: miner.h:162
CChain & ChainActive()
Definition: validation.cpp:73
uint64_t nBlockTx
Definition: miner.h:146
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:505
static const Amount DEFAULT_BLOCK_MIN_TX_FEE_PER_KB(1000 *SATOSHI)
Default for -blockmintxfee, which sets the minimum feerate for a transaction in blocks created by min...
void onlyUnconfirmed(CTxMemPool::setEntries &testSet)
Remove confirmed (inBlock) entries from given set.
Definition: miner.cpp:244
int64_t nLockTimeCutoff
Definition: miner.h:153
static CTransactionRef MakeTransactionRef()
Definition: transaction.h:339
CTxMemPool::setEntries inBlock
Definition: miner.h:149
bool TestBlockValidity(BlockValidationState &state, const CChainParams &params, const CBlock &block, CBlockIndex *pindexPrev, BlockValidationOptions validationOptions)
Check a block is completely valid from start to finish (only works on top of our current best block) ...
std::unique_ptr< CBlockTemplate > pblocktemplate
Definition: miner.h:135
Definition: amount.h:17
bool fPowAllowMinDifficultyBlocks
Definition: params.h:101
CBlock * pblock
Definition: miner.h:137
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:171
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
Definition: validation.cpp:849
static constexpr Amount SATOSHI
Definition: amount.h:151
bool TestPackage(uint64_t packageSize, int64_t packageSigOpCount) const
Test if a new package would "fit" in the block.
Definition: miner.cpp:256
std::vector< CTxOut > vout
Definition: transaction.h:300
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:47
CTransactionRef tx
Definition: miner.h:30
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:498
static const uint64_t MIN_TX_SIZE
The minimum allowed size for a transaction, in bytes.
Definition: consensus.h:16
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Determine what nVersion a new block should use.
uint64_t nMaxGeneratedBlockSize
Definition: miner.h:140
uint32_t nTime
Definition: block.h:28
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1193
indexed_modified_transaction_set::index< ancestor_score >::type::iterator modtxscoreiter
Definition: miner.h:117
std::vector< CTxIn > vin
Definition: transaction.h:299
BlockHash GetBlockHash() const
Definition: blockindex.h:133
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:67
#define LOCK2(cs1, cs2)
Definition: sync.h:233
Amount GetMinerFundAmount(const Amount &coinbaseValue)
Definition: minerfund.cpp:18
Amount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
Definition: feerate.cpp:51
virtual uint64_t GetMaxBlockSize() const =0
Definition: config.h:19
uint64_t GetMaxBlockSigChecksCount(uint64_t maxBlockSize)
Compute the maximum number of sigchecks that can be contained in a block given the MAXIMUM block size...
Definition: consensus.h:49
bool MineBlocksOnDemand() const
Whether it is possible to mine blocks on demand (no retargeting)
Definition: chainparams.h:84
Definition: txmempool.h:306
uint256 hashMerkleRoot
Definition: block.h:27
static constexpr unsigned int LOCKTIME_MEDIAN_TIME_PAST
Use GetMedianTimePast() instead of nTime for end point timestamp.
Definition: consensus.h:40
uint64_t nMaxGeneratedBlockSize
Definition: miner.h:163
std::string ToString() const
Definition: validation.h:122
int64_t nSigOpCountWithAncestors
Definition: miner.h:65
int64_t nMedianTimePast
Definition: miner.h:154
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:90
std::set< txiter, CompareIteratorById > setEntries
Definition: txmempool.h:557
Generate a new block, without valid proof-of-work.
Definition: miner.h:132
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Compute the Merkle root of the transactions in a block.
Definition: merkle.cpp:69
Amount nModFeesWithAncestors
Definition: miner.h:64
bool SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx) EXCLUSIVE_LOCKS_REQUIRED(m_mempool.cs)
Return true if given transaction from mapTx has already been evaluated, or if the transaction&#39;s cache...
Definition: miner.cpp:354
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:246
void SortForBlock(const CTxMemPool::setEntries &package, std::vector< CTxMemPool::txiter > &sortedEntries)
Sort the package in an order that is valid to appear in a block.
Definition: miner.cpp:361
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn)
Construct a new block template with coinbase to scriptPubKeyIn.
Definition: miner.cpp:121
static std::optional< int64_t > m_last_block_size
Definition: miner.h:178
BlockAssembler(const Config &config, const CTxMemPool &mempool)
Definition: miner.cpp:101
Parameters that influence chain consensus.
Definition: params.h:59
bool CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents=true) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Try to calculate all in-mempool ancestors of entry.
Definition: txmempool.cpp:185
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:22
static const int MAX_COINBASE_SCRIPTSIG_SIZE
Coinbase scripts have their own script size limit.
Definition: consensus.h:34
int64_t GetBlockTime() const
Definition: block.h:59
static const std::vector< uint8_t > getExcessiveBlockSizeSig(uint64_t nExcessiveBlockSize)
Definition: miner.cpp:540
static constexpr uint32_t STANDARD_LOCKTIME_VERIFY_FLAGS
Used as the flags parameter to sequence and nLocktime checks in non-consensus code.
Definition: policy.h:109
int64_t GetMedianTimePast() const
Definition: blockindex.h:172
const CTxMemPool & m_mempool
Definition: miner.h:157
uint64_t nSizeWithAncestors
Definition: miner.h:63
uint32_t GetNextWorkRequired(const CBlockIndex *pindexPrev, const CBlockHeader *pblock, const CChainParams &chainParams)
Definition: pow.cpp:21
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition: time.cpp:67
256-bit opaque blob.
Definition: uint256.h:120
std::vector< CTransactionRef > vtx
Definition: block.h:65
bool ContextualCheckTransaction(const Consensus::Params &params, const CTransaction &tx, TxValidationState &state, int nHeight, int64_t nLockTimeCutoff, int64_t nMedianTimePast)
Context dependent validity checks for non coinbase transactions.
Definition: tx_verify.cpp:40
void IncrementExtraNonce(CBlock *pblock, const CBlockIndex *pindexPrev, uint64_t nExcessiveBlockSize, unsigned int &nExtraNonce)
Modify the extranonce in a block.
Definition: miner.cpp:546
void addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated) EXCLUSIVE_LOCKS_REQUIRED(m_mempool.cs)
Add transactions based on feerate including unconfirmed ancestors.
Definition: miner.cpp:380
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:468
CFeeRate blockMinFeeRate
Definition: miner.h:142
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: blockindex.h:23
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:429
bool ParseMoney(const std::string &money_string, Amount &nRet)
Parse an amount denoted in full coins.
Definition: moneystr.cpp:34
uint64_t nBlockSigOps
Definition: miner.h:147
int64_t UpdateTime(CBlockHeader *pblock, const CChainParams &chainParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:32
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:11
int nHeight
Definition: miner.h:152
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:479
int64_t GetAdjustedTime()
Definition: timedata.cpp:34
A mutable version of CTransaction.
Definition: transaction.h:297
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:168
Amount nFees
Definition: miner.h:148
ArgsManager gArgs
Definition: system.cpp:76
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
void resetBlock()
Clear the block&#39;s state and prepare for assembling a new block.
Definition: miner.cpp:105
uint64_t nMaxGeneratedBlockSigChecks
Definition: miner.h:141
uint64_t GetVirtualSizeWithAncestors() const
Definition: miner.cpp:50
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:36
const CChainParams & chainParams
Definition: miner.h:155
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:59
static const bool DEFAULT_PRINTPRIORITY
Definition: miner.h:27
static std::optional< int64_t > m_last_block_num_txs
Definition: miner.h:177
static const uint64_t DEFAULT_MAX_BLOCK_SIZE
Default setting for maximum allowed size for a block, in bytes.
Definition: consensus.h:20
static BlockAssembler::Options DefaultOptions(const Config &config)
Definition: miner.cpp:78
Definition: script.h:48
int64_t GetVirtualTransactionSize(int64_t nSize, int64_t nSigOpCount, unsigned int bytes_per_sigop)
Compute the virtual transaction size (size, or more if sigops are too dense).
Definition: policy.cpp:161
static const uint64_t DEFAULT_MAX_GENERATED_BLOCK_SIZE
Default for -blockmaxsize, which controls the maximum size of block the mining code will create...
Definition: policy.h:24
int32_t nVersion
Definition: block.h:25
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:22
BlockHash hashPrevBlock
Definition: block.h:26
bool IsMagneticAnomalyEnabled(const Consensus::Params &params, int32_t nHeight)
Check if Nov 15, 2018 HF has activated using block height.
Definition: activation.cpp:37
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it...
Definition: txmempool.h:545
uint32_t nBits
Definition: block.h:29
std::vector< CTxDestination > GetMinerFundWhitelist(const Consensus::Params &params, const CBlockIndex *pindexPrev)
Definition: minerfund.cpp:34
boost::multi_index_container< CTxMemPoolModifiedEntry, boost::multi_index::indexed_by< boost::multi_index::ordered_unique< modifiedentry_iter, CompareCTxMemPoolIter >, boost::multi_index::ordered_non_unique< boost::multi_index::tag< ancestor_score >, boost::multi_index::identity< CTxMemPoolModifiedEntry >, CompareTxMemPoolEntryByAncestorFee > > > indexed_modified_transaction_set
Definition: miner.h:112