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