Bitcoin Core  22.99.0
P2P Digital Currency
miner.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2021 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 <consensus/amount.h>
12 #include <consensus/consensus.h>
13 #include <consensus/merkle.h>
14 #include <consensus/tx_verify.h>
15 #include <consensus/validation.h>
16 #include <deploymentstatus.h>
17 #include <policy/feerate.h>
18 #include <policy/policy.h>
19 #include <pow.h>
20 #include <primitives/transaction.h>
21 #include <timedata.h>
22 #include <util/moneystr.h>
23 #include <util/system.h>
24 #include <validation.h>
25 
26 #include <algorithm>
27 #include <utility>
28 
29 namespace node {
30 int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
31 {
32  int64_t nOldTime = pblock->nTime;
33  int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast() + 1, GetAdjustedTime());
34 
35  if (nOldTime < nNewTime) {
36  pblock->nTime = nNewTime;
37  }
38 
39  // Updating time can change work required on testnet:
40  if (consensusParams.fPowAllowMinDifficultyBlocks) {
41  pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
42  }
43 
44  return nNewTime - nOldTime;
45 }
46 
48 {
49  CMutableTransaction tx{*block.vtx.at(0)};
50  tx.vout.erase(tx.vout.begin() + GetWitnessCommitmentIndex(block));
51  block.vtx.at(0) = MakeTransactionRef(tx);
52 
53  CBlockIndex* prev_block = WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock));
54  GenerateCoinbaseCommitment(block, prev_block, Params().GetConsensus());
55 
56  block.hashMerkleRoot = BlockMerkleRoot(block);
57 }
58 
60 {
63 }
64 
65 BlockAssembler::BlockAssembler(CChainState& chainstate, const CTxMemPool& mempool, const CChainParams& params, const Options& options)
66  : chainparams(params),
67  m_mempool(mempool),
68  m_chainstate(chainstate)
69 {
71  // Limit weight to between 4K and MAX_BLOCK_WEIGHT-4K for sanity:
72  nBlockMaxWeight = std::max<size_t>(4000, std::min<size_t>(MAX_BLOCK_WEIGHT - 4000, options.nBlockMaxWeight));
73 }
74 
76 {
77  // Block resource limits
78  // If -blockmaxweight is not given, limit to DEFAULT_BLOCK_MAX_WEIGHT
80  options.nBlockMaxWeight = gArgs.GetIntArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
81  if (gArgs.IsArgSet("-blockmintxfee")) {
82  std::optional<CAmount> parsed = ParseMoney(gArgs.GetArg("-blockmintxfee", ""));
83  options.blockMinFeeRate = CFeeRate{parsed.value_or(DEFAULT_BLOCK_MIN_TX_FEE)};
84  } else {
86  }
87  return options;
88 }
89 
90 BlockAssembler::BlockAssembler(CChainState& chainstate, const CTxMemPool& mempool, const CChainParams& params)
91  : BlockAssembler(chainstate, mempool, params, DefaultOptions()) {}
92 
94 {
95  inBlock.clear();
96 
97  // Reserve space for coinbase tx
98  nBlockWeight = 4000;
99  nBlockSigOpsCost = 400;
100  fIncludeWitness = false;
101 
102  // These counters do not include coinbase tx
103  nBlockTx = 0;
104  nFees = 0;
105 }
106 
107 std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn)
108 {
109  int64_t nTimeStart = GetTimeMicros();
110 
111  resetBlock();
112 
113  pblocktemplate.reset(new CBlockTemplate());
114 
115  if (!pblocktemplate.get()) {
116  return nullptr;
117  }
118  CBlock* const pblock = &pblocktemplate->block; // pointer for convenience
119 
120  // Add dummy coinbase tx as first transaction
121  pblock->vtx.emplace_back();
122  pblocktemplate->vTxFees.push_back(-1); // updated at end
123  pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end
124 
126  CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip();
127  assert(pindexPrev != nullptr);
128  nHeight = pindexPrev->nHeight + 1;
129 
131  // -regtest only: allow overriding block.nVersion with
132  // -blockversion=N to test forking scenarios
134  pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion);
135  }
136 
137  pblock->nTime = GetAdjustedTime();
138  m_lock_time_cutoff = pindexPrev->GetMedianTimePast();
139 
140  // Decide whether to include witness transactions
141  // This is only needed in case the witness softfork activation is reverted
142  // (which would require a very deep reorganization).
143  // Note that the mempool would accept transactions with witness data before
144  // the deployment is active, but we would only ever mine blocks after activation
145  // unless there is a massive block reorganization with the witness softfork
146  // not activated.
147  // TODO: replace this with a call to main to assess validity of a mempool
148  // transaction (which in most cases can be a no-op).
150 
151  int nPackagesSelected = 0;
152  int nDescendantsUpdated = 0;
153  addPackageTxs(nPackagesSelected, nDescendantsUpdated);
154 
155  int64_t nTime1 = GetTimeMicros();
156 
159 
160  // Create coinbase transaction.
161  CMutableTransaction coinbaseTx;
162  coinbaseTx.vin.resize(1);
163  coinbaseTx.vin[0].prevout.SetNull();
164  coinbaseTx.vout.resize(1);
165  coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
166  coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
167  coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
168  pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
169  pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus());
170  pblocktemplate->vTxFees[0] = -nFees;
171 
172  LogPrintf("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
173 
174  // Fill in header
175  pblock->hashPrevBlock = pindexPrev->GetBlockHash();
176  UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
177  pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
178  pblock->nNonce = 0;
179  pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]);
180 
181  BlockValidationState state;
182  if (!TestBlockValidity(state, chainparams, m_chainstate, *pblock, pindexPrev, false, false)) {
183  throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, state.ToString()));
184  }
185  int64_t nTime2 = GetTimeMicros();
186 
187  LogPrint(BCLog::BENCH, "CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n", 0.001 * (nTime1 - nTimeStart), nPackagesSelected, nDescendantsUpdated, 0.001 * (nTime2 - nTime1), 0.001 * (nTime2 - nTimeStart));
188 
189  return std::move(pblocktemplate);
190 }
191 
193 {
194  for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
195  // Only test txs not already in the block
196  if (inBlock.count(*iit)) {
197  testSet.erase(iit++);
198  } else {
199  iit++;
200  }
201  }
202 }
203 
204 bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
205 {
206  // TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
207  if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= nBlockMaxWeight) {
208  return false;
209  }
210  if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST) {
211  return false;
212  }
213  return true;
214 }
215 
216 // Perform transaction-level checks before adding to block:
217 // - transaction finality (locktime)
218 // - premature witness (in case segwit transactions are added to mempool before
219 // segwit activation)
221 {
222  for (CTxMemPool::txiter it : package) {
223  if (!IsFinalTx(it->GetTx(), nHeight, m_lock_time_cutoff)) {
224  return false;
225  }
226  if (!fIncludeWitness && it->GetTx().HasWitness()) {
227  return false;
228  }
229  }
230  return true;
231 }
232 
234 {
235  pblocktemplate->block.vtx.emplace_back(iter->GetSharedTx());
236  pblocktemplate->vTxFees.push_back(iter->GetFee());
237  pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
238  nBlockWeight += iter->GetTxWeight();
239  ++nBlockTx;
240  nBlockSigOpsCost += iter->GetSigOpCost();
241  nFees += iter->GetFee();
242  inBlock.insert(iter);
243 
244  bool fPrintPriority = gArgs.GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
245  if (fPrintPriority) {
246  LogPrintf("fee rate %s txid %s\n",
247  CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
248  iter->GetTx().GetHash().ToString());
249  }
250 }
251 
253  indexed_modified_transaction_set &mapModifiedTx)
254 {
256 
257  int nDescendantsUpdated = 0;
258  for (CTxMemPool::txiter it : alreadyAdded) {
259  CTxMemPool::setEntries descendants;
260  m_mempool.CalculateDescendants(it, descendants);
261  // Insert all descendants (not yet in block) into the modified set
262  for (CTxMemPool::txiter desc : descendants) {
263  if (alreadyAdded.count(desc)) {
264  continue;
265  }
266  ++nDescendantsUpdated;
267  modtxiter mit = mapModifiedTx.find(desc);
268  if (mit == mapModifiedTx.end()) {
269  CTxMemPoolModifiedEntry modEntry(desc);
270  modEntry.nSizeWithAncestors -= it->GetTxSize();
271  modEntry.nModFeesWithAncestors -= it->GetModifiedFee();
272  modEntry.nSigOpCostWithAncestors -= it->GetSigOpCost();
273  mapModifiedTx.insert(modEntry);
274  } else {
275  mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
276  }
277  }
278  }
279  return nDescendantsUpdated;
280 }
281 
282 // Skip entries in mapTx that are already in a block or are present
283 // in mapModifiedTx (which implies that the mapTx ancestor state is
284 // stale due to ancestor inclusion in the block)
285 // Also skip transactions that we've already failed to add. This can happen if
286 // we consider a transaction in mapModifiedTx and it fails: we can then
287 // potentially consider it again while walking mapTx. It's currently
288 // guaranteed to fail again, but as a belt-and-suspenders check we put it in
289 // failedTx and avoid re-evaluation, since the re-evaluation would be using
290 // cached size/sigops/fee values that are not actually correct.
292 {
294 
295  assert(it != m_mempool.mapTx.end());
296  return mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it);
297 }
298 
299 void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, std::vector<CTxMemPool::txiter>& sortedEntries)
300 {
301  // Sort package by ancestor count
302  // If a transaction A depends on transaction B, then A's ancestor count
303  // must be greater than B's. So this is sufficient to validly order the
304  // transactions for block inclusion.
305  sortedEntries.clear();
306  sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
307  std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
308 }
309 
310 // This transaction selection algorithm orders the mempool based
311 // on feerate of a transaction including all unconfirmed ancestors.
312 // Since we don't remove transactions from the mempool as we select them
313 // for block inclusion, we need an alternate method of updating the feerate
314 // of a transaction with its not-yet-selected ancestors as we go.
315 // This is accomplished by walking the in-mempool descendants of selected
316 // transactions and storing a temporary modified state in mapModifiedTxs.
317 // Each time through the loop, we compare the best transaction in
318 // mapModifiedTxs with the next transaction in the mempool to decide what
319 // transaction package to work on next.
320 void BlockAssembler::addPackageTxs(int& nPackagesSelected, int& nDescendantsUpdated)
321 {
323 
324  // mapModifiedTx will store sorted packages after they are modified
325  // because some of their txs are already in the block
326  indexed_modified_transaction_set mapModifiedTx;
327  // Keep track of entries that failed inclusion, to avoid duplicate work
328  CTxMemPool::setEntries failedTx;
329 
330  // Start by adding all descendants of previously added txs to mapModifiedTx
331  // and modifying them for their already included ancestors
332  UpdatePackagesForAdded(inBlock, mapModifiedTx);
333 
334  CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = m_mempool.mapTx.get<ancestor_score>().begin();
335  CTxMemPool::txiter iter;
336 
337  // Limit the number of attempts to add transactions to the block when it is
338  // close to full; this is just a simple heuristic to finish quickly if the
339  // mempool has a lot of entries.
340  const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
341  int64_t nConsecutiveFailed = 0;
342 
343  while (mi != m_mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty()) {
344  // First try to find a new transaction in mapTx to evaluate.
345  if (mi != m_mempool.mapTx.get<ancestor_score>().end() &&
346  SkipMapTxEntry(m_mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) {
347  ++mi;
348  continue;
349  }
350 
351  // Now that mi is not stale, determine which transaction to evaluate:
352  // the next entry from mapTx, or the best from mapModifiedTx?
353  bool fUsingModified = false;
354 
355  modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
356  if (mi == m_mempool.mapTx.get<ancestor_score>().end()) {
357  // We're out of entries in mapTx; use the entry from mapModifiedTx
358  iter = modit->iter;
359  fUsingModified = true;
360  } else {
361  // Try to compare the mapTx entry to the mapModifiedTx entry
362  iter = m_mempool.mapTx.project<0>(mi);
363  if (modit != mapModifiedTx.get<ancestor_score>().end() &&
365  // The best entry in mapModifiedTx has higher score
366  // than the one from mapTx.
367  // Switch which transaction (package) to consider
368  iter = modit->iter;
369  fUsingModified = true;
370  } else {
371  // Either no entry in mapModifiedTx, or it's worse than mapTx.
372  // Increment mi for the next loop iteration.
373  ++mi;
374  }
375  }
376 
377  // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
378  // contain anything that is inBlock.
379  assert(!inBlock.count(iter));
380 
381  uint64_t packageSize = iter->GetSizeWithAncestors();
382  CAmount packageFees = iter->GetModFeesWithAncestors();
383  int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
384  if (fUsingModified) {
385  packageSize = modit->nSizeWithAncestors;
386  packageFees = modit->nModFeesWithAncestors;
387  packageSigOpsCost = modit->nSigOpCostWithAncestors;
388  }
389 
390  if (packageFees < blockMinFeeRate.GetFee(packageSize)) {
391  // Everything else we might consider has a lower fee rate
392  return;
393  }
394 
395  if (!TestPackage(packageSize, packageSigOpsCost)) {
396  if (fUsingModified) {
397  // Since we always look at the best entry in mapModifiedTx,
398  // we must erase failed entries so that we can consider the
399  // next best entry on the next loop iteration
400  mapModifiedTx.get<ancestor_score>().erase(modit);
401  failedTx.insert(iter);
402  }
403 
404  ++nConsecutiveFailed;
405 
406  if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight >
407  nBlockMaxWeight - 4000) {
408  // Give up if we're close to full and haven't succeeded in a while
409  break;
410  }
411  continue;
412  }
413 
414  CTxMemPool::setEntries ancestors;
415  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
416  std::string dummy;
417  m_mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
418 
419  onlyUnconfirmed(ancestors);
420  ancestors.insert(iter);
421 
422  // Test if all tx's are Final
423  if (!TestPackageTransactions(ancestors)) {
424  if (fUsingModified) {
425  mapModifiedTx.get<ancestor_score>().erase(modit);
426  failedTx.insert(iter);
427  }
428  continue;
429  }
430 
431  // This transaction will make it in; reset the failed counter.
432  nConsecutiveFailed = 0;
433 
434  // Package can be added. Sort the entries in a valid order.
435  std::vector<CTxMemPool::txiter> sortedEntries;
436  SortForBlock(ancestors, sortedEntries);
437 
438  for (size_t i = 0; i < sortedEntries.size(); ++i) {
439  AddToBlock(sortedEntries[i]);
440  // Erase from the modified set, if present
441  mapModifiedTx.erase(sortedEntries[i]);
442  }
443 
444  ++nPackagesSelected;
445 
446  // Update transactions that depend on each of these
447  nDescendantsUpdated += UpdatePackagesForAdded(ancestors, mapModifiedTx);
448  }
449 }
450 
451 void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
452 {
453  // Update nExtraNonce
454  static uint256 hashPrevBlock;
455  if (hashPrevBlock != pblock->hashPrevBlock) {
456  nExtraNonce = 0;
457  hashPrevBlock = pblock->hashPrevBlock;
458  }
459  ++nExtraNonce;
460  unsigned int nHeight = pindexPrev->nHeight + 1; // Height first in coinbase required for block.version=2
461  CMutableTransaction txCoinbase(*pblock->vtx[0]);
462  txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce));
463  assert(txCoinbase.vin[0].scriptSig.size() <= 100);
464 
465  pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
466  pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
467 }
468 } // namespace node
node::BlockAssembler::chainparams
const CChainParams & chainparams
Definition: miner.h:150
LOCK2
#define LOCK2(cs1, cs2)
Definition: sync.h:227
node::BlockAssembler::nFees
CAmount nFees
Definition: miner.h:143
CTxMemPool::setEntries
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:523
policy.h
CMutableTransaction::vin
std::vector< CTxIn > vin
Definition: transaction.h:366
node::BlockAssembler::AddToBlock
void AddToBlock(CTxMemPool::txiter iter)
Add a tx to the block.
Definition: miner.cpp:233
node::BlockAssembler::SortForBlock
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:299
GetBlockSubsidy
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
Definition: validation.cpp:1414
feerate.h
GetNextWorkRequired
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock, const Consensus::Params &params)
Definition: pow.cpp:13
ArgsManager::GetBoolArg
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:600
node::BlockAssembler::addPackageTxs
void addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated) EXCLUSIVE_LOCKS_REQUIRED(m_mempool.cs)
Add transactions based on feerate including unconfirmed ancestors Increments nPackagesSelected / nDes...
Definition: miner.cpp:320
node::BlockAssembler::nHeight
int nHeight
Definition: miner.h:147
assert
assert(!tx.IsCoinBase())
node::BlockManager::LookupBlockIndex
CBlockIndex * LookupBlockIndex(const uint256 &hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: blockstorage.cpp:35
node::BlockAssembler::m_chainstate
CChainState & m_chainstate
Definition: miner.h:152
pow.h
CBlockHeader::hashMerkleRoot
uint256 hashMerkleRoot
Definition: block.h:26
VersionBitsCache::ComputeBlockVersion
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Determine what nVersion a new block should use.
Definition: versionbits.cpp:224
CBlockHeader::nBits
uint32_t nBits
Definition: block.h:28
nHeight
unsigned int nHeight
Definition: mempool_eviction.cpp:14
DEFAULT_BLOCK_MAX_WEIGHT
static const unsigned int DEFAULT_BLOCK_MAX_WEIGHT
Default for -blockmaxweight, which controls the range of block weights the mining code will create.
Definition: policy.h:20
node::BlockAssembler::onlyUnconfirmed
void onlyUnconfirmed(CTxMemPool::setEntries &testSet)
Remove confirmed (inBlock) entries from given set.
Definition: miner.cpp:192
CBlockHeader
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:20
BlockValidationState
Definition: validation.h:141
node::update_for_parent_inclusion
Definition: miner.h:113
node::modtxscoreiter
indexed_modified_transaction_set::index< ancestor_score >::type::iterator modtxscoreiter
Definition: miner.h:111
node::BlockAssembler::nBlockTx
uint64_t nBlockTx
Definition: miner.h:141
moneystr.h
node::BlockAssembler::nBlockMaxWeight
unsigned int nBlockMaxWeight
Definition: miner.h:136
transaction.h
CBlockHeader::nVersion
int32_t nVersion
Definition: block.h:24
CTxMemPool::txiter
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:520
timedata.h
node::BlockAssembler::Options
Definition: miner.h:155
CTxMemPool
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:429
CompareTxMemPoolEntryByAncestorFee
Definition: txmempool.h:275
DeploymentActiveAfter
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::BuriedDeployment dep)
Determine if a deployment is active for the next block.
Definition: deploymentstatus.h:17
ArgsManager::IsArgSet
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:494
CBlockIndex::nHeight
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:164
validation.h
node::DEFAULT_PRINTPRIORITY
static const bool DEFAULT_PRINTPRIORITY
Definition: miner.h:27
CChainParams
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:69
node::BlockAssembler::m_lock_time_cutoff
int64_t m_lock_time_cutoff
Definition: miner.h:148
BCLog::BENCH
@ BENCH
Definition: logging.h:43
WITH_LOCK
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:270
MakeTransactionRef
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:407
CChainParams::GetConsensus
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:82
CTxMemPool::CalculateMemPoolAncestors
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:308
GetLegacySigOpCount
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Auxiliary functions for transaction validation (ideally should not be exposed)
Definition: tx_verify.cpp:115
node::BlockAssembler::TestPackageTransactions
bool TestPackageTransactions(const CTxMemPool::setEntries &package) const
Perform checks on each transaction in a package: locktime, premature-witness, serialized size (if nec...
Definition: miner.cpp:220
chainparams.h
IsFinalTx
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
Check if transaction is final and can be included in a block with the specified height and time.
Definition: tx_verify.cpp:16
CChain::Tip
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:447
node::BlockAssembler::Options::nBlockMaxWeight
size_t nBlockMaxWeight
Definition: miner.h:157
node::BlockAssembler::resetBlock
void resetBlock()
Clear the block's state and prepare for assembling a new block.
Definition: miner.cpp:93
CFeeRate
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:29
node::IncrementExtraNonce
void IncrementExtraNonce(CBlock *pblock, const CBlockIndex *pindexPrev, unsigned int &nExtraNonce)
Modify the extranonce in a block.
Definition: miner.cpp:451
DEFAULT_BLOCK_MIN_TX_FEE
static const unsigned int DEFAULT_BLOCK_MIN_TX_FEE
Default for -blockmintxfee, which sets the minimum feerate for a transaction in blocks created by min...
Definition: policy.h:22
AssertLockHeld
AssertLockHeld(pool.cs)
ValidationState::ToString
std::string ToString() const
Definition: validation.h:126
deploymentstatus.h
CScriptNum
Definition: script.h:219
CBlockHeader::nNonce
uint32_t nNonce
Definition: block.h:29
Consensus::Params
Parameters that influence chain consensus.
Definition: params.h:70
OP_0
@ OP_0
Definition: script.h:69
g_versionbitscache
VersionBitsCache g_versionbitscache
Global cache for versionbits deployment status.
Definition: deploymentstatus.cpp:12
Consensus::DEPLOYMENT_SEGWIT
@ DEPLOYMENT_SEGWIT
Definition: params.h:24
CTxMemPool::cs
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:517
CTxMemPool::get
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:908
node::BlockAssembler::m_last_block_num_txs
static std::optional< int64_t > m_last_block_num_txs
Definition: miner.h:167
tx_verify.h
node::BlockAssembler::m_last_block_weight
static std::optional< int64_t > m_last_block_weight
Definition: miner.h:168
CBlockIndex::GetMedianTimePast
int64_t GetMedianTimePast() const
Definition: chain.h:290
node::BlockAssembler::Options::blockMinFeeRate
CFeeRate blockMinFeeRate
Definition: miner.h:158
MAX_BLOCK_SIGOPS_COST
static const int64_t MAX_BLOCK_SIGOPS_COST
The maximum allowed number of signature check operations in a block (network rule)
Definition: consensus.h:17
node::CTxMemPoolModifiedEntry::nModFeesWithAncestors
CAmount nModFeesWithAncestors
Definition: miner.h:56
node::BlockAssembler::blockMinFeeRate
CFeeRate blockMinFeeRate
Definition: miner.h:137
Consensus::Params::fPowAllowMinDifficultyBlocks
bool fPowAllowMinDifficultyBlocks
Definition: params.h:101
node::BlockAssembler::inBlock
CTxMemPool::setEntries inBlock
Definition: miner.h:144
consensus.h
miner.h
node::CBlockTemplate
Definition: miner.h:29
GenerateCoinbaseCommitment
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...
Definition: validation.cpp:3326
node::BlockAssembler::m_mempool
const CTxMemPool & m_mempool
Definition: miner.h:151
ArgsManager::GetArg
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:588
node::BlockAssembler::SkipMapTxEntry
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:291
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
LogPrintf
#define LogPrintf(...)
Definition: logging.h:188
node::BlockAssembler::CreateNewBlock
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn)
Construct a new block template with coinbase to scriptPubKeyIn.
Definition: miner.cpp:107
CBlockHeader::nTime
uint32_t nTime
Definition: block.h:27
node::BlockAssembler::pblocktemplate
std::unique_ptr< CBlockTemplate > pblocktemplate
Definition: miner.h:132
node::modtxiter
indexed_modified_transaction_set::nth_index< 0 >::type::iterator modtxiter
Definition: miner.h:110
uint256
256-bit opaque blob.
Definition: uint256.h:126
CFeeRate::ToString
std::string ToString(const FeeEstimateMode &fee_estimate_mode=FeeEstimateMode::BTC_KVB) const
Definition: feerate.cpp:39
node::BlockAssembler::fIncludeWitness
bool fIncludeWitness
Definition: miner.h:135
CChainState
CChainState stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:459
LogPrint
#define LogPrint(category,...)
Definition: logging.h:192
node::BlockAssembler
Generate a new block, without valid proof-of-work.
Definition: miner.h:128
node::BlockAssembler::BlockAssembler
BlockAssembler(CChainState &chainstate, const CTxMemPool &mempool, const CChainParams &params)
Definition: miner.cpp:90
GetWitnessCommitmentIndex
int GetWitnessCommitmentIndex(const CBlock &block)
Compute at which vout of the block's coinbase transaction the witness commitment occurs,...
Definition: validation.h:162
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:405
GetBlockWeight
static int64_t GetBlockWeight(const CBlock &block)
Definition: validation.h:151
CBlockIndex::GetBlockHash
uint256 GetBlockHash() const
Definition: chain.h:264
coins.h
gArgs
ArgsManager gArgs
Definition: system.cpp:87
ancestor_score
Definition: txmempool.h:318
merkle.h
ChainstateManager
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:792
CBlockHeader::hashPrevBlock
uint256 hashPrevBlock
Definition: block.h:25
system.h
CBlock
Definition: block.h:62
CMutableTransaction::vout
std::vector< CTxOut > vout
Definition: transaction.h:367
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
GetAdjustedTime
int64_t GetAdjustedTime()
Definition: timedata.cpp:35
node::CTxMemPoolModifiedEntry::nSigOpCostWithAncestors
int64_t nSigOpCostWithAncestors
Definition: miner.h:57
CBlock::vtx
std::vector< CTransactionRef > vtx
Definition: block.h:66
TestBlockValidity
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, CChainState &chainstate, 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)
Definition: validation.cpp:3747
ParseMoney
std::optional< CAmount > ParseMoney(const std::string &money_string)
Parse an amount denoted in full coins.
Definition: moneystr.cpp:41
MAX_BLOCK_WEIGHT
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition: consensus.h:15
node::indexed_modified_transaction_set
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:108
node::BlockAssembler::TestPackage
bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
Test if a new package would "fit" in the block.
Definition: miner.cpp:204
node::UpdateTime
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:30
node::CompareTxIterByAncestorCount
Definition: miner.h:83
node::RegenerateCommitments
void RegenerateCommitments(CBlock &block, ChainstateManager &chainman)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed.
Definition: miner.cpp:47
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:561
node
Definition: init.h:22
CChainParams::MineBlocksOnDemand
bool MineBlocksOnDemand() const
Whether it is possible to mine blocks on demand (no retargeting)
Definition: chainparams.h:110
node::DefaultOptions
static BlockAssembler::Options DefaultOptions()
Definition: miner.cpp:75
GetTimeMicros
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition: time.cpp:122
node::BlockAssembler::nBlockWeight
uint64_t nBlockWeight
Definition: miner.h:140
node::CTxMemPoolModifiedEntry
Definition: miner.h:39
CFeeRate::GetFee
CAmount GetFee(uint32_t num_bytes) const
Return the fee in satoshis for the given size in bytes.
Definition: feerate.cpp:23
CMutableTransaction
A mutable version of CTransaction.
Definition: transaction.h:364
cs_main
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:138
CBlockIndex
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:151
ArgsManager::GetIntArg
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: system.cpp:594
amount.h
node::BlockAssembler::UpdatePackagesForAdded
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:252
node::BlockAssembler::Options::Options
Options()
Definition: miner.cpp:59
node::BlockAssembler::nBlockSigOpsCost
uint64_t nBlockSigOpsCost
Definition: miner.h:142
WITNESS_SCALE_FACTOR
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
CChainState::m_chain
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:540
ChainstateManager::m_blockman
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:862
BlockMerkleRoot
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:65
node::CTxMemPoolModifiedEntry::nSizeWithAncestors
uint64_t nSizeWithAncestors
Definition: miner.h:55
CTxMemPool::CalculateDescendants
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:582