Coverage Report

Created: 2026-09-02 14:16

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