Bitcoin Core  24.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<int64_t>(pindexPrev->GetMedianTimePast() + 1, TicksSinceEpoch<std::chrono::seconds>(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  const CBlockIndex* prev_block = WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock));
54  chainman.GenerateCoinbaseCommitment(block, prev_block);
55 
56  block.hashMerkleRoot = BlockMerkleRoot(block);
57 }
58 
60 {
63 }
64 
65 BlockAssembler::BlockAssembler(Chainstate& chainstate, const CTxMemPool* mempool, const Options& options)
66  : chainparams{chainstate.m_chainman.GetParams()},
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 
91  : BlockAssembler(chainstate, mempool, DefaultOptions()) {}
92 
94 {
95  inBlock.clear();
96 
97  // Reserve space for coinbase tx
98  nBlockWeight = 4000;
99  nBlockSigOpsCost = 400;
100 
101  // These counters do not include coinbase tx
102  nBlockTx = 0;
103  nFees = 0;
104 }
105 
106 std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn)
107 {
108  int64_t nTimeStart = GetTimeMicros();
109 
110  resetBlock();
111 
112  pblocktemplate.reset(new CBlockTemplate());
113 
114  if (!pblocktemplate.get()) {
115  return nullptr;
116  }
117  CBlock* const pblock = &pblocktemplate->block; // pointer for convenience
118 
119  // Add dummy coinbase tx as first transaction
120  pblock->vtx.emplace_back();
121  pblocktemplate->vTxFees.push_back(-1); // updated at end
122  pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end
123 
124  LOCK(::cs_main);
125  CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip();
126  assert(pindexPrev != nullptr);
127  nHeight = pindexPrev->nHeight + 1;
128 
130  // -regtest only: allow overriding block.nVersion with
131  // -blockversion=N to test forking scenarios
133  pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion);
134  }
135 
136  pblock->nTime = TicksSinceEpoch<std::chrono::seconds>(GetAdjustedTime());
137  m_lock_time_cutoff = pindexPrev->GetMedianTimePast();
138 
139  int nPackagesSelected = 0;
140  int nDescendantsUpdated = 0;
141  if (m_mempool) {
142  LOCK(m_mempool->cs);
143  addPackageTxs(*m_mempool, nPackagesSelected, nDescendantsUpdated);
144  }
145 
146  int64_t nTime1 = GetTimeMicros();
147 
150 
151  // Create coinbase transaction.
152  CMutableTransaction coinbaseTx;
153  coinbaseTx.vin.resize(1);
154  coinbaseTx.vin[0].prevout.SetNull();
155  coinbaseTx.vout.resize(1);
156  coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
157  coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
158  coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
159  pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
160  pblocktemplate->vchCoinbaseCommitment = m_chainstate.m_chainman.GenerateCoinbaseCommitment(*pblock, pindexPrev);
161  pblocktemplate->vTxFees[0] = -nFees;
162 
163  LogPrintf("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
164 
165  // Fill in header
166  pblock->hashPrevBlock = pindexPrev->GetBlockHash();
167  UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
168  pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
169  pblock->nNonce = 0;
170  pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]);
171 
172  BlockValidationState state;
173  if (!TestBlockValidity(state, chainparams, m_chainstate, *pblock, pindexPrev, GetAdjustedTime, false, false)) {
174  throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, state.ToString()));
175  }
176  int64_t nTime2 = GetTimeMicros();
177 
178  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));
179 
180  return std::move(pblocktemplate);
181 }
182 
184 {
185  for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
186  // Only test txs not already in the block
187  if (inBlock.count(*iit)) {
188  testSet.erase(iit++);
189  } else {
190  iit++;
191  }
192  }
193 }
194 
195 bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
196 {
197  // TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
198  if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= nBlockMaxWeight) {
199  return false;
200  }
201  if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST) {
202  return false;
203  }
204  return true;
205 }
206 
207 // Perform transaction-level checks before adding to block:
208 // - transaction finality (locktime)
210 {
211  for (CTxMemPool::txiter it : package) {
212  if (!IsFinalTx(it->GetTx(), nHeight, m_lock_time_cutoff)) {
213  return false;
214  }
215  }
216  return true;
217 }
218 
220 {
221  pblocktemplate->block.vtx.emplace_back(iter->GetSharedTx());
222  pblocktemplate->vTxFees.push_back(iter->GetFee());
223  pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
224  nBlockWeight += iter->GetTxWeight();
225  ++nBlockTx;
226  nBlockSigOpsCost += iter->GetSigOpCost();
227  nFees += iter->GetFee();
228  inBlock.insert(iter);
229 
230  bool fPrintPriority = gArgs.GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
231  if (fPrintPriority) {
232  LogPrintf("fee rate %s txid %s\n",
233  CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
234  iter->GetTx().GetHash().ToString());
235  }
236 }
237 
241 static int UpdatePackagesForAdded(const CTxMemPool& mempool,
242  const CTxMemPool::setEntries& alreadyAdded,
244 {
245  AssertLockHeld(mempool.cs);
246 
247  int nDescendantsUpdated = 0;
248  for (CTxMemPool::txiter it : alreadyAdded) {
249  CTxMemPool::setEntries descendants;
250  mempool.CalculateDescendants(it, descendants);
251  // Insert all descendants (not yet in block) into the modified set
252  for (CTxMemPool::txiter desc : descendants) {
253  if (alreadyAdded.count(desc)) {
254  continue;
255  }
256  ++nDescendantsUpdated;
257  modtxiter mit = mapModifiedTx.find(desc);
258  if (mit == mapModifiedTx.end()) {
259  CTxMemPoolModifiedEntry modEntry(desc);
260  modEntry.nSizeWithAncestors -= it->GetTxSize();
261  modEntry.nModFeesWithAncestors -= it->GetModifiedFee();
262  modEntry.nSigOpCostWithAncestors -= it->GetSigOpCost();
263  mapModifiedTx.insert(modEntry);
264  } else {
265  mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
266  }
267  }
268  }
269  return nDescendantsUpdated;
270 }
271 
272 void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, std::vector<CTxMemPool::txiter>& sortedEntries)
273 {
274  // Sort package by ancestor count
275  // If a transaction A depends on transaction B, then A's ancestor count
276  // must be greater than B's. So this is sufficient to validly order the
277  // transactions for block inclusion.
278  sortedEntries.clear();
279  sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
280  std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
281 }
282 
283 // This transaction selection algorithm orders the mempool based
284 // on feerate of a transaction including all unconfirmed ancestors.
285 // Since we don't remove transactions from the mempool as we select them
286 // for block inclusion, we need an alternate method of updating the feerate
287 // of a transaction with its not-yet-selected ancestors as we go.
288 // This is accomplished by walking the in-mempool descendants of selected
289 // transactions and storing a temporary modified state in mapModifiedTxs.
290 // Each time through the loop, we compare the best transaction in
291 // mapModifiedTxs with the next transaction in the mempool to decide what
292 // transaction package to work on next.
293 void BlockAssembler::addPackageTxs(const CTxMemPool& mempool, int& nPackagesSelected, int& nDescendantsUpdated)
294 {
295  AssertLockHeld(mempool.cs);
296 
297  // mapModifiedTx will store sorted packages after they are modified
298  // because some of their txs are already in the block
299  indexed_modified_transaction_set mapModifiedTx;
300  // Keep track of entries that failed inclusion, to avoid duplicate work
301  CTxMemPool::setEntries failedTx;
302 
303  CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin();
304  CTxMemPool::txiter iter;
305 
306  // Limit the number of attempts to add transactions to the block when it is
307  // close to full; this is just a simple heuristic to finish quickly if the
308  // mempool has a lot of entries.
309  const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
310  int64_t nConsecutiveFailed = 0;
311 
312  while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty()) {
313  // First try to find a new transaction in mapTx to evaluate.
314  //
315  // Skip entries in mapTx that are already in a block or are present
316  // in mapModifiedTx (which implies that the mapTx ancestor state is
317  // stale due to ancestor inclusion in the block)
318  // Also skip transactions that we've already failed to add. This can happen if
319  // we consider a transaction in mapModifiedTx and it fails: we can then
320  // potentially consider it again while walking mapTx. It's currently
321  // guaranteed to fail again, but as a belt-and-suspenders check we put it in
322  // failedTx and avoid re-evaluation, since the re-evaluation would be using
323  // cached size/sigops/fee values that are not actually correct.
326  if (mi != mempool.mapTx.get<ancestor_score>().end()) {
327  auto it = mempool.mapTx.project<0>(mi);
328  assert(it != mempool.mapTx.end());
329  if (mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it)) {
330  ++mi;
331  continue;
332  }
333  }
334 
335  // Now that mi is not stale, determine which transaction to evaluate:
336  // the next entry from mapTx, or the best from mapModifiedTx?
337  bool fUsingModified = false;
338 
339  modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
340  if (mi == mempool.mapTx.get<ancestor_score>().end()) {
341  // We're out of entries in mapTx; use the entry from mapModifiedTx
342  iter = modit->iter;
343  fUsingModified = true;
344  } else {
345  // Try to compare the mapTx entry to the mapModifiedTx entry
346  iter = mempool.mapTx.project<0>(mi);
347  if (modit != mapModifiedTx.get<ancestor_score>().end() &&
349  // The best entry in mapModifiedTx has higher score
350  // than the one from mapTx.
351  // Switch which transaction (package) to consider
352  iter = modit->iter;
353  fUsingModified = true;
354  } else {
355  // Either no entry in mapModifiedTx, or it's worse than mapTx.
356  // Increment mi for the next loop iteration.
357  ++mi;
358  }
359  }
360 
361  // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
362  // contain anything that is inBlock.
363  assert(!inBlock.count(iter));
364 
365  uint64_t packageSize = iter->GetSizeWithAncestors();
366  CAmount packageFees = iter->GetModFeesWithAncestors();
367  int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
368  if (fUsingModified) {
369  packageSize = modit->nSizeWithAncestors;
370  packageFees = modit->nModFeesWithAncestors;
371  packageSigOpsCost = modit->nSigOpCostWithAncestors;
372  }
373 
374  if (packageFees < blockMinFeeRate.GetFee(packageSize)) {
375  // Everything else we might consider has a lower fee rate
376  return;
377  }
378 
379  if (!TestPackage(packageSize, packageSigOpsCost)) {
380  if (fUsingModified) {
381  // Since we always look at the best entry in mapModifiedTx,
382  // we must erase failed entries so that we can consider the
383  // next best entry on the next loop iteration
384  mapModifiedTx.get<ancestor_score>().erase(modit);
385  failedTx.insert(iter);
386  }
387 
388  ++nConsecutiveFailed;
389 
390  if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight >
391  nBlockMaxWeight - 4000) {
392  // Give up if we're close to full and haven't succeeded in a while
393  break;
394  }
395  continue;
396  }
397 
398  CTxMemPool::setEntries ancestors;
399  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
400  std::string dummy;
401  mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
402 
403  onlyUnconfirmed(ancestors);
404  ancestors.insert(iter);
405 
406  // Test if all tx's are Final
407  if (!TestPackageTransactions(ancestors)) {
408  if (fUsingModified) {
409  mapModifiedTx.get<ancestor_score>().erase(modit);
410  failedTx.insert(iter);
411  }
412  continue;
413  }
414 
415  // This transaction will make it in; reset the failed counter.
416  nConsecutiveFailed = 0;
417 
418  // Package can be added. Sort the entries in a valid order.
419  std::vector<CTxMemPool::txiter> sortedEntries;
420  SortForBlock(ancestors, sortedEntries);
421 
422  for (size_t i = 0; i < sortedEntries.size(); ++i) {
423  AddToBlock(sortedEntries[i]);
424  // Erase from the modified set, if present
425  mapModifiedTx.erase(sortedEntries[i]);
426  }
427 
428  ++nPackagesSelected;
429 
430  // Update transactions that depend on each of these
431  nDescendantsUpdated += UpdatePackagesForAdded(mempool, ancestors, mapModifiedTx);
432  }
433 }
434 } // namespace node
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:121
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:500
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: system.cpp:629
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:604
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:654
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
int32_t nVersion
Definition: block.h:25
uint256 hashPrevBlock
Definition: block.h:26
uint256 hashMerkleRoot
Definition: block.h:27
Definition: block.h:69
std::vector< CTransactionRef > vtx
Definition: block.h:72
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:152
uint256 GetBlockHash() const
Definition: chain.h:264
int64_t GetMedianTimePast() const
Definition: chain.h:296
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:164
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:439
bool MineBlocksOnDemand() const
Whether it is possible to mine blocks on demand (no retargeting)
Definition: chainparams.h:110
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:82
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:33
std::string ToString(const FeeEstimateMode &fee_estimate_mode=FeeEstimateMode::BTC_KVB) const
Definition: feerate.cpp:39
CAmount GetFee(uint32_t num_bytes) const
Return the fee in satoshis for the given vsize in vbytes.
Definition: feerate.cpp:23
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:411
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:432
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:521
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:882
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:270
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:527
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:524
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:435
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:516
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition: validation.h:482
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:797
std::vector< unsigned char > GenerateCoinbaseCommitment(CBlock &block, const CBlockIndex *pindexPrev) const
Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks...
VersionBitsCache m_versionbitscache
Track versionbit status.
Definition: validation.h:975
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:895
Definition: txmempool.h:278
std::string ToString() const
Definition: validation.h:127
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params &params) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Determine what nVersion a new block should use.
Generate a new block, without valid proof-of-work.
Definition: miner.h:129
Chainstate & m_chainstate
Definition: miner.h:151
void onlyUnconfirmed(CTxMemPool::setEntries &testSet)
Remove confirmed (inBlock) entries from given set.
Definition: miner.cpp:183
void resetBlock()
Clear the block's state and prepare for assembling a new block.
Definition: miner.cpp:93
bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
Test if a new package would "fit" in the block.
Definition: miner.cpp:195
const CTxMemPool *const m_mempool
Definition: miner.h:150
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:209
unsigned int nBlockMaxWeight
Definition: miner.h:135
const CChainParams & chainparams
Definition: miner.h:149
void addPackageTxs(const CTxMemPool &mempool, int &nPackagesSelected, int &nDescendantsUpdated) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs)
Add transactions based on feerate including unconfirmed ancestors Increments nPackagesSelected / nDes...
Definition: miner.cpp:293
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn)
Construct a new block template with coinbase to scriptPubKeyIn.
Definition: miner.cpp:106
CFeeRate blockMinFeeRate
Definition: miner.h:136
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:272
uint64_t nBlockTx
Definition: miner.h:140
CTxMemPool::setEntries inBlock
Definition: miner.h:143
uint64_t nBlockSigOpsCost
Definition: miner.h:141
BlockAssembler(Chainstate &chainstate, const CTxMemPool *mempool)
Definition: miner.cpp:90
int64_t m_lock_time_cutoff
Definition: miner.h:147
uint64_t nBlockWeight
Definition: miner.h:139
std::unique_ptr< CBlockTemplate > pblocktemplate
Definition: miner.h:132
static std::optional< int64_t > m_last_block_num_txs
Definition: miner.h:166
void AddToBlock(CTxMemPool::txiter iter)
Add a tx to the block.
Definition: miner.cpp:219
static std::optional< int64_t > m_last_block_weight
Definition: miner.h:167
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
static int64_t GetBlockWeight(const CBlock &block)
Definition: validation.h:152
int GetWitnessCommitmentIndex(const CBlock &block)
Compute at which vout of the block's coinbase transaction the witness commitment occurs,...
Definition: validation.h:163
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition: consensus.h:15
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
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
#define LogPrint(category,...)
Definition: logging.h:243
#define LogPrintf(...)
Definition: logging.h:234
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:65
std::optional< CAmount > ParseMoney(const std::string &money_string)
Parse an amount denoted in full coins.
Definition: moneystr.cpp:42
@ BENCH
Definition: logging.h:44
Definition: init.h:25
indexed_modified_transaction_set::nth_index< 0 >::type::iterator modtxiter
Definition: miner.h:110
void RegenerateCommitments(CBlock &block, ChainstateManager &chainman)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed.
Definition: miner.cpp:47
static const bool DEFAULT_PRINTPRIORITY
Definition: miner.h:27
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:30
indexed_modified_transaction_set::index< ancestor_score >::type::iterator modtxscoreiter
Definition: miner.h:111
static int UpdatePackagesForAdded(const CTxMemPool &mempool, const CTxMemPool::setEntries &alreadyAdded, indexed_modified_transaction_set &mapModifiedTx) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs)
Add descendants of given transactions to mapModifiedTx with ancestor state updated assuming given tra...
Definition: miner.cpp:241
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
static BlockAssembler::Options DefaultOptions()
Definition: miner.cpp:75
static constexpr 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:25
static constexpr unsigned int DEFAULT_BLOCK_MAX_WEIGHT
Default for -blockmaxweight, which controls the range of block weights the mining code will create.
Definition: policy.h:23
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock, const Consensus::Params &params)
Definition: pow.cpp:13
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:415
@ OP_0
Definition: script.h:72
A mutable version of CTransaction.
Definition: transaction.h:373
std::vector< CTxOut > vout
Definition: transaction.h:375
std::vector< CTxIn > vin
Definition: transaction.h:374
Parameters that influence chain consensus.
Definition: params.h:73
bool fPowAllowMinDifficultyBlocks
Definition: params.h:109
Definition: miner.h:39
CAmount nModFeesWithAncestors
Definition: miner.h:56
uint64_t nSizeWithAncestors
Definition: miner.h:55
int64_t nSigOpCostWithAncestors
Definition: miner.h:57
#define LOCK(cs)
Definition: sync.h:261
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:305
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition: time.cpp:110
NodeClock::time_point GetAdjustedTime()
Definition: timedata.cpp:35
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Auxiliary functions for transaction validation (ideally should not be exposed)
Definition: tx_verify.cpp:116
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:17
ArgsManager gArgs
Definition: system.cpp:86
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev, const std::function< NodeClock::time_point()> &adjusted_time_callback, bool fCheckPOW, bool fCheckMerkleRoot)
Check a block is completely valid from start to finish (only works on top of our current best block)
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())