Bitcoin Core 31.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-present 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 <common/args.h>
11#include <consensus/amount.h>
12#include <consensus/consensus.h>
13#include <consensus/merkle.h>
14#include <consensus/params.h>
15#include <consensus/tx_verify.h>
17#include <interfaces/types.h>
18#include <node/blockstorage.h>
20#include <node/mining_args.h>
21#include <node/mining_types.h>
22#include <policy/feerate.h>
23#include <policy/policy.h>
24#include <pow.h>
25#include <primitives/block.h>
27#include <script/script.h>
28#include <sync.h>
29#include <tinyformat.h>
30#include <txgraph.h>
31#include <txmempool.h>
32#include <uint256.h>
33#include <util/check.h>
34#include <util/feefrac.h>
35#include <util/log.h>
36#include <util/result.h>
38#include <util/time.h>
39#include <util/translation.h>
40#include <validation.h>
41#include <validationinterface.h>
42#include <versionbits.h>
43
44#include <algorithm>
45#include <compare>
46#include <condition_variable>
47#include <cstddef>
48#include <functional>
49#include <numeric>
50#include <span>
51#include <stdexcept>
52#include <string>
53#include <utility>
54
55namespace node {
56
57int64_t GetMinimumTime(const CBlockIndex* pindexPrev, const int64_t difficulty_adjustment_interval)
58{
59 int64_t min_time{pindexPrev->GetMedianTimePast() + 1};
60 // Height of block to be mined.
61 const int height{pindexPrev->nHeight + 1};
62 // Account for BIP94 timewarp rule on all networks. This makes future
63 // activation safer.
64 if (height % difficulty_adjustment_interval == 0) {
65 min_time = std::max<int64_t>(min_time, pindexPrev->GetBlockTime() - MAX_TIMEWARP);
66 }
67 return min_time;
68}
69
70int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
71{
72 int64_t nOldTime = pblock->nTime;
73 int64_t nNewTime{std::max<int64_t>(GetMinimumTime(pindexPrev, consensusParams.DifficultyAdjustmentInterval()),
74 TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()))};
75
76 if (nOldTime < nNewTime) {
77 pblock->nTime = nNewTime;
78 }
79
80 // Updating time can change work required on testnet:
81 if (consensusParams.fPowAllowMinDifficultyBlocks) {
82 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
83 }
84
85 return nNewTime - nOldTime;
86}
87
89{
90 CMutableTransaction tx{*block.vtx.at(0)};
91 tx.vout.erase(tx.vout.begin() + GetWitnessCommitmentIndex(block));
92 block.vtx.at(0) = MakeTransactionRef(tx);
93
94 const CBlockIndex* prev_block = WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock));
95 chainman.GenerateCoinbaseCommitment(block, prev_block);
96
97 block.hashMerkleRoot = BlockMerkleRoot(block);
98}
99
101 const CTxMemPool* mempool,
102 BlockCreateOptions options)
103 : chainparams{chainstate.m_chainman.GetParams()},
104 m_mempool{options.use_mempool ? mempool : nullptr},
105 m_chainstate{chainstate},
106 m_options{[&] {
107 if (auto result{CheckMiningOptions(options, /*use_argnames=*/false)}; !result) {
108 throw std::runtime_error(util::ErrorString(result).original);
109 }
110 return FlattenMiningOptions(std::move(options));
111 }()}
112{
113}
114
115void BlockAssembler::resetBlock()
116{
117 // Reserve space for fixed-size block header, txs count, and coinbase tx.
118 nBlockWeight = *Assert(m_options.block_reserved_weight);
119 nBlockSigOpsCost = m_options.coinbase_output_max_additional_sigops;
120
121 // These counters do not include coinbase tx
122 nBlockTx = 0;
123 nFees = 0;
124}
125
126std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock()
127{
128 const auto time_start{SteadyClock::now()};
129
130 resetBlock();
131
132 pblocktemplate.reset(new CBlockTemplate());
133 CBlock* const pblock = &pblocktemplate->block; // pointer for convenience
134
135 // Add dummy coinbase tx as first transaction. It is skipped by the
136 // getblocktemplate RPC and mining interface consumers must not use it.
137 pblock->vtx.emplace_back();
138
140 CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip();
141 assert(pindexPrev != nullptr);
142 nHeight = pindexPrev->nHeight + 1;
143
144 pblock->nVersion = m_chainstate.m_chainman.m_versionbitscache.ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
145 // -regtest only: allow overriding block.nVersion with
146 // -blockversion=N to test forking scenarios
147 if (chainparams.MineBlocksOnDemand()) {
148 pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion);
149 }
150
151 pblock->nTime = TicksSinceEpoch<std::chrono::seconds>(NodeClock::now());
152 m_lock_time_cutoff = pindexPrev->GetMedianTimePast();
153
154 if (m_mempool) {
155 LOCK(m_mempool->cs);
156 m_mempool->StartBlockBuilding();
157 addChunks();
158 m_mempool->StopBlockBuilding();
159 }
160
161 const auto time_1{SteadyClock::now()};
162
163 m_last_block_num_txs = nBlockTx;
164 m_last_block_weight = nBlockWeight;
165
166 // Create coinbase transaction.
167 CMutableTransaction coinbaseTx;
168
169 // Construct coinbase transaction struct in parallel
170 CoinbaseTx& coinbase_tx{pblocktemplate->m_coinbase_tx};
171 coinbase_tx.version = coinbaseTx.version;
172
173 coinbaseTx.vin.resize(1);
174 coinbaseTx.vin[0].prevout.SetNull();
175 coinbaseTx.vin[0].nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; // Make sure timelock is enforced.
176 coinbase_tx.sequence = coinbaseTx.vin[0].nSequence;
177
178 // Add an output that spends the full coinbase reward.
179 coinbaseTx.vout.resize(1);
180 coinbaseTx.vout[0].scriptPubKey = m_options.coinbase_output_script;
181 // Block subsidy + fees
182 const CAmount block_reward{nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus())};
183 coinbaseTx.vout[0].nValue = block_reward;
184 coinbase_tx.block_reward_remaining = block_reward;
185
186 // Start the coinbase scriptSig with the block height as required by BIP34.
187 // Mining clients are expected to append extra data to this prefix, so
188 // increasing its length would reduce the space they can use and may break
189 // existing clients.
190 coinbaseTx.vin[0].scriptSig = CScript() << nHeight;
191 // Set script_sig_prefix here, so IPC mining clients are not affected by
192 // the optional scriptSig padding below. They provide their own extraNonce,
193 // and in a typical setup a pool name or realistic extraNonce already makes
194 // the scriptSig long enough.
195 coinbase_tx.script_sig_prefix = coinbaseTx.vin[0].scriptSig;
196 if (nHeight <= 16) {
197 // For blocks at heights <= 16, the BIP34-encoded height alone is only
198 // one byte. Consensus requires coinbase scriptSigs to be at least two
199 // bytes long (bad-cb-length), so an OP_0 is always appended at those
200 // heights.
201 coinbaseTx.vin[0].scriptSig << OP_0;
202 }
203 Assert(nHeight > 0);
204 coinbaseTx.nLockTime = static_cast<uint32_t>(nHeight - 1);
205 coinbase_tx.lock_time = coinbaseTx.nLockTime;
206
207 pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
208 m_chainstate.m_chainman.GenerateCoinbaseCommitment(*pblock, pindexPrev);
209
210 const CTransactionRef& final_coinbase{pblock->vtx[0]};
211 if (final_coinbase->HasWitness()) {
212 const auto& witness_stack{final_coinbase->vin[0].scriptWitness.stack};
213 // Consensus requires the coinbase witness stack to have exactly one
214 // element of 32 bytes.
215 Assert(witness_stack.size() == 1 && witness_stack[0].size() == 32);
216 coinbase_tx.witness = uint256(witness_stack[0]);
217 }
218 if (const int witness_index = GetWitnessCommitmentIndex(*pblock); witness_index != NO_WITNESS_COMMITMENT) {
219 Assert(witness_index >= 0 && static_cast<size_t>(witness_index) < final_coinbase->vout.size());
220 coinbase_tx.required_outputs.push_back(final_coinbase->vout[witness_index]);
221 }
222
223 LogInfo("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
224
225 // Fill in header
226 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
227 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
228 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
229 pblock->nNonce = 0;
230
231 if (m_options.test_block_validity) {
232 if (BlockValidationState state{TestBlockValidity(m_chainstate, *pblock, /*check_pow=*/false, /*check_merkle_root=*/false)}; !state.IsValid()) {
233 throw std::runtime_error(strprintf("TestBlockValidity failed: %s", state.ToString()));
234 }
235 }
236 const auto time_2{SteadyClock::now()};
237
238 LogDebug(BCLog::BENCH, "CreateNewBlock() chunks: %.2fms, validity: %.2fms (total %.2fms)\n",
239 Ticks<MillisecondsDouble>(time_1 - time_start),
240 Ticks<MillisecondsDouble>(time_2 - time_1),
241 Ticks<MillisecondsDouble>(time_2 - time_start));
242
243 return std::move(pblocktemplate);
244}
245
246bool BlockAssembler::TestChunkBlockLimits(FeePerWeight chunk_feerate, int64_t chunk_sigops_cost) const
247{
248 // block_max_weight has been flattened before block assembly limit checks.
249 Assert(m_options.block_max_weight);
250 if (nBlockWeight + chunk_feerate.size >= *m_options.block_max_weight) {
251 return false;
252 }
253 if (nBlockSigOpsCost + chunk_sigops_cost >= MAX_BLOCK_SIGOPS_COST) {
254 return false;
255 }
256 return true;
257}
258
259// Perform transaction-level checks before adding to block:
260// - transaction finality (locktime)
261bool BlockAssembler::TestChunkTransactions(const std::vector<CTxMemPoolEntryRef>& txs) const
262{
263 for (const auto tx : txs) {
264 if (!IsFinalTx(tx.get().GetTx(), nHeight, m_lock_time_cutoff)) {
265 return false;
266 }
267 }
268 return true;
269}
270
271void BlockAssembler::AddToBlock(const CTxMemPoolEntry& entry)
272{
273 pblocktemplate->block.vtx.emplace_back(entry.GetSharedTx());
274 pblocktemplate->vTxFees.push_back(entry.GetFee());
275 pblocktemplate->vTxSigOpsCost.push_back(entry.GetSigOpCost());
276 nBlockWeight += entry.GetTxWeight();
277 ++nBlockTx;
278 nBlockSigOpsCost += entry.GetSigOpCost();
279 nFees += entry.GetFee();
280
281 if (*m_options.print_modified_fee) {
282 LogInfo("fee rate %s txid %s\n",
283 CFeeRate(entry.GetModifiedFee(), entry.GetTxSize()).ToString(),
284 entry.GetTx().GetHash().ToString());
285 }
286}
287
288void BlockAssembler::addChunks()
289{
290 // Limit the number of attempts to add transactions to the block when it is
291 // close to full; this is just a simple heuristic to finish quickly if the
292 // mempool has a lot of entries.
293 const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
294 constexpr int32_t BLOCK_FULL_ENOUGH_WEIGHT_DELTA = 4000;
295 int64_t nConsecutiveFailed = 0;
296
297 std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> selected_transactions;
298 selected_transactions.reserve(MAX_CLUSTER_COUNT_LIMIT);
299 FeePerWeight chunk_feerate;
300
301 // This fills selected_transactions
302 chunk_feerate = m_mempool->GetBlockBuilderChunk(selected_transactions);
303 FeePerVSize chunk_feerate_vsize = ToFeePerVSize(chunk_feerate);
304
305 while (selected_transactions.size() > 0) {
306 // Check to see if min fee rate is still respected.
307 if (ByRatio{chunk_feerate_vsize} < ByRatio{m_options.block_min_fee_rate->GetFeePerVSize()}) {
308 // Everything else we might consider has a lower feerate
309 return;
310 }
311
312 int64_t chunk_sig_ops = 0;
313 for (const auto& tx : selected_transactions) {
314 chunk_sig_ops += tx.get().GetSigOpCost();
315 }
316
317 // Check to see if this chunk will fit.
318 if (!TestChunkBlockLimits(chunk_feerate, chunk_sig_ops) || !TestChunkTransactions(selected_transactions)) {
319 // This chunk won't fit, so we skip it and will try the next best one.
320 m_mempool->SkipBuilderChunk();
321 ++nConsecutiveFailed;
322
323 // block_max_weight has been flattened before block assembly limit checks.
324 Assert(m_options.block_max_weight);
325 if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight +
326 BLOCK_FULL_ENOUGH_WEIGHT_DELTA > *m_options.block_max_weight) {
327 // Give up if we're close to full and haven't succeeded in a while
328 return;
329 }
330 } else {
331 m_mempool->IncludeBuilderChunk();
332
333 // This chunk will fit, so add it to the block.
334 nConsecutiveFailed = 0;
335 for (const auto& tx : selected_transactions) {
336 AddToBlock(tx);
337 }
338 pblocktemplate->m_package_feerates.emplace_back(chunk_feerate_vsize);
339 }
340
341 selected_transactions.clear();
342 chunk_feerate = m_mempool->GetBlockBuilderChunk(selected_transactions);
343 chunk_feerate_vsize = ToFeePerVSize(chunk_feerate);
344 }
345}
346
347void AddMerkleRootAndCoinbase(CBlock& block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce)
348{
349 if (block.vtx.size() == 0) {
350 block.vtx.emplace_back(coinbase);
351 } else {
352 block.vtx[0] = coinbase;
353 }
354 block.nVersion = version;
355 block.nTime = timestamp;
356 block.nNonce = nonce;
357 block.hashMerkleRoot = BlockMerkleRoot(block);
358
359 // Reset cached checks
360 block.m_checked_witness_commitment = false;
361 block.m_checked_merkle_root = false;
362 block.fChecked = false;
363}
364
365namespace {
366class SubmitBlockStateCatcher final : public CValidationInterface
367{
368public:
370 bool m_found{false};
372
373 explicit SubmitBlockStateCatcher(const uint256& hash) : m_hash{hash} {}
374
375protected:
376 void BlockChecked(const std::shared_ptr<const CBlock>& block, const BlockValidationState& state) override
377 {
378 if (block->GetHash() != m_hash) return;
379 // ProcessNewBlock emits BlockChecked synchronously while holding cs_main,
380 // so SubmitBlock can read these fields after ProcessNewBlock returns
381 // without extra synchronization.
382 m_found = true;
383 m_state = state;
384 }
385};
386} // namespace
387
388bool SubmitBlock(ChainstateManager& chainman, const std::shared_ptr<const CBlock>& block, bool* new_block, std::string& reason, std::string& debug)
389{
390 reason.clear();
391 debug.clear();
392
393 // This follows the submitblock RPC's validation-state capture pattern, but
394 // is intentionally kept separate from the RPC implementation. The RPC entry
395 // point decodes hex, formats BIP22/JSONRPC results, and calls
396 // UpdateUncommittedBlockStructures() for legacy witness handling. IPC
397 // callers submit already-formed blocks and need bool + reason/debug
398 // results, while submitSolution() preserves its duplicate-as-success
399 // behavior.
400 auto sc = std::make_shared<SubmitBlockStateCatcher>(block->GetHash());
401 CHECK_NONFATAL(chainman.m_options.signals)->RegisterSharedValidationInterface(sc);
402 bool accepted = chainman.ProcessNewBlock(block, /*force_processing=*/true, /*min_pow_checked=*/true, /*new_block=*/new_block);
403 CHECK_NONFATAL(chainman.m_options.signals)->UnregisterSharedValidationInterface(sc);
404
405 if (new_block && !*new_block && accepted) {
406 reason = "duplicate";
407 } else if (!sc->m_found) {
408 // A block can be accepted and stored without being connected, for
409 // example if it does not have more work than the current tip. In that
410 // case no BlockChecked callback is emitted, so the validation result is
411 // inconclusive. Mining::submitBlock treats this as an error for mining
412 // clients, but it does not mean the block is invalid.
413 reason = "inconclusive";
414 } else if (!sc->m_state.IsValid()) {
415 reason = sc->m_state.GetRejectReason();
416 debug = sc->m_state.GetDebugMessage();
417 }
418 return accepted;
419}
420
421void InterruptWait(KernelNotifications& kernel_notifications, bool& interrupt_wait)
422{
423 LOCK(kernel_notifications.m_tip_block_mutex);
424 interrupt_wait = true;
425 kernel_notifications.m_tip_block_cv.notify_all();
426}
427
428std::unique_ptr<CBlockTemplate> WaitAndCreateNewBlock(ChainstateManager& chainman,
429 KernelNotifications& kernel_notifications,
430 CTxMemPool* mempool,
431 const std::unique_ptr<CBlockTemplate>& block_template,
432 const BlockWaitOptions& wait_options,
433 const BlockCreateOptions& create_options,
434 bool& interrupt_wait)
435{
436 // Delay calculating the current template fees, just in case a new block
437 // comes in before the next tick.
438 CAmount current_fees = -1;
439
440 // Alternate waiting for a new tip and checking if fees have risen.
441 // The latter check is expensive so we only run it once per second.
442 auto now{NodeClock::now()};
443 const auto deadline = now + wait_options.timeout;
444 const MillisecondsDouble tick{1000};
445 const bool allow_min_difficulty{chainman.GetParams().GetConsensus().fPowAllowMinDifficultyBlocks};
446
447 do {
448 bool tip_changed{false};
449 {
450 WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
451 // Note that wait_until() checks the predicate before waiting
452 kernel_notifications.m_tip_block_cv.wait_until(lock, std::min(now + tick, deadline), [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
453 AssertLockHeld(kernel_notifications.m_tip_block_mutex);
454 const auto tip_block{kernel_notifications.TipBlock()};
455 // We assume tip_block is set, because this is an instance
456 // method on BlockTemplate and no template could have been
457 // generated before a tip exists.
458 tip_changed = Assume(tip_block) && tip_block != block_template->block.hashPrevBlock;
459 return tip_changed || chainman.m_interrupt || interrupt_wait;
460 });
461 if (interrupt_wait) {
462 interrupt_wait = false;
463 return nullptr;
464 }
465 }
466
467 if (chainman.m_interrupt) return nullptr;
468 // At this point the tip changed, a full tick went by or we reached
469 // the deadline.
470
471 // Must release m_tip_block_mutex before locking cs_main, to avoid deadlocks.
473
474 // On test networks return a minimum difficulty block after 20 minutes
475 if (!tip_changed && allow_min_difficulty) {
476 const NodeClock::time_point tip_time{std::chrono::seconds{chainman.ActiveChain().Tip()->GetBlockTime()}};
477 if (now > tip_time + 20min) {
478 tip_changed = true;
479 }
480 }
481
490 if (wait_options.fee_threshold < MAX_MONEY || tip_changed) {
491 auto new_tmpl{BlockAssembler{
492 chainman.ActiveChainstate(),
493 mempool,
494 create_options
495 }.CreateNewBlock()};
496
497 // If the tip changed, return the new template regardless of its fees.
498 if (tip_changed) return new_tmpl;
499
500 // Calculate the original template total fees if we haven't already
501 if (current_fees == -1) {
502 current_fees = std::accumulate(block_template->vTxFees.begin(), block_template->vTxFees.end(), CAmount{0});
503 }
504
505 // Check if fees increased enough to return the new template
506 const CAmount new_fees = std::accumulate(new_tmpl->vTxFees.begin(), new_tmpl->vTxFees.end(), CAmount{0});
507 Assume(wait_options.fee_threshold != MAX_MONEY);
508 if (new_fees >= current_fees + wait_options.fee_threshold) return new_tmpl;
509 }
510
511 now = NodeClock::now();
512 } while (now < deadline);
513
514 return nullptr;
515}
516
517std::optional<BlockRef> GetTip(ChainstateManager& chainman)
518{
520 CBlockIndex* tip{chainman.ActiveChain().Tip()};
521 if (!tip) return {};
522 return BlockRef{tip->GetBlockHash(), tip->nHeight};
523}
524
525bool CooldownIfHeadersAhead(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const BlockRef& last_tip, bool& interrupt_mining)
526{
527 uint256 last_tip_hash{last_tip.hash};
528
529 while (const std::optional<int> remaining = chainman.BlocksAheadOfTip()) {
530 const int cooldown_seconds = std::clamp(*remaining, 3, 20);
531 const auto cooldown_deadline{MockableSteadyClock::now() + std::chrono::seconds{cooldown_seconds}};
532
533 {
534 WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
535 kernel_notifications.m_tip_block_cv.wait_until(lock, cooldown_deadline, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
536 const auto tip_block = kernel_notifications.TipBlock();
537 return chainman.m_interrupt || interrupt_mining || (tip_block && *tip_block != last_tip_hash);
538 });
539 if (chainman.m_interrupt || interrupt_mining) {
540 interrupt_mining = false;
541 return false;
542 }
543
544 // If the tip changed during the wait, extend the deadline
545 const auto tip_block = kernel_notifications.TipBlock();
546 if (tip_block && *tip_block != last_tip_hash) {
547 last_tip_hash = *tip_block;
548 continue;
549 }
550 }
551
552 // No tip change and the cooldown window has expired.
553 if (MockableSteadyClock::now() >= cooldown_deadline) break;
554 }
555
556 return true;
557}
558
559std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const uint256& current_tip, MillisecondsDouble& timeout, bool& interrupt)
560{
561 Assume(timeout >= 0ms); // No internal callers should use a negative timeout
562 if (timeout < 0ms) timeout = 0ms;
563 if (timeout > std::chrono::years{100}) timeout = std::chrono::years{100}; // Upper bound to avoid UB in std::chrono
564 auto deadline{std::chrono::steady_clock::now() + timeout};
565 {
566 WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
567 // For callers convenience, wait longer than the provided timeout
568 // during startup for the tip to be non-null. That way this function
569 // always returns valid tip information when possible and only
570 // returns null when shutting down, not when timing out.
571 kernel_notifications.m_tip_block_cv.wait(lock, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
572 return kernel_notifications.TipBlock() || chainman.m_interrupt || interrupt;
573 });
574 if (chainman.m_interrupt || interrupt) {
575 interrupt = false;
576 return {};
577 }
578 // At this point TipBlock is set, so continue to wait until it is
579 // different then `current_tip` provided by caller.
580 kernel_notifications.m_tip_block_cv.wait_until(lock, deadline, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
581 return Assume(kernel_notifications.TipBlock()) != current_tip || chainman.m_interrupt || interrupt;
582 });
583 if (chainman.m_interrupt || interrupt) {
584 interrupt = false;
585 return {};
586 }
587 }
588
589 // Must release m_tip_block_mutex before getTip() locks cs_main, to
590 // avoid deadlocks.
591 return GetTip(chainman);
592}
593
594} // 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:40
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:112
#define Assert(val)
Identity function.
Definition: check.h:116
#define Assume(val)
Assume is the identity function.
Definition: check.h:128
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Definition: args.h:324
Wrapper around FeeFrac & derived types, which adds a feerate-based ordering which treats equal-feerat...
Definition: feefrac.h:219
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:27
uint32_t nNonce
Definition: block.h:35
uint32_t nBits
Definition: block.h:34
uint32_t nTime
Definition: block.h:33
int32_t nVersion
Definition: block.h:30
uint256 hashPrevBlock
Definition: block.h:31
uint256 hashMerkleRoot
Definition: block.h:32
Definition: block.h:74
bool m_checked_merkle_root
Definition: block.h:82
std::vector< CTransactionRef > vtx
Definition: block.h:77
bool m_checked_witness_commitment
Definition: block.h:81
bool fChecked
Definition: block.h:80
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:94
uint256 GetBlockHash() const
Definition: chain.h:198
int64_t GetBlockTime() const
Definition: chain.h:221
int64_t GetMedianTimePast() const
Definition: chain.h:233
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:106
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:396
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:89
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
Definition: feerate.h:32
std::string ToString(FeeRateFormat fee_rate_format=FeeRateFormat::BTC_KVB) const
Definition: feerate.cpp:29
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
const Txid & GetHash() const LIFETIMEBOUND
Definition: transaction.h:328
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:82
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: mempool_entry.h:66
const CTransaction & GetTx() const
int32_t GetTxWeight() const
int64_t GetSigOpCost() const
CTransactionRef GetSharedTx() const
int32_t GetTxSize() const
const CAmount & GetFee() const
CAmount GetModifiedFee() const
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:187
Implement this to subscribe to events generated in validation and mempool.
virtual void BlockChecked(const std::shared_ptr< const CBlock > &, const BlockValidationState &)
Notifies listeners of a block validation result.
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:554
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
Definition: validation.h:945
Chainstate & ActiveChainstate() const
Alternatives to CurrentChainstate() used by older code to query latest chainstate information without...
bool ProcessNewBlock(const std::shared_ptr< const CBlock > &block, bool force_processing, bool min_pow_checked, bool *new_block) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
const util::SignalInterrupt & m_interrupt
Definition: validation.h:1039
const CChainParams & GetParams() const
Definition: validation.h:1012
void 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 Options m_options
Definition: validation.h:1040
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1173
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1043
bool IsValid() const
Definition: validation.h:105
Generate a new block, without valid proof-of-work.
Definition: miner.h:61
BlockAssembler(Chainstate &chainstate, const CTxMemPool *mempool, BlockCreateOptions create_options)
Definition: miner.cpp:100
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
std::optional< uint256 > TipBlock() EXCLUSIVE_LOCKS_REQUIRED(m_tip_block_mutex)
The block for which the last blockTip notification was received.
std::string ToString() const
256-bit opaque blob.
Definition: uint256.h:196
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:66
static constexpr int NO_WITNESS_COMMITMENT
Index marker for when no witness commitment is present in a coinbase transaction.
Definition: validation.h:15
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 int64_t MAX_BLOCK_SIGOPS_COST
The maximum allowed number of signature check operations in a block (network rule)
Definition: consensus.h:17
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
#define LogInfo(...)
Definition: log.h:125
#define LogDebug(category,...)
Definition: log.h:143
unsigned int nHeight
BlockValidationState m_state
Definition: miner.cpp:371
uint256 m_hash
Definition: miner.cpp:369
bool m_found
Definition: miner.cpp:370
unsigned int nonce
is used externally by mining IPC clients, so it should only declare simple data definitions.
@ BENCH
Definition: categories.h:20
Definition: messages.h:21
void RegenerateCommitments(CBlock &block, ChainstateManager &chainman)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed.
Definition: miner.cpp:88
std::optional< BlockRef > WaitTipChanged(ChainstateManager &chainman, KernelNotifications &kernel_notifications, const uint256 &current_tip, MillisecondsDouble &timeout, bool &interrupt)
Definition: miner.cpp:559
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:70
bool SubmitBlock(ChainstateManager &chainman, const std::shared_ptr< const CBlock > &block, bool *new_block, std::string &reason, std::string &debug)
Submit a block and capture the validation state via the BlockChecked callback.
Definition: miner.cpp:388
BlockCreateOptions FlattenMiningOptions(BlockCreateOptions options)
Replace null optional values with their hardcoded defaults.
Definition: mining_args.cpp:81
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:57
void InterruptWait(KernelNotifications &kernel_notifications, bool &interrupt_wait)
Definition: miner.cpp:421
std::unique_ptr< CBlockTemplate > WaitAndCreateNewBlock(ChainstateManager &chainman, KernelNotifications &kernel_notifications, CTxMemPool *mempool, const std::unique_ptr< CBlockTemplate > &block_template, const BlockWaitOptions &wait_options, const BlockCreateOptions &create_options, bool &interrupt_wait)
Return a new block template when fees rise to a certain threshold or after a new tip; return nullopt ...
Definition: miner.cpp:428
void AddMerkleRootAndCoinbase(CBlock &block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce)
Definition: miner.cpp:347
Result< void > CheckMiningOptions(BlockCreateOptions options, bool use_argnames)
Check option values for validity.
Definition: mining_args.cpp:30
bool CooldownIfHeadersAhead(ChainstateManager &chainman, KernelNotifications &kernel_notifications, const BlockRef &last_tip, bool &interrupt_mining)
Wait while the best known header extends the current chain tip AND at least one block is being added ...
Definition: miner.cpp:525
std::optional< BlockRef > GetTip(ChainstateManager &chainman)
Definition: miner.cpp:517
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:93
static FeePerVSize ToFeePerVSize(FeePerWeight feerate)
Definition: policy.h:197
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:404
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:403
@ OP_0
Definition: script.h:77
A mutable version of CTransaction.
Definition: transaction.h:358
std::vector< CTxOut > vout
Definition: transaction.h:360
std::vector< CTxIn > vin
Definition: transaction.h:359
Parameters that influence chain consensus.
Definition: params.h:87
int64_t DifficultyAdjustmentInterval() const
Definition: params.h:129
bool fPowAllowMinDifficultyBlocks
Definition: params.h:116
int32_t size
Definition: feefrac.h:90
Tagged wrapper around FeeFrac to avoid unit confusion.
Definition: feefrac.h:192
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition: time.cpp:65
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition: time.cpp:38
std::chrono::time_point< NodeClock > time_point
Definition: time.h:28
Hash/height pair to help track and identify blocks.
Definition: types.h:13
uint256 hash
Definition: types.h:14
Block template creation options.
Definition: mining_types.h:33
MillisecondsDouble timeout
How long to wait before returning nullptr instead of a new template.
Definition: mining_types.h:99
CAmount fee_threshold
The wait method will not return a new template unless it has fees at least fee_threshold sats higher ...
Definition: mining_types.h:112
Template containing all coinbase transaction fields that are set by our miner code.
Definition: mining_types.h:132
#define WAIT_LOCK(cs, name)
Definition: sync.h:274
#define LOCK(cs)
Definition: sync.h:268
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:299
#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
static constexpr unsigned MAX_CLUSTER_COUNT_LIMIT
Definition: txgraph.h:18
std::chrono::duration< double, std::chrono::milliseconds::period > MillisecondsDouble
Definition: time.h:103
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
BlockValidationState TestBlockValidity(Chainstate &chainstate, const CBlock &block, const bool check_pow, const bool check_merkle_root)
Verify a block, including transactions.
assert(!tx.IsCoinBase())