Coverage Report

Created: 2026-07-23 20:35

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