Coverage Report

Created: 2026-04-29 19:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/node/miner.cpp
Line
Count
Source
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 <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>
16
#include <consensus/validation.h>
17
#include <deploymentstatus.h>
18
#include <logging.h>
19
#include <node/context.h>
20
#include <node/kernel_notifications.h>
21
#include <policy/feerate.h>
22
#include <policy/policy.h>
23
#include <pow.h>
24
#include <primitives/transaction.h>
25
#include <util/moneystr.h>
26
#include <util/signalinterrupt.h>
27
#include <util/time.h>
28
#include <validation.h>
29
30
#include <algorithm>
31
#include <utility>
32
#include <numeric>
33
34
namespace node {
35
36
int64_t GetMinimumTime(const CBlockIndex* pindexPrev, const int64_t difficulty_adjustment_interval)
37
48.6k
{
38
48.6k
    int64_t min_time{pindexPrev->GetMedianTimePast() + 1};
39
    // Height of block to be mined.
40
48.6k
    const int height{pindexPrev->nHeight + 1};
41
    // Account for BIP94 timewarp rule on all networks. This makes future
42
    // activation safer.
43
48.6k
    if (height % difficulty_adjustment_interval == 0) {
44
214
        min_time = std::max<int64_t>(min_time, pindexPrev->GetBlockTime() - MAX_TIMEWARP);
45
214
    }
46
48.6k
    return min_time;
47
48.6k
}
48
49
int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
50
46.5k
{
51
46.5k
    int64_t nOldTime = pblock->nTime;
52
46.5k
    int64_t nNewTime{std::max<int64_t>(GetMinimumTime(pindexPrev, consensusParams.DifficultyAdjustmentInterval()),
53
46.5k
                                       TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()))};
54
55
46.5k
    if (nOldTime < nNewTime) {
56
34.5k
        pblock->nTime = nNewTime;
57
34.5k
    }
58
59
    // Updating time can change work required on testnet:
60
46.5k
    if (consensusParams.fPowAllowMinDifficultyBlocks) {
61
46.4k
        pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
62
46.4k
    }
63
64
46.5k
    return nNewTime - nOldTime;
65
46.5k
}
66
67
void RegenerateCommitments(CBlock& block, ChainstateManager& chainman)
68
7.37k
{
69
7.37k
    CMutableTransaction tx{*block.vtx.at(0)};
70
7.37k
    tx.vout.erase(tx.vout.begin() + GetWitnessCommitmentIndex(block));
71
7.37k
    block.vtx.at(0) = MakeTransactionRef(tx);
72
73
7.37k
    const CBlockIndex* prev_block = WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock));
74
7.37k
    chainman.GenerateCoinbaseCommitment(block, prev_block);
75
76
7.37k
    block.hashMerkleRoot = BlockMerkleRoot(block);
77
7.37k
}
78
79
static BlockAssembler::Options ClampOptions(BlockAssembler::Options options)
80
44.4k
{
81
    // Apply DEFAULT_BLOCK_RESERVED_WEIGHT when the caller left it unset.
82
44.4k
    options.block_reserved_weight = std::clamp<size_t>(options.block_reserved_weight.value_or(DEFAULT_BLOCK_RESERVED_WEIGHT), MINIMUM_BLOCK_RESERVED_WEIGHT, MAX_BLOCK_WEIGHT);
83
44.4k
    options.coinbase_output_max_additional_sigops = std::clamp<size_t>(options.coinbase_output_max_additional_sigops, 0, MAX_BLOCK_SIGOPS_COST);
84
    // Limit weight to between block_reserved_weight and MAX_BLOCK_WEIGHT for sanity:
85
    // block_reserved_weight can safely exceed -blockmaxweight, but the rest of the block template will be empty.
86
44.4k
    options.nBlockMaxWeight = std::clamp<size_t>(options.nBlockMaxWeight, *options.block_reserved_weight, MAX_BLOCK_WEIGHT);
87
44.4k
    return options;
88
44.4k
}
89
90
BlockAssembler::BlockAssembler(Chainstate& chainstate, const CTxMemPool* mempool, const Options& options)
91
44.4k
    : chainparams{chainstate.m_chainman.GetParams()},
92
44.4k
      m_mempool{options.use_mempool ? mempool : nullptr},
93
44.4k
      m_chainstate{chainstate},
94
44.4k
      m_options{ClampOptions(options)}
95
44.4k
{
96
44.4k
}
97
98
void ApplyArgsManOptions(const ArgsManager& args, BlockAssembler::Options& options)
99
36.5k
{
100
    // Block resource limits
101
36.5k
    options.nBlockMaxWeight = args.GetIntArg("-blockmaxweight", options.nBlockMaxWeight);
102
36.5k
    if (const auto blockmintxfee{args.GetArg("-blockmintxfee")}) {
103
36
        if (const auto parsed{ParseMoney(*blockmintxfee)}) options.blockMinFeeRate = CFeeRate{*parsed};
104
36
    }
105
36.5k
    options.print_modified_fee = args.GetBoolArg("-printpriority", options.print_modified_fee);
106
36.5k
    if (!options.block_reserved_weight) {
107
36.5k
        options.block_reserved_weight = args.GetIntArg("-blockreservedweight");
108
36.5k
    }
109
36.5k
}
110
111
void BlockAssembler::resetBlock()
112
44.4k
{
113
    // Reserve space for fixed-size block header, txs count, and coinbase tx.
114
44.4k
    nBlockWeight = *Assert(m_options.block_reserved_weight);
115
44.4k
    nBlockSigOpsCost = m_options.coinbase_output_max_additional_sigops;
116
117
    // These counters do not include coinbase tx
118
44.4k
    nBlockTx = 0;
119
44.4k
    nFees = 0;
120
44.4k
}
121
122
std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock()
123
44.4k
{
124
44.4k
    const auto time_start{SteadyClock::now()};
125
126
44.4k
    resetBlock();
127
128
44.4k
    pblocktemplate.reset(new CBlockTemplate());
129
44.4k
    CBlock* const pblock = &pblocktemplate->block; // pointer for convenience
130
131
    // Add dummy coinbase tx as first transaction. It is skipped by the
132
    // getblocktemplate RPC and mining interface consumers must not use it.
133
44.4k
    pblock->vtx.emplace_back();
134
135
44.4k
    LOCK(::cs_main);
136
44.4k
    CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip();
137
44.4k
    assert(pindexPrev != nullptr);
138
44.4k
    nHeight = pindexPrev->nHeight + 1;
139
140
44.4k
    pblock->nVersion = m_chainstate.m_chainman.m_versionbitscache.ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
141
    // -regtest only: allow overriding block.nVersion with
142
    // -blockversion=N to test forking scenarios
143
44.4k
    if (chainparams.MineBlocksOnDemand()) {
144
44.3k
        pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion);
145
44.3k
    }
146
147
44.4k
    pblock->nTime = TicksSinceEpoch<std::chrono::seconds>(NodeClock::now());
148
44.4k
    m_lock_time_cutoff = pindexPrev->GetMedianTimePast();
149
150
44.4k
    if (m_mempool) {
151
37.1k
        LOCK(m_mempool->cs);
152
37.1k
        m_mempool->StartBlockBuilding();
153
37.1k
        addChunks();
154
37.1k
        m_mempool->StopBlockBuilding();
155
37.1k
    }
156
157
44.4k
    const auto time_1{SteadyClock::now()};
158
159
44.4k
    m_last_block_num_txs = nBlockTx;
160
44.4k
    m_last_block_weight = nBlockWeight;
161
162
    // Create coinbase transaction.
163
44.4k
    CMutableTransaction coinbaseTx;
164
165
    // Construct coinbase transaction struct in parallel
166
44.4k
    CoinbaseTx& coinbase_tx{pblocktemplate->m_coinbase_tx};
167
44.4k
    coinbase_tx.version = coinbaseTx.version;
168
169
44.4k
    coinbaseTx.vin.resize(1);
170
44.4k
    coinbaseTx.vin[0].prevout.SetNull();
171
44.4k
    coinbaseTx.vin[0].nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; // Make sure timelock is enforced.
172
44.4k
    coinbase_tx.sequence = coinbaseTx.vin[0].nSequence;
173
174
    // Add an output that spends the full coinbase reward.
175
44.4k
    coinbaseTx.vout.resize(1);
176
44.4k
    coinbaseTx.vout[0].scriptPubKey = m_options.coinbase_output_script;
177
    // Block subsidy + fees
178
44.4k
    const CAmount block_reward{nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus())};
179
44.4k
    coinbaseTx.vout[0].nValue = block_reward;
180
44.4k
    coinbase_tx.block_reward_remaining = block_reward;
181
182
    // Start the coinbase scriptSig with the block height as required by BIP34.
183
    // Mining clients are expected to append extra data to this prefix, so
184
    // increasing its length would reduce the space they can use and may break
185
    // existing clients.
186
44.4k
    coinbaseTx.vin[0].scriptSig = CScript() << nHeight;
187
44.4k
    if (m_options.include_dummy_extranonce) {
188
        // For blocks at heights <= 16, the BIP34-encoded height alone is only
189
        // one byte. Consensus requires coinbase scriptSigs to be at least two
190
        // bytes long (bad-cb-length), so tests and regtest include a dummy
191
        // extraNonce (OP_0)
192
44.4k
        coinbaseTx.vin[0].scriptSig << OP_0;
193
44.4k
    }
194
44.4k
    coinbase_tx.script_sig_prefix = coinbaseTx.vin[0].scriptSig;
195
44.4k
    Assert(nHeight > 0);
196
44.4k
    coinbaseTx.nLockTime = static_cast<uint32_t>(nHeight - 1);
197
44.4k
    coinbase_tx.lock_time = coinbaseTx.nLockTime;
198
199
44.4k
    pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
200
44.4k
    m_chainstate.m_chainman.GenerateCoinbaseCommitment(*pblock, pindexPrev);
201
202
44.4k
    const CTransactionRef& final_coinbase{pblock->vtx[0]};
203
44.4k
    if (final_coinbase->HasWitness()) {
204
43.8k
        const auto& witness_stack{final_coinbase->vin[0].scriptWitness.stack};
205
        // Consensus requires the coinbase witness stack to have exactly one
206
        // element of 32 bytes.
207
43.8k
        Assert(witness_stack.size() == 1 && witness_stack[0].size() == 32);
208
43.8k
        coinbase_tx.witness = uint256(witness_stack[0]);
209
43.8k
    }
210
44.4k
    if (const int witness_index = GetWitnessCommitmentIndex(*pblock); witness_index != NO_WITNESS_COMMITMENT) {
211
44.4k
        Assert(witness_index >= 0 && static_cast<size_t>(witness_index) < final_coinbase->vout.size());
212
44.4k
        coinbase_tx.required_outputs.push_back(final_coinbase->vout[witness_index]);
213
44.4k
    }
214
215
44.4k
    LogInfo("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
216
217
    // Fill in header
218
44.4k
    pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
219
44.4k
    UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
220
44.4k
    pblock->nBits          = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
221
44.4k
    pblock->nNonce         = 0;
222
223
44.4k
    if (m_options.test_block_validity) {
224
        // if nHeight <= 16, and include_dummy_extranonce=false this will fail due to bad-cb-length.
225
44.4k
        if (BlockValidationState state{TestBlockValidity(m_chainstate, *pblock, /*check_pow=*/false, /*check_merkle_root=*/false)}; !state.IsValid()) {
226
5
            throw std::runtime_error(strprintf("TestBlockValidity failed: %s", state.ToString()));
227
5
        }
228
44.4k
    }
229
44.4k
    const auto time_2{SteadyClock::now()};
230
231
44.4k
    LogDebug(BCLog::BENCH, "CreateNewBlock() chunks: %.2fms, validity: %.2fms (total %.2fms)\n",
232
44.4k
             Ticks<MillisecondsDouble>(time_1 - time_start),
233
44.4k
             Ticks<MillisecondsDouble>(time_2 - time_1),
234
44.4k
             Ticks<MillisecondsDouble>(time_2 - time_start));
235
236
44.4k
    return std::move(pblocktemplate);
237
44.4k
}
238
239
bool BlockAssembler::TestChunkBlockLimits(FeePerWeight chunk_feerate, int64_t chunk_sigops_cost) const
240
50.9k
{
241
50.9k
    if (nBlockWeight + chunk_feerate.size >= m_options.nBlockMaxWeight) {
242
41.1k
        return false;
243
41.1k
    }
244
9.80k
    if (nBlockSigOpsCost + chunk_sigops_cost >= MAX_BLOCK_SIGOPS_COST) {
245
2
        return false;
246
2
    }
247
9.80k
    return true;
248
9.80k
}
249
250
// Perform transaction-level checks before adding to block:
251
// - transaction finality (locktime)
252
bool BlockAssembler::TestChunkTransactions(const std::vector<CTxMemPoolEntryRef>& txs) const
253
9.80k
{
254
10.6k
    for (const auto tx : txs) {
255
10.6k
        if (!IsFinalTx(tx.get().GetTx(), nHeight, m_lock_time_cutoff)) {
256
2
            return false;
257
2
        }
258
10.6k
    }
259
9.80k
    return true;
260
9.80k
}
261
262
void BlockAssembler::AddToBlock(const CTxMemPoolEntry& entry)
263
10.6k
{
264
10.6k
    pblocktemplate->block.vtx.emplace_back(entry.GetSharedTx());
265
10.6k
    pblocktemplate->vTxFees.push_back(entry.GetFee());
266
10.6k
    pblocktemplate->vTxSigOpsCost.push_back(entry.GetSigOpCost());
267
10.6k
    nBlockWeight += entry.GetTxWeight();
268
10.6k
    ++nBlockTx;
269
10.6k
    nBlockSigOpsCost += entry.GetSigOpCost();
270
10.6k
    nFees += entry.GetFee();
271
272
10.6k
    if (m_options.print_modified_fee) {
273
88
        LogInfo("fee rate %s txid %s\n",
274
88
                  CFeeRate(entry.GetModifiedFee(), entry.GetTxSize()).ToString(),
275
88
                  entry.GetTx().GetHash().ToString());
276
88
    }
277
10.6k
}
278
279
void BlockAssembler::addChunks()
280
37.1k
{
281
    // Limit the number of attempts to add transactions to the block when it is
282
    // close to full; this is just a simple heuristic to finish quickly if the
283
    // mempool has a lot of entries.
284
37.1k
    const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
285
37.1k
    constexpr int32_t BLOCK_FULL_ENOUGH_WEIGHT_DELTA = 4000;
286
37.1k
    int64_t nConsecutiveFailed = 0;
287
288
37.1k
    std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> selected_transactions;
289
37.1k
    selected_transactions.reserve(MAX_CLUSTER_COUNT_LIMIT);
290
37.1k
    FeePerWeight chunk_feerate;
291
292
    // This fills selected_transactions
293
37.1k
    chunk_feerate = m_mempool->GetBlockBuilderChunk(selected_transactions);
294
37.1k
    FeePerVSize chunk_feerate_vsize = ToFeePerVSize(chunk_feerate);
295
296
88.0k
    while (selected_transactions.size() > 0) {
297
        // Check to see if min fee rate is still respected.
298
51.0k
        if (chunk_feerate_vsize << m_options.blockMinFeeRate.GetFeePerVSize()) {
299
            // Everything else we might consider has a lower feerate
300
46
            return;
301
46
        }
302
303
50.9k
        int64_t chunk_sig_ops = 0;
304
53.9k
        for (const auto& tx : selected_transactions) {
305
53.9k
            chunk_sig_ops += tx.get().GetSigOpCost();
306
53.9k
        }
307
308
        // Check to see if this chunk will fit.
309
50.9k
        if (!TestChunkBlockLimits(chunk_feerate, chunk_sig_ops) || !TestChunkTransactions(selected_transactions)) {
310
            // This chunk won't fit, so we skip it and will try the next best one.
311
41.1k
            m_mempool->SkipBuilderChunk();
312
41.1k
            ++nConsecutiveFailed;
313
314
41.1k
            if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight +
315
17
                    BLOCK_FULL_ENOUGH_WEIGHT_DELTA > m_options.nBlockMaxWeight) {
316
                // Give up if we're close to full and haven't succeeded in a while
317
17
                return;
318
17
            }
319
41.1k
        } else {
320
9.80k
            m_mempool->IncludeBuilderChunk();
321
322
            // This chunk will fit, so add it to the block.
323
9.80k
            nConsecutiveFailed = 0;
324
10.6k
            for (const auto& tx : selected_transactions) {
325
10.6k
                AddToBlock(tx);
326
10.6k
            }
327
9.80k
            pblocktemplate->m_package_feerates.emplace_back(chunk_feerate_vsize);
328
9.80k
        }
329
330
50.9k
        selected_transactions.clear();
331
50.9k
        chunk_feerate = m_mempool->GetBlockBuilderChunk(selected_transactions);
332
50.9k
        chunk_feerate_vsize = ToFeePerVSize(chunk_feerate);
333
50.9k
    }
334
37.1k
}
335
336
void AddMerkleRootAndCoinbase(CBlock& block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce)
337
55
{
338
55
    if (block.vtx.size() == 0) {
339
0
        block.vtx.emplace_back(coinbase);
340
55
    } else {
341
55
        block.vtx[0] = coinbase;
342
55
    }
343
55
    block.nVersion = version;
344
55
    block.nTime = timestamp;
345
55
    block.nNonce = nonce;
346
55
    block.hashMerkleRoot = BlockMerkleRoot(block);
347
348
    // Reset cached checks
349
55
    block.m_checked_witness_commitment = false;
350
55
    block.m_checked_merkle_root = false;
351
55
    block.fChecked = false;
352
55
}
353
354
void InterruptWait(KernelNotifications& kernel_notifications, bool& interrupt_wait)
355
0
{
356
0
    LOCK(kernel_notifications.m_tip_block_mutex);
357
0
    interrupt_wait = true;
358
0
    kernel_notifications.m_tip_block_cv.notify_all();
359
0
}
360
361
std::unique_ptr<CBlockTemplate> WaitAndCreateNewBlock(ChainstateManager& chainman,
362
                                                      KernelNotifications& kernel_notifications,
363
                                                      CTxMemPool* mempool,
364
                                                      const std::unique_ptr<CBlockTemplate>& block_template,
365
                                                      const BlockWaitOptions& options,
366
                                                      const BlockAssembler::Options& assemble_options,
367
                                                      bool& interrupt_wait)
368
62
{
369
    // Delay calculating the current template fees, just in case a new block
370
    // comes in before the next tick.
371
62
    CAmount current_fees = -1;
372
373
    // Alternate waiting for a new tip and checking if fees have risen.
374
    // The latter check is expensive so we only run it once per second.
375
62
    auto now{NodeClock::now()};
376
62
    const auto deadline = now + options.timeout;
377
62
    const MillisecondsDouble tick{1000};
378
62
    const bool allow_min_difficulty{chainman.GetParams().GetConsensus().fPowAllowMinDifficultyBlocks};
379
380
62
    do {
381
62
        bool tip_changed{false};
382
62
        {
383
62
            WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
384
            // Note that wait_until() checks the predicate before waiting
385
69
            kernel_notifications.m_tip_block_cv.wait_until(lock, std::min(now + tick, deadline), [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
386
69
                AssertLockHeld(kernel_notifications.m_tip_block_mutex);
387
69
                const auto tip_block{kernel_notifications.TipBlock()};
388
                // We assume tip_block is set, because this is an instance
389
                // method on BlockTemplate and no template could have been
390
                // generated before a tip exists.
391
69
                tip_changed = Assume(tip_block) && tip_block != block_template->block.hashPrevBlock;
392
69
                return tip_changed || chainman.m_interrupt || interrupt_wait;
393
69
            });
394
62
            if (interrupt_wait) {
395
0
                interrupt_wait = false;
396
0
                return nullptr;
397
0
            }
398
62
        }
399
400
62
        if (chainman.m_interrupt) return nullptr;
401
        // At this point the tip changed, a full tick went by or we reached
402
        // the deadline.
403
404
        // Must release m_tip_block_mutex before locking cs_main, to avoid deadlocks.
405
62
        LOCK(::cs_main);
406
407
        // On test networks return a minimum difficulty block after 20 minutes
408
62
        if (!tip_changed && allow_min_difficulty) {
409
3
            const NodeClock::time_point tip_time{std::chrono::seconds{chainman.ActiveChain().Tip()->GetBlockTime()}};
410
3
            if (now > tip_time + 20min) {
411
1
                tip_changed = true;
412
1
            }
413
3
        }
414
415
        /**
416
         * We determine if fees increased compared to the previous template by generating
417
         * a fresh template. There may be more efficient ways to determine how much
418
         * (approximate) fees for the next block increased, perhaps more so after
419
         * Cluster Mempool.
420
         *
421
         * We'll also create a new template if the tip changed during this iteration.
422
         */
423
62
        if (options.fee_threshold < MAX_MONEY || tip_changed) {
424
62
            auto new_tmpl{BlockAssembler{
425
62
                chainman.ActiveChainstate(),
426
62
                mempool,
427
62
                assemble_options}
428
62
                              .CreateNewBlock()};
429
430
            // If the tip changed, return the new template regardless of its fees.
431
62
            if (tip_changed) return new_tmpl;
432
433
            // Calculate the original template total fees if we haven't already
434
6
            if (current_fees == -1) {
435
6
                current_fees = std::accumulate(block_template->vTxFees.begin(), block_template->vTxFees.end(), CAmount{0});
436
6
            }
437
438
            // Check if fees increased enough to return the new template
439
6
            const CAmount new_fees = std::accumulate(new_tmpl->vTxFees.begin(), new_tmpl->vTxFees.end(), CAmount{0});
440
6
            Assume(options.fee_threshold != MAX_MONEY);
441
6
            if (new_fees >= current_fees + options.fee_threshold) return new_tmpl;
442
6
        }
443
444
4
        now = NodeClock::now();
445
4
    } while (now < deadline);
446
447
4
    return nullptr;
448
62
}
449
450
std::optional<BlockRef> GetTip(ChainstateManager& chainman)
451
38.8k
{
452
38.8k
    LOCK(::cs_main);
453
38.8k
    CBlockIndex* tip{chainman.ActiveChain().Tip()};
454
38.8k
    if (!tip) return {};
455
38.8k
    return BlockRef{tip->GetBlockHash(), tip->nHeight};
456
38.8k
}
457
458
bool CooldownIfHeadersAhead(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const BlockRef& last_tip, bool& interrupt_mining)
459
0
{
460
0
    uint256 last_tip_hash{last_tip.hash};
461
462
0
    while (const std::optional<int> remaining = chainman.BlocksAheadOfTip()) {
463
0
        const int cooldown_seconds = std::clamp(*remaining, 3, 20);
464
0
        const auto cooldown_deadline{MockableSteadyClock::now() + std::chrono::seconds{cooldown_seconds}};
465
466
0
        {
467
0
            WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
468
0
            kernel_notifications.m_tip_block_cv.wait_until(lock, cooldown_deadline, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
469
0
                const auto tip_block = kernel_notifications.TipBlock();
470
0
                return chainman.m_interrupt || interrupt_mining || (tip_block && *tip_block != last_tip_hash);
471
0
            });
472
0
            if (chainman.m_interrupt || interrupt_mining) {
473
0
                interrupt_mining = false;
474
0
                return false;
475
0
            }
476
477
            // If the tip changed during the wait, extend the deadline
478
0
            const auto tip_block = kernel_notifications.TipBlock();
479
0
            if (tip_block && *tip_block != last_tip_hash) {
480
0
                last_tip_hash = *tip_block;
481
0
                continue;
482
0
            }
483
0
        }
484
485
        // No tip change and the cooldown window has expired.
486
0
        if (MockableSteadyClock::now() >= cooldown_deadline) break;
487
0
    }
488
489
0
    return true;
490
0
}
491
492
std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const uint256& current_tip, MillisecondsDouble& timeout, bool& interrupt)
493
36.6k
{
494
36.6k
    Assume(timeout >= 0ms); // No internal callers should use a negative timeout
495
36.6k
    if (timeout < 0ms) timeout = 0ms;
496
36.6k
    if (timeout > std::chrono::years{100}) timeout = std::chrono::years{100}; // Upper bound to avoid UB in std::chrono
497
36.6k
    auto deadline{std::chrono::steady_clock::now() + timeout};
498
36.6k
    {
499
36.6k
        WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
500
        // For callers convenience, wait longer than the provided timeout
501
        // during startup for the tip to be non-null. That way this function
502
        // always returns valid tip information when possible and only
503
        // returns null when shutting down, not when timing out.
504
36.6k
        kernel_notifications.m_tip_block_cv.wait(lock, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
505
36.6k
            return kernel_notifications.TipBlock() || chainman.m_interrupt || interrupt;
506
36.6k
        });
507
36.6k
        if (chainman.m_interrupt || interrupt) {
508
0
            interrupt = false;
509
0
            return {};
510
0
        }
511
        // At this point TipBlock is set, so continue to wait until it is
512
        // different then `current_tip` provided by caller.
513
36.6k
        kernel_notifications.m_tip_block_cv.wait_until(lock, deadline, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
514
36.6k
            return Assume(kernel_notifications.TipBlock()) != current_tip || chainman.m_interrupt || interrupt;
515
36.6k
        });
516
36.6k
        if (chainman.m_interrupt || interrupt) {
517
2
            interrupt = false;
518
2
            return {};
519
2
        }
520
36.6k
    }
521
522
    // Must release m_tip_block_mutex before getTip() locks cs_main, to
523
    // avoid deadlocks.
524
36.6k
    return GetTip(chainman);
525
36.6k
}
526
527
} // namespace node