Bitcoin Core 29.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-2022 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 <common/args.h>
12#include <consensus/amount.h>
13#include <consensus/consensus.h>
14#include <consensus/merkle.h>
15#include <consensus/tx_verify.h>
17#include <deploymentstatus.h>
18#include <logging.h>
19#include <node/context.h>
21#include <policy/feerate.h>
22#include <policy/policy.h>
23#include <pow.h>
25#include <util/moneystr.h>
27#include <util/time.h>
28#include <validation.h>
29
30#include <algorithm>
31#include <utility>
32
33namespace node {
34
35int64_t GetMinimumTime(const CBlockIndex* pindexPrev, const int64_t difficulty_adjustment_interval)
36{
37 int64_t min_time{pindexPrev->GetMedianTimePast() + 1};
38 // Height of block to be mined.
39 const int height{pindexPrev->nHeight + 1};
40 // Account for BIP94 timewarp rule on all networks. This makes future
41 // activation safer.
42 if (height % difficulty_adjustment_interval == 0) {
43 min_time = std::max<int64_t>(min_time, pindexPrev->GetBlockTime() - MAX_TIMEWARP);
44 }
45 return min_time;
46}
47
48int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
49{
50 int64_t nOldTime = pblock->nTime;
51 int64_t nNewTime{std::max<int64_t>(GetMinimumTime(pindexPrev, consensusParams.DifficultyAdjustmentInterval()),
52 TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()))};
53
54 if (nOldTime < nNewTime) {
55 pblock->nTime = nNewTime;
56 }
57
58 // Updating time can change work required on testnet:
59 if (consensusParams.fPowAllowMinDifficultyBlocks) {
60 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
61 }
62
63 return nNewTime - nOldTime;
64}
65
67{
68 CMutableTransaction tx{*block.vtx.at(0)};
69 tx.vout.erase(tx.vout.begin() + GetWitnessCommitmentIndex(block));
70 block.vtx.at(0) = MakeTransactionRef(tx);
71
72 const CBlockIndex* prev_block = WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock));
73 chainman.GenerateCoinbaseCommitment(block, prev_block);
74
75 block.hashMerkleRoot = BlockMerkleRoot(block);
76}
77
79{
83 // Limit weight to between block_reserved_weight and MAX_BLOCK_WEIGHT for sanity:
84 // block_reserved_weight can safely exceed -blockmaxweight, but the rest of the block template will be empty.
85 options.nBlockMaxWeight = std::clamp<size_t>(options.nBlockMaxWeight, options.block_reserved_weight, MAX_BLOCK_WEIGHT);
86 return options;
87}
88
89BlockAssembler::BlockAssembler(Chainstate& chainstate, const CTxMemPool* mempool, const Options& options)
90 : chainparams{chainstate.m_chainman.GetParams()},
91 m_mempool{options.use_mempool ? mempool : nullptr},
92 m_chainstate{chainstate},
93 m_options{ClampOptions(options)}
94{
95}
96
98{
99 // Block resource limits
100 options.nBlockMaxWeight = args.GetIntArg("-blockmaxweight", options.nBlockMaxWeight);
101 if (const auto blockmintxfee{args.GetArg("-blockmintxfee")}) {
102 if (const auto parsed{ParseMoney(*blockmintxfee)}) options.blockMinFeeRate = CFeeRate{*parsed};
103 }
104 options.print_modified_fee = args.GetBoolArg("-printpriority", options.print_modified_fee);
105 options.block_reserved_weight = args.GetIntArg("-blockreservedweight", options.block_reserved_weight);
106}
107
108void BlockAssembler::resetBlock()
109{
110 inBlock.clear();
111
112 // Reserve space for fixed-size block header, txs count, and coinbase tx.
113 nBlockWeight = m_options.block_reserved_weight;
114 nBlockSigOpsCost = m_options.coinbase_output_max_additional_sigops;
115
116 // These counters do not include coinbase tx
117 nBlockTx = 0;
118 nFees = 0;
119}
120
121std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock()
122{
123 const auto time_start{SteadyClock::now()};
124
125 resetBlock();
126
127 pblocktemplate.reset(new CBlockTemplate());
128 CBlock* const pblock = &pblocktemplate->block; // pointer for convenience
129
130 // Add dummy coinbase tx as first transaction. It is skipped by the
131 // getblocktemplate RPC and mining interface consumers must not use it.
132 pblock->vtx.emplace_back();
133
135 CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip();
136 assert(pindexPrev != nullptr);
137 nHeight = pindexPrev->nHeight + 1;
138
139 pblock->nVersion = m_chainstate.m_chainman.m_versionbitscache.ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
140 // -regtest only: allow overriding block.nVersion with
141 // -blockversion=N to test forking scenarios
142 if (chainparams.MineBlocksOnDemand()) {
143 pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion);
144 }
145
146 pblock->nTime = TicksSinceEpoch<std::chrono::seconds>(NodeClock::now());
147 m_lock_time_cutoff = pindexPrev->GetMedianTimePast();
148
149 int nPackagesSelected = 0;
150 int nDescendantsUpdated = 0;
151 if (m_mempool) {
152 addPackageTxs(nPackagesSelected, nDescendantsUpdated);
153 }
154
155 const auto time_1{SteadyClock::now()};
156
157 m_last_block_num_txs = nBlockTx;
158 m_last_block_weight = nBlockWeight;
159
160 // Create coinbase transaction.
161 CMutableTransaction coinbaseTx;
162 coinbaseTx.vin.resize(1);
163 coinbaseTx.vin[0].prevout.SetNull();
164 coinbaseTx.vin[0].nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; // Make sure timelock is enforced.
165 coinbaseTx.vout.resize(1);
166 coinbaseTx.vout[0].scriptPubKey = m_options.coinbase_output_script;
167 coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
168 coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
169 Assert(nHeight > 0);
170 coinbaseTx.nLockTime = static_cast<uint32_t>(nHeight - 1);
171 pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
172 pblocktemplate->vchCoinbaseCommitment = m_chainstate.m_chainman.GenerateCoinbaseCommitment(*pblock, pindexPrev);
173
174 LogPrintf("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
175
176 // Fill in header
177 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
178 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
179 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
180 pblock->nNonce = 0;
181
183 if (m_options.test_block_validity && !TestBlockValidity(state, chainparams, m_chainstate, *pblock, pindexPrev,
184 /*fCheckPOW=*/false, /*fCheckMerkleRoot=*/false)) {
185 throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, state.ToString()));
186 }
187 const auto time_2{SteadyClock::now()};
188
189 LogDebug(BCLog::BENCH, "CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n",
190 Ticks<MillisecondsDouble>(time_1 - time_start), nPackagesSelected, nDescendantsUpdated,
191 Ticks<MillisecondsDouble>(time_2 - time_1),
192 Ticks<MillisecondsDouble>(time_2 - time_start));
193
194 return std::move(pblocktemplate);
195}
196
197void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet)
198{
199 for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
200 // Only test txs not already in the block
201 if (inBlock.count((*iit)->GetSharedTx()->GetHash())) {
202 testSet.erase(iit++);
203 } else {
204 iit++;
205 }
206 }
207}
208
209bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
210{
211 // TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
212 if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= m_options.nBlockMaxWeight) {
213 return false;
214 }
215 if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST) {
216 return false;
217 }
218 return true;
219}
220
221// Perform transaction-level checks before adding to block:
222// - transaction finality (locktime)
223bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package) const
224{
225 for (CTxMemPool::txiter it : package) {
226 if (!IsFinalTx(it->GetTx(), nHeight, m_lock_time_cutoff)) {
227 return false;
228 }
229 }
230 return true;
231}
232
233void BlockAssembler::AddToBlock(CTxMemPool::txiter iter)
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->GetSharedTx()->GetHash());
243
244 if (m_options.print_modified_fee) {
245 LogPrintf("fee rate %s txid %s\n",
246 CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
247 iter->GetTx().GetHash().ToString());
248 }
249}
250
254static int UpdatePackagesForAdded(const CTxMemPool& mempool,
255 const CTxMemPool::setEntries& alreadyAdded,
257{
258 AssertLockHeld(mempool.cs);
259
260 int nDescendantsUpdated = 0;
261 for (CTxMemPool::txiter it : alreadyAdded) {
262 CTxMemPool::setEntries descendants;
263 mempool.CalculateDescendants(it, descendants);
264 // Insert all descendants (not yet in block) into the modified set
265 for (CTxMemPool::txiter desc : descendants) {
266 if (alreadyAdded.count(desc)) {
267 continue;
268 }
269 ++nDescendantsUpdated;
270 modtxiter mit = mapModifiedTx.find(desc);
271 if (mit == mapModifiedTx.end()) {
272 CTxMemPoolModifiedEntry modEntry(desc);
273 mit = mapModifiedTx.insert(modEntry).first;
274 }
275 mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
276 }
277 }
278 return nDescendantsUpdated;
279}
280
281void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, std::vector<CTxMemPool::txiter>& sortedEntries)
282{
283 // Sort package by ancestor count
284 // If a transaction A depends on transaction B, then A's ancestor count
285 // must be greater than B's. So this is sufficient to validly order the
286 // transactions for block inclusion.
287 sortedEntries.clear();
288 sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
289 std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
290}
291
292// This transaction selection algorithm orders the mempool based
293// on feerate of a transaction including all unconfirmed ancestors.
294// Since we don't remove transactions from the mempool as we select them
295// for block inclusion, we need an alternate method of updating the feerate
296// of a transaction with its not-yet-selected ancestors as we go.
297// This is accomplished by walking the in-mempool descendants of selected
298// transactions and storing a temporary modified state in mapModifiedTxs.
299// Each time through the loop, we compare the best transaction in
300// mapModifiedTxs with the next transaction in the mempool to decide what
301// transaction package to work on next.
302void BlockAssembler::addPackageTxs(int& nPackagesSelected, int& nDescendantsUpdated)
303{
304 const auto& mempool{*Assert(m_mempool)};
305 LOCK(mempool.cs);
306
307 // mapModifiedTx will store sorted packages after they are modified
308 // because some of their txs are already in the block
310 // Keep track of entries that failed inclusion, to avoid duplicate work
311 std::set<Txid> failedTx;
312
313 CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin();
315
316 // Limit the number of attempts to add transactions to the block when it is
317 // close to full; this is just a simple heuristic to finish quickly if the
318 // mempool has a lot of entries.
319 const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
320 constexpr int32_t BLOCK_FULL_ENOUGH_WEIGHT_DELTA = 4000;
321 int64_t nConsecutiveFailed = 0;
322
323 while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty()) {
324 // First try to find a new transaction in mapTx to evaluate.
325 //
326 // Skip entries in mapTx that are already in a block or are present
327 // in mapModifiedTx (which implies that the mapTx ancestor state is
328 // stale due to ancestor inclusion in the block)
329 // Also skip transactions that we've already failed to add. This can happen if
330 // we consider a transaction in mapModifiedTx and it fails: we can then
331 // potentially consider it again while walking mapTx. It's currently
332 // guaranteed to fail again, but as a belt-and-suspenders check we put it in
333 // failedTx and avoid re-evaluation, since the re-evaluation would be using
334 // cached size/sigops/fee values that are not actually correct.
337 if (mi != mempool.mapTx.get<ancestor_score>().end()) {
338 auto it = mempool.mapTx.project<0>(mi);
339 assert(it != mempool.mapTx.end());
340 if (mapModifiedTx.count(it) || inBlock.count(it->GetSharedTx()->GetHash()) || failedTx.count(it->GetSharedTx()->GetHash())) {
341 ++mi;
342 continue;
343 }
344 }
345
346 // Now that mi is not stale, determine which transaction to evaluate:
347 // the next entry from mapTx, or the best from mapModifiedTx?
348 bool fUsingModified = false;
349
350 modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
351 if (mi == mempool.mapTx.get<ancestor_score>().end()) {
352 // We're out of entries in mapTx; use the entry from mapModifiedTx
353 iter = modit->iter;
354 fUsingModified = true;
355 } else {
356 // Try to compare the mapTx entry to the mapModifiedTx entry
357 iter = mempool.mapTx.project<0>(mi);
358 if (modit != mapModifiedTx.get<ancestor_score>().end() &&
360 // The best entry in mapModifiedTx has higher score
361 // than the one from mapTx.
362 // Switch which transaction (package) to consider
363 iter = modit->iter;
364 fUsingModified = true;
365 } else {
366 // Either no entry in mapModifiedTx, or it's worse than mapTx.
367 // Increment mi for the next loop iteration.
368 ++mi;
369 }
370 }
371
372 // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
373 // contain anything that is inBlock.
374 assert(!inBlock.count(iter->GetSharedTx()->GetHash()));
375
376 uint64_t packageSize = iter->GetSizeWithAncestors();
377 CAmount packageFees = iter->GetModFeesWithAncestors();
378 int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
379 if (fUsingModified) {
380 packageSize = modit->nSizeWithAncestors;
381 packageFees = modit->nModFeesWithAncestors;
382 packageSigOpsCost = modit->nSigOpCostWithAncestors;
383 }
384
385 if (packageFees < m_options.blockMinFeeRate.GetFee(packageSize)) {
386 // Everything else we might consider has a lower fee rate
387 return;
388 }
389
390 if (!TestPackage(packageSize, packageSigOpsCost)) {
391 if (fUsingModified) {
392 // Since we always look at the best entry in mapModifiedTx,
393 // we must erase failed entries so that we can consider the
394 // next best entry on the next loop iteration
395 mapModifiedTx.get<ancestor_score>().erase(modit);
396 failedTx.insert(iter->GetSharedTx()->GetHash());
397 }
398
399 ++nConsecutiveFailed;
400
401 if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight >
402 m_options.nBlockMaxWeight - BLOCK_FULL_ENOUGH_WEIGHT_DELTA) {
403 // Give up if we're close to full and haven't succeeded in a while
404 break;
405 }
406 continue;
407 }
408
409 auto ancestors{mempool.AssumeCalculateMemPoolAncestors(__func__, *iter, CTxMemPool::Limits::NoLimits(), /*fSearchForParents=*/false)};
410
411 onlyUnconfirmed(ancestors);
412 ancestors.insert(iter);
413
414 // Test if all tx's are Final
415 if (!TestPackageTransactions(ancestors)) {
416 if (fUsingModified) {
417 mapModifiedTx.get<ancestor_score>().erase(modit);
418 failedTx.insert(iter->GetSharedTx()->GetHash());
419 }
420 continue;
421 }
422
423 // This transaction will make it in; reset the failed counter.
424 nConsecutiveFailed = 0;
425
426 // Package can be added. Sort the entries in a valid order.
427 std::vector<CTxMemPool::txiter> sortedEntries;
428 SortForBlock(ancestors, sortedEntries);
429
430 for (size_t i = 0; i < sortedEntries.size(); ++i) {
431 AddToBlock(sortedEntries[i]);
432 // Erase from the modified set, if present
433 mapModifiedTx.erase(sortedEntries[i]);
434 }
435
436 ++nPackagesSelected;
437 pblocktemplate->m_package_feerates.emplace_back(packageFees, static_cast<int32_t>(packageSize));
438
439 // Update transactions that depend on each of these
440 nDescendantsUpdated += UpdatePackagesForAdded(mempool, ancestors, mapModifiedTx);
441 }
442}
443
444void AddMerkleRootAndCoinbase(CBlock& block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce)
445{
446 if (block.vtx.size() == 0) {
447 block.vtx.emplace_back(coinbase);
448 } else {
449 block.vtx[0] = coinbase;
450 }
451 block.nVersion = version;
452 block.nTime = timestamp;
453 block.nNonce = nonce;
454 block.hashMerkleRoot = BlockMerkleRoot(block);
455}
456
457std::unique_ptr<CBlockTemplate> WaitAndCreateNewBlock(ChainstateManager& chainman,
458 KernelNotifications& kernel_notifications,
459 CTxMemPool* mempool,
460 const std::unique_ptr<CBlockTemplate>& block_template,
461 const BlockWaitOptions& options,
462 const BlockAssembler::Options& assemble_options)
463{
464 // Delay calculating the current template fees, just in case a new block
465 // comes in before the next tick.
466 CAmount current_fees = -1;
467
468 // Alternate waiting for a new tip and checking if fees have risen.
469 // The latter check is expensive so we only run it once per second.
470 auto now{NodeClock::now()};
471 const auto deadline = now + options.timeout;
472 const MillisecondsDouble tick{1000};
473 const bool allow_min_difficulty{chainman.GetParams().GetConsensus().fPowAllowMinDifficultyBlocks};
474
475 do {
476 bool tip_changed{false};
477 {
478 WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
479 // Note that wait_until() checks the predicate before waiting
480 kernel_notifications.m_tip_block_cv.wait_until(lock, std::min(now + tick, deadline), [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
481 AssertLockHeld(kernel_notifications.m_tip_block_mutex);
482 const auto tip_block{kernel_notifications.TipBlock()};
483 // We assume tip_block is set, because this is an instance
484 // method on BlockTemplate and no template could have been
485 // generated before a tip exists.
486 tip_changed = Assume(tip_block) && tip_block != block_template->block.hashPrevBlock;
487 return tip_changed || chainman.m_interrupt;
488 });
489 }
490
491 if (chainman.m_interrupt) return nullptr;
492 // At this point the tip changed, a full tick went by or we reached
493 // the deadline.
494
495 // Must release m_tip_block_mutex before locking cs_main, to avoid deadlocks.
497
498 // On test networks return a minimum difficulty block after 20 minutes
499 if (!tip_changed && allow_min_difficulty) {
500 const NodeClock::time_point tip_time{std::chrono::seconds{chainman.ActiveChain().Tip()->GetBlockTime()}};
501 if (now > tip_time + 20min) {
502 tip_changed = true;
503 }
504 }
505
514 if (options.fee_threshold < MAX_MONEY || tip_changed) {
515 auto new_tmpl{BlockAssembler{
516 chainman.ActiveChainstate(),
517 mempool,
518 assemble_options}
519 .CreateNewBlock()};
520
521 // If the tip changed, return the new template regardless of its fees.
522 if (tip_changed) return new_tmpl;
523
524 // Calculate the original template total fees if we haven't already
525 if (current_fees == -1) {
526 current_fees = 0;
527 for (CAmount fee : block_template->vTxFees) {
528 current_fees += fee;
529 }
530 }
531
532 CAmount new_fees = 0;
533 for (CAmount fee : new_tmpl->vTxFees) {
534 new_fees += fee;
535 Assume(options.fee_threshold != MAX_MONEY);
536 if (new_fees >= current_fees + options.fee_threshold) return new_tmpl;
537 }
538 }
539
540 now = NodeClock::now();
541 } while (now < deadline);
542
543 return nullptr;
544}
545
546std::optional<BlockRef> GetTip(ChainstateManager& chainman)
547{
549 CBlockIndex* tip{chainman.ActiveChain().Tip()};
550 if (!tip) return {};
551 return BlockRef{tip->GetBlockHash(), tip->nHeight};
552}
553
554std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const uint256& current_tip, MillisecondsDouble& timeout)
555{
556 Assume(timeout >= 0ms); // No internal callers should use a negative timeout
557 if (timeout < 0ms) timeout = 0ms;
558 if (timeout > std::chrono::years{100}) timeout = std::chrono::years{100}; // Upper bound to avoid UB in std::chrono
559 auto deadline{std::chrono::steady_clock::now() + timeout};
560 {
561 WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
562 // For callers convenience, wait longer than the provided timeout
563 // during startup for the tip to be non-null. That way this function
564 // always returns valid tip information when possible and only
565 // returns null when shutting down, not when timing out.
566 kernel_notifications.m_tip_block_cv.wait(lock, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
567 return kernel_notifications.TipBlock() || chainman.m_interrupt;
568 });
569 if (chainman.m_interrupt) return {};
570 // At this point TipBlock is set, so continue to wait until it is
571 // different then `current_tip` provided by caller.
572 kernel_notifications.m_tip_block_cv.wait_until(lock, deadline, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
573 return Assume(kernel_notifications.TipBlock()) != current_tip || chainman.m_interrupt;
574 });
575 }
576 if (chainman.m_interrupt) return {};
577
578 // Must release m_tip_block_mutex before getTip() locks cs_main, to
579 // avoid deadlocks.
580 return GetTip(chainman);
581}
582} // namespace node
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:26
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
ArgsManager gArgs
Definition: args.cpp:42
ArgsManager & args
Definition: bitcoind.cpp:277
#define Assert(val)
Identity function.
Definition: check.h:106
#define Assume(val)
Assume is the identity function.
Definition: check.h:118
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: args.cpp:482
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: args.cpp:457
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:507
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:141
uint256 GetBlockHash() const
Definition: chain.h:243
int64_t GetBlockTime() const
Definition: chain.h:266
int64_t GetMedianTimePast() const
Definition: chain.h:278
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:153
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:433
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:81
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
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:415
static const uint32_t MAX_SEQUENCE_NONFINAL
This is the maximum sequence number that enables both nLockTime and OP_CHECKLOCKTIMEVERIFY (BIP 65).
Definition: transaction.h:87
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:304
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:396
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:393
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:507
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:867
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
Definition: validation.h:1109
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...
const util::SignalInterrupt & m_interrupt
Definition: validation.h:1002
const CChainParams & GetParams() const
Definition: validation.h:975
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1110
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1006
Definition: txmempool.h:164
std::string ToString() const
Definition: validation.h:111
Generate a new block, without valid proof-of-work.
Definition: miner.h:151
BlockAssembler(Chainstate &chainstate, const CTxMemPool *mempool, const Options &options)
Definition: miner.cpp:89
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
256-bit opaque blob.
Definition: uint256.h:196
static int64_t GetBlockWeight(const CBlock &block)
Definition: validation.h:136
int GetWitnessCommitmentIndex(const CBlock &block)
Compute at which vout of the block's coinbase transaction the witness commitment occurs,...
Definition: validation.h:147
static constexpr int64_t MAX_TIMEWARP
Maximum number of seconds that the timestamp of the first block of a difficulty adjustment period is ...
Definition: consensus.h:35
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
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
#define LogDebug(category,...)
Definition: logging.h:280
#define LogPrintf(...)
Definition: logging.h:266
unsigned int nHeight
uint64_t fee
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:66
unsigned int nonce
Definition: miner_tests.cpp:74
std::optional< CAmount > ParseMoney(const std::string &money_string)
Parse an amount denoted in full coins.
Definition: moneystr.cpp:45
@ BENCH
Definition: logging.h:47
Definition: messages.h:20
static BlockAssembler::Options ClampOptions(BlockAssembler::Options options)
Definition: miner.cpp:78
boost::multi_index_container< CTxMemPoolModifiedEntry, CTxMemPoolModifiedEntry_Indices > indexed_modified_transaction_set
Definition: miner.h:130
indexed_modified_transaction_set::nth_index< 0 >::type::iterator modtxiter
Definition: miner.h:132
void RegenerateCommitments(CBlock &block, ChainstateManager &chainman)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed.
Definition: miner.cpp:66
int64_t GetMinimumTime(const CBlockIndex *pindexPrev, const int64_t difficulty_adjustment_interval)
Get the minimum time a miner should use in the next block.
Definition: miner.cpp:35
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:48
indexed_modified_transaction_set::index< ancestor_score >::type::iterator modtxscoreiter
Definition: miner.h:133
util::Result< void > ApplyArgsManOptions(const ArgsManager &args, BlockManager::Options &opts)
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:254
std::optional< BlockRef > WaitTipChanged(ChainstateManager &chainman, KernelNotifications &kernel_notifications, const uint256 &current_tip, MillisecondsDouble &timeout)
Definition: miner.cpp:554
std::unique_ptr< CBlockTemplate > WaitAndCreateNewBlock(ChainstateManager &chainman, KernelNotifications &kernel_notifications, CTxMemPool *mempool, const std::unique_ptr< CBlockTemplate > &block_template, const BlockWaitOptions &options, const BlockAssembler::Options &assemble_options)
Return a new block template when fees rise to a certain threshold or after a new tip; return nullopt ...
Definition: miner.cpp:457
void AddMerkleRootAndCoinbase(CBlock &block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce)
Definition: miner.cpp:444
std::optional< BlockRef > GetTip(ChainstateManager &chainman)
Definition: miner.cpp:546
static constexpr unsigned int MINIMUM_BLOCK_RESERVED_WEIGHT
This accounts for the block header, var_int encoding of the transaction count and a minimally viable ...
Definition: policy.h:30
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock, const Consensus::Params &params)
Definition: pow.cpp:14
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:424
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
@ OP_0
Definition: script.h:76
A mutable version of CTransaction.
Definition: transaction.h:378
std::vector< CTxOut > vout
Definition: transaction.h:380
std::vector< CTxIn > vin
Definition: transaction.h:379
Parameters that influence chain consensus.
Definition: params.h:83
int64_t DifficultyAdjustmentInterval() const
Definition: params.h:125
bool fPowAllowMinDifficultyBlocks
Definition: params.h:112
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition: time.cpp:26
std::chrono::time_point< NodeClock > time_point
Definition: time.h:19
Hash/height pair to help track and identify blocks.
Definition: types.h:13
static constexpr MemPoolLimits NoLimits()
size_t block_reserved_weight
The default reserved weight for the fixed-size block header, transaction count and coinbase transacti...
Definition: types.h:43
size_t coinbase_output_max_additional_sigops
The maximum additional sigops which the pool will add in coinbase transaction outputs.
Definition: types.h:48
MillisecondsDouble timeout
How long to wait before returning nullptr instead of a new template.
Definition: types.h:72
CAmount fee_threshold
The wait method will not return a new template unless it has fees at least fee_threshold sats higher ...
Definition: types.h:85
Definition: miner.h:57
#define WAIT_LOCK(cs, name)
Definition: sync.h:263
#define LOCK(cs)
Definition: sync.h:257
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:302
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
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
std::chrono::duration< double, std::chrono::milliseconds::period > MillisecondsDouble
Definition: time.h:88
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, Chainstate &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)
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())