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