Coverage Report

Created: 2026-09-14 20:36

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 <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>
16
#include <consensus/validation.h>
17
#include <interfaces/types.h>
18
#include <node/blockstorage.h>
19
#include <node/kernel_notifications.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>
26
#include <primitives/transaction.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>
37
#include <util/signalinterrupt.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
55
namespace node {
56
57
int64_t GetMinimumTime(const CBlockIndex* pindexPrev, const int64_t difficulty_adjustment_interval)
58
43.9k
{
59
43.9k
    int64_t min_time{pindexPrev->GetMedianTimePast() + 1};
60
    // Height of block to be mined.
61
43.9k
    const int height{pindexPrev->nHeight + 1};
62
    // Account for BIP94 timewarp rule on all networks. This makes future
63
    // activation safer.
64
43.9k
    if (height % difficulty_adjustment_interval == 0) {
65
199
        min_time = std::max<int64_t>(min_time, pindexPrev->GetBlockTime() - MAX_TIMEWARP);
66
199
    }
67
    // Account for the BIP54 Murch-Zawy rule on all networks: the last block of
68
    // a difficulty adjustment period may not be earlier than its first block.
69
43.9k
    if (height % difficulty_adjustment_interval == difficulty_adjustment_interval - 1) {
70
198
        const int first_height{height - static_cast<int>(difficulty_adjustment_interval) + 1};
71
198
        const CBlockIndex* first_block{Assert(pindexPrev->GetAncestor(first_height))};
72
198
        min_time = std::max<int64_t>(min_time, first_block->GetBlockTime());
73
198
    }
74
43.9k
    return min_time;
75
43.9k
}
76
77
int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
78
43.8k
{
79
43.8k
    int64_t nOldTime = pblock->nTime;
80
43.8k
    int64_t nNewTime{std::max<int64_t>(GetMinimumTime(pindexPrev, consensusParams.DifficultyAdjustmentInterval()),
81
43.8k
                                       TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()))};
82
83
43.8k
    if (nOldTime < nNewTime) {
84
32.2k
        pblock->nTime = nNewTime;
85
32.2k
    }
86
87
    // Updating time can change work required on testnet:
88
43.8k
    if (consensusParams.fPowAllowMinDifficultyBlocks) {
89
43.6k
        pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
90
43.6k
    }
91
92
43.8k
    return nNewTime - nOldTime;
93
43.8k
}
94
95
void RegenerateCommitments(CBlock& block, ChainstateManager& chainman)
96
8.70k
{
97
8.70k
    CMutableTransaction tx{*block.vtx.at(0)};
98
8.70k
    tx.vout.erase(tx.vout.begin() + GetWitnessCommitmentIndex(block));
99
8.70k
    block.vtx.at(0) = MakeTransactionRef(tx);
100
101
8.70k
    const CBlockIndex* prev_block = WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock));
102
8.70k
    chainman.GenerateCoinbaseCommitment(block, prev_block);
103
104
8.70k
    block.hashMerkleRoot = BlockMerkleRoot(block);
105
8.70k
}
106
107
BlockAssembler::BlockAssembler(Chainstate& chainstate,
108
                               const CTxMemPool* mempool,
109
                               BlockCreateOptions options)
110
43.7k
    : chainparams{chainstate.m_chainman.GetParams()},
111
43.7k
      m_mempool{options.use_mempool ? mempool : nullptr},
112
43.7k
      m_chainstate{chainstate},
113
43.7k
      m_options{[&] {
114
43.7k
          if (auto result{CheckMiningOptions(options, /*use_argnames=*/false)}; !result) {
115
4
              throw std::runtime_error(util::ErrorString(result).original);
116
4
          }
117
43.7k
          return FlattenMiningOptions(std::move(options));
118
43.7k
      }()}
119
43.7k
{
120
43.7k
}
121
122
void BlockAssembler::resetBlock()
123
43.7k
{
124
    // Reserve space for fixed-size block header, txs count, and coinbase tx.
125
43.7k
    nBlockWeight = *Assert(m_options.block_reserved_weight);
126
43.7k
    nBlockSigOpsCost = m_options.coinbase_output_max_additional_sigops;
127
128
    // These counters do not include coinbase tx
129
43.7k
    nBlockTx = 0;
130
43.7k
    nFees = 0;
131
43.7k
}
132
133
std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock()
134
43.7k
{
135
43.7k
    const auto time_start{SteadyClock::now()};
136
137
43.7k
    resetBlock();
138
139
43.7k
    pblocktemplate.reset(new CBlockTemplate());
140
43.7k
    CBlock* const pblock = &pblocktemplate->block; // pointer for convenience
141
142
    // Add dummy coinbase tx as first transaction. It is skipped by the
143
    // getblocktemplate RPC and mining interface consumers must not use it.
144
43.7k
    pblock->vtx.emplace_back();
145
146
43.7k
    LOCK(::cs_main);
147
43.7k
    CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip();
148
43.7k
    assert(pindexPrev != nullptr);
149
43.7k
    nHeight = pindexPrev->nHeight + 1;
150
151
43.7k
    pblock->nVersion = m_chainstate.m_chainman.m_versionbitscache.ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
152
    // -regtest only: allow overriding block.nVersion with
153
    // -blockversion=N to test forking scenarios
154
43.7k
    if (chainparams.MineBlocksOnDemand()) {
155
43.5k
        pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion);
156
43.5k
    }
157
158
43.7k
    pblock->nTime = TicksSinceEpoch<std::chrono::seconds>(NodeClock::now());
159
43.7k
    m_lock_time_cutoff = pindexPrev->GetMedianTimePast();
160
161
43.7k
    if (m_mempool) {
162
34.9k
        LOCK(m_mempool->cs);
163
34.9k
        m_mempool->StartBlockBuilding();
164
34.9k
        addChunks();
165
34.9k
        m_mempool->StopBlockBuilding();
166
34.9k
    }
167
168
43.7k
    const auto time_1{SteadyClock::now()};
169
170
43.7k
    m_last_block_num_txs = nBlockTx;
171
43.7k
    m_last_block_weight = nBlockWeight;
172
173
    // Create coinbase transaction.
174
43.7k
    CMutableTransaction coinbaseTx;
175
176
    // Construct coinbase transaction struct in parallel
177
43.7k
    CoinbaseTx& coinbase_tx{pblocktemplate->m_coinbase_tx};
178
43.7k
    coinbase_tx.version = coinbaseTx.version;
179
180
43.7k
    coinbaseTx.vin.resize(1);
181
43.7k
    coinbaseTx.vin[0].prevout.SetNull();
182
43.7k
    coinbaseTx.vin[0].nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; // Make sure timelock is enforced.
183
43.7k
    coinbase_tx.sequence = coinbaseTx.vin[0].nSequence;
184
185
    // Add an output that spends the full coinbase reward.
186
43.7k
    coinbaseTx.vout.resize(1);
187
43.7k
    coinbaseTx.vout[0].scriptPubKey = m_options.coinbase_output_script;
188
    // Block subsidy + fees
189
43.7k
    const CAmount block_reward{nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus())};
190
43.7k
    coinbaseTx.vout[0].nValue = block_reward;
191
43.7k
    coinbase_tx.block_reward_remaining = block_reward;
192
193
    // Start the coinbase scriptSig with the block height as required by BIP34.
194
    // Mining clients are expected to append extra data to this prefix, so
195
    // increasing its length would reduce the space they can use and may break
196
    // existing clients.
197
43.7k
    coinbaseTx.vin[0].scriptSig = CScript() << nHeight;
198
    // Set script_sig_prefix here, so IPC mining clients are not affected by
199
    // the optional scriptSig padding below. They provide their own extraNonce,
200
    // and in a typical setup a pool name or realistic extraNonce already makes
201
    // the scriptSig long enough.
202
43.7k
    coinbase_tx.script_sig_prefix = coinbaseTx.vin[0].scriptSig;
203
43.7k
    if (nHeight <= 16) {
204
        // For blocks at heights <= 16, the BIP34-encoded height alone is only
205
        // one byte. Consensus requires coinbase scriptSigs to be at least two
206
        // bytes long (bad-cb-length), so an OP_0 is always appended at those
207
        // heights.
208
2.79k
        coinbaseTx.vin[0].scriptSig << OP_0;
209
2.79k
    }
210
43.7k
    Assert(nHeight > 0);
211
43.7k
    coinbaseTx.nLockTime = static_cast<uint32_t>(nHeight - 1);
212
43.7k
    coinbase_tx.lock_time = coinbaseTx.nLockTime;
213
214
43.7k
    pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
215
43.7k
    m_chainstate.m_chainman.GenerateCoinbaseCommitment(*pblock, pindexPrev);
216
217
43.7k
    const CTransactionRef& final_coinbase{pblock->vtx[0]};
218
43.7k
    if (final_coinbase->HasWitness()) {
219
43.0k
        const auto& witness_stack{final_coinbase->vin[0].scriptWitness.stack};
220
        // Consensus requires the coinbase witness stack to have exactly one
221
        // element of 32 bytes.
222
43.0k
        Assert(witness_stack.size() == 1 && witness_stack[0].size() == 32);
223
43.0k
        coinbase_tx.witness = uint256(witness_stack[0]);
224
43.0k
    }
225
43.7k
    if (const int witness_index = GetWitnessCommitmentIndex(*pblock); witness_index != NO_WITNESS_COMMITMENT) {
226
43.7k
        Assert(witness_index >= 0 && static_cast<size_t>(witness_index) < final_coinbase->vout.size());
227
43.7k
        coinbase_tx.required_outputs.push_back(final_coinbase->vout[witness_index]);
228
43.7k
    }
229
230
43.7k
    LogInfo("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
231
232
    // Fill in header
233
43.7k
    pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
234
43.7k
    UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
235
43.7k
    pblock->nBits          = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
236
43.7k
    pblock->nNonce         = 0;
237
238
43.7k
    if (m_options.test_block_validity) {
239
43.2k
        if (BlockValidationState state{TestBlockValidity(m_chainstate, *pblock, /*check_pow=*/false, /*check_merkle_root=*/false)}; !state.IsValid()) {
240
5
            throw std::runtime_error(strprintf("TestBlockValidity failed: %s", state.ToString()));
241
5
        }
242
43.2k
    }
243
43.6k
    const auto time_2{SteadyClock::now()};
244
245
43.6k
    LogDebug(BCLog::BENCH, "CreateNewBlock() chunks: %.2fms, validity: %.2fms (total %.2fms)\n",
246
43.6k
             Ticks<MillisecondsDouble>(time_1 - time_start),
247
43.6k
             Ticks<MillisecondsDouble>(time_2 - time_1),
248
43.6k
             Ticks<MillisecondsDouble>(time_2 - time_start));
249
250
43.6k
    return std::move(pblocktemplate);
251
43.7k
}
252
253
bool BlockAssembler::TestChunkBlockLimits(int64_t chunk_weight, int64_t chunk_sigops_cost) const
254
86.3k
{
255
    // block_max_weight has been flattened before block assembly limit checks.
256
86.3k
    Assert(m_options.block_max_weight);
257
86.3k
    if (nBlockWeight + chunk_weight >= m_options.block_max_weight) {
258
35.3k
        return false;
259
35.3k
    }
260
50.9k
    if (nBlockSigOpsCost + chunk_sigops_cost >= MAX_BLOCK_SIGOPS_COST) {
261
2
        return false;
262
2
    }
263
50.9k
    return true;
264
50.9k
}
265
266
// Perform transaction-level checks before adding to block:
267
// - transaction finality (locktime)
268
bool BlockAssembler::TestChunkTransactions(const std::vector<CTxMemPoolEntryRef>& txs) const
269
50.9k
{
270
52.3k
    for (const auto tx : txs) {
271
52.3k
        if (!IsFinalTx(tx.get().GetTx(), nHeight, m_lock_time_cutoff)) {
272
2
            return false;
273
2
        }
274
52.3k
    }
275
50.9k
    return true;
276
50.9k
}
277
278
void BlockAssembler::AddToBlock(const CTxMemPoolEntry& entry)
279
52.3k
{
280
52.3k
    pblocktemplate->block.vtx.emplace_back(entry.GetSharedTx());
281
52.3k
    pblocktemplate->vTxFees.push_back(entry.GetFee());
282
52.3k
    pblocktemplate->vTxSigOpsCost.push_back(entry.GetSigOpCost());
283
52.3k
    nBlockWeight += entry.GetTxWeight();
284
52.3k
    ++nBlockTx;
285
52.3k
    nBlockSigOpsCost += entry.GetSigOpCost();
286
52.3k
    nFees += entry.GetFee();
287
288
52.3k
    if (*m_options.print_modified_fee) {
289
88
        LogInfo("fee rate %s txid %s\n",
290
88
                  CFeeRate(entry.GetModifiedFee(), entry.GetTxSize()).ToString(),
291
88
                  entry.GetTx().GetHash().ToString());
292
88
    }
293
52.3k
}
294
295
void BlockAssembler::addChunks()
296
34.9k
{
297
    // Limit the number of attempts to add transactions to the block when it is
298
    // close to full; this is just a simple heuristic to finish quickly if the
299
    // mempool has a lot of entries.
300
34.9k
    const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
301
34.9k
    constexpr int32_t BLOCK_FULL_ENOUGH_WEIGHT_DELTA = 4000;
302
34.9k
    int64_t nConsecutiveFailed = 0;
303
304
34.9k
    std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> selected_transactions;
305
34.9k
    selected_transactions.reserve(MAX_CLUSTER_COUNT_LIMIT);
306
34.9k
    FeePerWeight chunk_feerate;
307
308
    // This fills selected_transactions
309
34.9k
    chunk_feerate = m_mempool->GetBlockBuilderChunk(selected_transactions);
310
34.9k
    FeePerVSize chunk_feerate_vsize = ToFeePerVSize(chunk_feerate);
311
312
121k
    while (selected_transactions.size() > 0) {
313
        // Check to see if min fee rate is still respected.
314
86.3k
        if (ByRatio{chunk_feerate_vsize} < ByRatio{m_options.block_min_fee_rate->GetFeePerVSize()}) {
315
            // Everything else we might consider has a lower feerate
316
48
            return;
317
48
        }
318
319
86.3k
        int64_t chunk_sig_ops = 0;
320
86.3k
        int64_t chunk_weight = 0;
321
89.7k
        for (const auto& tx : selected_transactions) {
322
89.7k
            chunk_sig_ops += tx.get().GetSigOpCost();
323
89.7k
            chunk_weight += tx.get().GetTxWeight();
324
89.7k
        }
325
326
        // Check to see if this chunk will fit.
327
86.3k
        if (!TestChunkBlockLimits(chunk_weight, chunk_sig_ops) || !TestChunkTransactions(selected_transactions)) {
328
            // This chunk won't fit, so we skip it and will try the next best one.
329
35.3k
            m_mempool->SkipBuilderChunk();
330
35.3k
            ++nConsecutiveFailed;
331
332
            // block_max_weight has been flattened before block assembly limit checks.
333
35.3k
            Assert(m_options.block_max_weight);
334
35.3k
            if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight +
335
14
                    BLOCK_FULL_ENOUGH_WEIGHT_DELTA > *m_options.block_max_weight) {
336
                // Give up if we're close to full and haven't succeeded in a while
337
14
                return;
338
14
            }
339
50.9k
        } else {
340
50.9k
            m_mempool->IncludeBuilderChunk();
341
342
            // This chunk will fit, so add it to the block.
343
50.9k
            nConsecutiveFailed = 0;
344
52.3k
            for (const auto& tx : selected_transactions) {
345
52.3k
                AddToBlock(tx);
346
52.3k
            }
347
50.9k
            pblocktemplate->m_package_feerates.emplace_back(chunk_feerate_vsize);
348
50.9k
        }
349
350
86.3k
        selected_transactions.clear();
351
86.3k
        chunk_feerate = m_mempool->GetBlockBuilderChunk(selected_transactions);
352
86.3k
        chunk_feerate_vsize = ToFeePerVSize(chunk_feerate);
353
86.3k
    }
354
34.9k
}
355
356
void AddMerkleRootAndCoinbase(CBlock& block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce)
357
77
{
358
77
    if (block.vtx.size() == 0) {
359
0
        block.vtx.emplace_back(coinbase);
360
77
    } else {
361
77
        block.vtx[0] = coinbase;
362
77
    }
363
77
    block.nVersion = version;
364
77
    block.nTime = timestamp;
365
77
    block.nNonce = nonce;
366
77
    block.hashMerkleRoot = BlockMerkleRoot(block);
367
368
    // Reset cached checks
369
77
    block.m_checked_witness_commitment = false;
370
77
    block.m_checked_merkle_root = false;
371
77
    block.fChecked = false;
372
77
}
373
374
namespace {
375
class SubmitBlockStateCatcher final : public CValidationInterface
376
{
377
public:
378
    uint256 m_hash;
379
    bool m_found{false};
380
    BlockValidationState m_state;
381
382
197
    explicit SubmitBlockStateCatcher(const uint256& hash) : m_hash{hash} {}
383
384
protected:
385
    void BlockChecked(const std::shared_ptr<const CBlock>& block, const BlockValidationState& state) override
386
137
    {
387
137
        if (block->GetHash() != m_hash) return;
388
        // ProcessNewBlock emits BlockChecked synchronously while holding cs_main,
389
        // so SubmitBlock can read these fields after ProcessNewBlock returns
390
        // without extra synchronization.
391
137
        m_found = true;
392
137
        m_state = state;
393
137
    }
394
};
395
} // namespace
396
397
bool SubmitBlock(ChainstateManager& chainman, const std::shared_ptr<const CBlock>& block, std::string& reason, std::string& debug)
398
197
{
399
197
    reason.clear();
400
197
    debug.clear();
401
402
    // This follows the submitblock RPC's validation-state capture pattern, but
403
    // is intentionally kept separate from the RPC implementation. The RPC entry
404
    // point decodes hex, formats BIP22/JSONRPC results, and calls
405
    // UpdateUncommittedBlockStructures() for legacy witness handling. IPC
406
    // callers submit already-formed blocks and need bool + reason/debug
407
    // results.
408
197
    auto sc = std::make_shared<SubmitBlockStateCatcher>(block->GetHash());
409
197
    CHECK_NONFATAL(chainman.m_options.signals)->RegisterSharedValidationInterface(sc);
410
197
    bool new_block;
411
197
    bool accepted = chainman.ProcessNewBlock(block, /*force_processing=*/true, /*min_pow_checked=*/true, /*new_block=*/&new_block);
412
    // No queue drain is needed. The BlockChecked notification used above is
413
    // emitted synchronously by ProcessNewBlock, unlike most validation signals.
414
197
    CHECK_NONFATAL(chainman.m_options.signals)->UnregisterSharedValidationInterface(sc);
415
416
197
    if (!new_block && accepted) {
417
58
        reason = "duplicate";
418
139
    } else if (!accepted && (!sc->m_found || sc->m_state.IsValid())) {
419
        // ProcessNewBlock can fail without a validation result, for example
420
        // from an activation or system error. It can also fail after a valid
421
        // BlockChecked result. In these cases the validation result is
422
        // inconclusive.
423
0
        reason = "inconclusive";
424
139
    } else if (!sc->m_found) {
425
        // The block was accepted but not connected, for example if it does not
426
        // have more work than the current tip.
427
2
        reason = "inconclusive";
428
137
    } else if (!sc->m_state.IsValid()) {
429
6
        reason = sc->m_state.GetRejectReason();
430
6
        debug = sc->m_state.GetDebugMessage();
431
6
    }
432
197
    const bool result{accepted && new_block && reason.empty()};
433
197
    CHECK_NONFATAL(result == reason.empty());
434
197
    return result;
435
197
}
436
437
void InterruptWait(KernelNotifications& kernel_notifications, bool& interrupt_wait)
438
3
{
439
3
    LOCK(kernel_notifications.m_tip_block_mutex);
440
3
    interrupt_wait = true;
441
3
    kernel_notifications.m_tip_block_cv.notify_all();
442
3
}
443
444
std::unique_ptr<CBlockTemplate> WaitAndCreateNewBlock(ChainstateManager& chainman,
445
                                                      KernelNotifications& kernel_notifications,
446
                                                      CTxMemPool* mempool,
447
                                                      const std::unique_ptr<CBlockTemplate>& block_template,
448
                                                      const BlockWaitOptions& wait_options,
449
                                                      const BlockCreateOptions& create_options,
450
                                                      bool& interrupt_wait)
451
75
{
452
    // Delay calculating the current template fees, just in case a new block
453
    // comes in before the next tick.
454
75
    CAmount current_fees = -1;
455
456
    // Alternate waiting for a new tip and checking if fees have risen.
457
    // The latter check is expensive so we only run it once per second.
458
75
    auto now{NodeClock::now()};
459
75
    const auto deadline = now + wait_options.timeout;
460
75
    const MillisecondsDouble tick{1000};
461
75
    const bool allow_min_difficulty{chainman.GetParams().GetConsensus().fPowAllowMinDifficultyBlocks};
462
463
93
    do {
464
93
        bool tip_changed{false};
465
93
        {
466
93
            WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
467
            // Note that wait_until() checks the predicate before waiting
468
128
            kernel_notifications.m_tip_block_cv.wait_until(lock, std::min(now + tick, deadline), [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
469
128
                AssertLockHeld(kernel_notifications.m_tip_block_mutex);
470
128
                const auto tip_block{kernel_notifications.TipBlock()};
471
                // We assume tip_block is set, because this is an instance
472
                // method on BlockTemplate and no template could have been
473
                // generated before a tip exists.
474
128
                tip_changed = Assume(tip_block) && tip_block != block_template->block.hashPrevBlock;
475
128
                return tip_changed || chainman.m_interrupt || interrupt_wait;
476
128
            });
477
93
            if (interrupt_wait) {
478
1
                interrupt_wait = false;
479
1
                return nullptr;
480
1
            }
481
93
        }
482
483
92
        if (chainman.m_interrupt) return nullptr;
484
        // At this point the tip changed, a full tick went by or we reached
485
        // the deadline.
486
487
        // Must release m_tip_block_mutex before locking cs_main, to avoid deadlocks.
488
92
        LOCK(::cs_main);
489
490
        // On test networks return a minimum difficulty block after 20 minutes
491
92
        if (!tip_changed && allow_min_difficulty) {
492
28
            const NodeClock::time_point tip_time{std::chrono::seconds{chainman.ActiveChain().Tip()->GetBlockTime()}};
493
28
            if (now > tip_time + 20min) {
494
1
                tip_changed = true;
495
1
            }
496
28
        }
497
498
        /**
499
         * We determine if fees increased compared to the previous template by generating
500
         * a fresh template. There may be more efficient ways to determine how much
501
         * (approximate) fees for the next block increased, perhaps more so after
502
         * Cluster Mempool.
503
         *
504
         * We'll also create a new template if the tip changed during this iteration.
505
         */
506
92
        if (wait_options.fee_threshold < MAX_MONEY || tip_changed) {
507
92
            auto new_tmpl{BlockAssembler{
508
92
                chainman.ActiveChainstate(),
509
92
                mempool,
510
92
                create_options
511
92
                }.CreateNewBlock()};
512
513
            // If the tip changed, return the new template regardless of its fees.
514
92
            if (tip_changed) return new_tmpl;
515
516
            // Calculate the original template total fees if we haven't already
517
31
            if (current_fees == -1) {
518
13
                current_fees = std::accumulate(block_template->vTxFees.begin(), block_template->vTxFees.end(), CAmount{0});
519
13
            }
520
521
            // Check if fees increased enough to return the new template
522
31
            const CAmount new_fees = std::accumulate(new_tmpl->vTxFees.begin(), new_tmpl->vTxFees.end(), CAmount{0});
523
31
            Assume(wait_options.fee_threshold != MAX_MONEY);
524
31
            if (new_fees >= current_fees + wait_options.fee_threshold) return new_tmpl;
525
31
        }
526
527
24
        now = NodeClock::now();
528
24
    } while (now < deadline);
529
530
6
    return nullptr;
531
75
}
532
533
std::optional<BlockRef> GetTip(ChainstateManager& chainman)
534
43.4k
{
535
43.4k
    LOCK(::cs_main);
536
43.4k
    CBlockIndex* tip{chainman.ActiveChain().Tip()};
537
43.4k
    if (!tip) return {};
538
43.4k
    return BlockRef{tip->GetBlockHash(), tip->nHeight};
539
43.4k
}
540
541
bool CooldownIfHeadersAhead(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const BlockRef& last_tip, bool& interrupt_mining)
542
19
{
543
19
    uint256 last_tip_hash{last_tip.hash};
544
545
20
    while (const std::optional<int> remaining = chainman.BlocksAheadOfTip()) {
546
2
        const int cooldown_seconds = std::clamp(*remaining, 3, 20);
547
2
        const auto cooldown_deadline{MockableSteadyClock::now() + std::chrono::seconds{cooldown_seconds}};
548
549
2
        {
550
2
            WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
551
4
            kernel_notifications.m_tip_block_cv.wait_until(lock, cooldown_deadline, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
552
4
                const auto tip_block = kernel_notifications.TipBlock();
553
4
                return chainman.m_interrupt || interrupt_mining || (tip_block && *tip_block != last_tip_hash);
554
4
            });
555
2
            if (chainman.m_interrupt || interrupt_mining) {
556
0
                interrupt_mining = false;
557
0
                return false;
558
0
            }
559
560
            // If the tip changed during the wait, extend the deadline
561
2
            const auto tip_block = kernel_notifications.TipBlock();
562
2
            if (tip_block && *tip_block != last_tip_hash) {
563
1
                last_tip_hash = *tip_block;
564
1
                continue;
565
1
            }
566
2
        }
567
568
        // No tip change and the cooldown window has expired.
569
1
        if (MockableSteadyClock::now() >= cooldown_deadline) break;
570
1
    }
571
572
19
    return true;
573
19
}
574
575
std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const uint256& current_tip, MillisecondsDouble& timeout, bool& interrupt)
576
43.2k
{
577
43.2k
    Assume(timeout >= 0ms); // No internal callers should use a negative timeout
578
43.2k
    if (timeout < 0ms) timeout = 0ms;
579
43.2k
    if (timeout > std::chrono::years{100}) timeout = std::chrono::years{100}; // Upper bound to avoid UB in std::chrono
580
43.2k
    auto deadline{std::chrono::steady_clock::now() + timeout};
581
43.2k
    {
582
43.2k
        WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
583
        // For callers convenience, wait longer than the provided timeout
584
        // during startup for the tip to be non-null. That way this function
585
        // always returns valid tip information when possible and only
586
        // returns null when shutting down, not when timing out.
587
43.2k
        kernel_notifications.m_tip_block_cv.wait(lock, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
588
43.2k
            return kernel_notifications.TipBlock() || chainman.m_interrupt || interrupt;
589
43.2k
        });
590
43.2k
        if (chainman.m_interrupt || interrupt) {
591
2
            interrupt = false;
592
2
            return {};
593
2
        }
594
        // At this point TipBlock is set, so continue to wait until it is
595
        // different then `current_tip` provided by caller.
596
43.2k
        kernel_notifications.m_tip_block_cv.wait_until(lock, deadline, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
597
43.2k
            return Assume(kernel_notifications.TipBlock()) != current_tip || chainman.m_interrupt || interrupt;
598
43.2k
        });
599
43.2k
        if (chainman.m_interrupt || interrupt) {
600
2
            interrupt = false;
601
2
            return {};
602
2
        }
603
43.2k
    }
604
605
    // Must release m_tip_block_mutex before getTip() locks cs_main, to
606
    // avoid deadlocks.
607
43.2k
    return GetTip(chainman);
608
43.2k
}
609
610
} // namespace node