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