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