Coverage Report

Created: 2026-09-01 13:35

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/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
590k
{
59
590k
    int64_t min_time{pindexPrev->GetMedianTimePast() + 1};
60
    // Height of block to be mined.
61
590k
    const int height{pindexPrev->nHeight + 1};
62
    // Account for BIP94 timewarp rule on all networks. This makes future
63
    // activation safer.
64
590k
    if (height % difficulty_adjustment_interval == 0) {
  Branch (64:9): [True: 2.69k, False: 587k]
65
2.69k
        min_time = std::max<int64_t>(min_time, pindexPrev->GetBlockTime() - MAX_TIMEWARP);
66
2.69k
    }
67
590k
    return min_time;
68
590k
}
69
70
int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
71
590k
{
72
590k
    int64_t nOldTime = pblock->nTime;
73
590k
    int64_t nNewTime{std::max<int64_t>(GetMinimumTime(pindexPrev, consensusParams.DifficultyAdjustmentInterval()),
74
590k
                                       TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()))};
75
76
590k
    if (nOldTime < nNewTime) {
  Branch (76:9): [True: 401k, False: 189k]
77
401k
        pblock->nTime = nNewTime;
78
401k
    }
79
80
    // Updating time can change work required on testnet:
81
590k
    if (consensusParams.fPowAllowMinDifficultyBlocks) {
  Branch (81:9): [True: 590k, False: 0]
82
590k
        pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
83
590k
    }
84
85
590k
    return nNewTime - nOldTime;
86
590k
}
87
88
void RegenerateCommitments(CBlock& block, ChainstateManager& chainman)
89
190k
{
90
190k
    CMutableTransaction tx{*block.vtx.at(0)};
91
190k
    tx.vout.erase(tx.vout.begin() + GetWitnessCommitmentIndex(block));
92
190k
    block.vtx.at(0) = MakeTransactionRef(tx);
93
94
190k
    const CBlockIndex* prev_block = WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock));
95
190k
    chainman.GenerateCoinbaseCommitment(block, prev_block);
96
97
190k
    block.hashMerkleRoot = BlockMerkleRoot(block);
98
190k
}
99
100
BlockAssembler::BlockAssembler(Chainstate& chainstate,
101
                               const CTxMemPool* mempool,
102
                               BlockCreateOptions options)
103
590k
    : chainparams{chainstate.m_chainman.GetParams()},
104
590k
      m_mempool{options.use_mempool ? mempool : nullptr},
  Branch (104:17): [True: 590k, False: 0]
105
590k
      m_chainstate{chainstate},
106
590k
      m_options{[&] {
107
590k
          if (auto result{CheckMiningOptions(options, /*use_argnames=*/false)}; !result) {
  Branch (107:81): [True: 0, False: 590k]
108
0
              throw std::runtime_error(util::ErrorString(result).original);
109
0
          }
110
590k
          return FlattenMiningOptions(std::move(options));
111
590k
      }()}
112
590k
{
113
590k
}
114
115
void BlockAssembler::resetBlock()
116
590k
{
117
    // Reserve space for fixed-size block header, txs count, and coinbase tx.
118
590k
    nBlockWeight = *Assert(m_options.block_reserved_weight);
119
590k
    nBlockSigOpsCost = m_options.coinbase_output_max_additional_sigops;
120
121
    // These counters do not include coinbase tx
122
590k
    nBlockTx = 0;
123
590k
    nFees = 0;
124
590k
}
125
126
std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock()
127
590k
{
128
590k
    const auto time_start{SteadyClock::now()};
129
130
590k
    resetBlock();
131
132
590k
    pblocktemplate.reset(new CBlockTemplate());
133
590k
    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
590k
    pblock->vtx.emplace_back();
138
139
590k
    LOCK(::cs_main);
140
590k
    CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip();
141
590k
    assert(pindexPrev != nullptr);
  Branch (141:5): [True: 590k, False: 0]
142
590k
    nHeight = pindexPrev->nHeight + 1;
143
144
590k
    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
590k
    if (chainparams.MineBlocksOnDemand()) {
  Branch (147:9): [True: 590k, False: 0]
148
590k
        pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion);
149
590k
    }
150
151
590k
    pblock->nTime = TicksSinceEpoch<std::chrono::seconds>(NodeClock::now());
152
590k
    m_lock_time_cutoff = pindexPrev->GetMedianTimePast();
153
154
590k
    if (m_mempool) {
  Branch (154:9): [True: 590k, False: 0]
155
590k
        LOCK(m_mempool->cs);
156
590k
        m_mempool->StartBlockBuilding();
157
590k
        addChunks();
158
590k
        m_mempool->StopBlockBuilding();
159
590k
    }
160
161
590k
    const auto time_1{SteadyClock::now()};
162
163
590k
    m_last_block_num_txs = nBlockTx;
164
590k
    m_last_block_weight = nBlockWeight;
165
166
    // Create coinbase transaction.
167
590k
    CMutableTransaction coinbaseTx;
168
169
    // Construct coinbase transaction struct in parallel
170
590k
    CoinbaseTx& coinbase_tx{pblocktemplate->m_coinbase_tx};
171
590k
    coinbase_tx.version = coinbaseTx.version;
172
173
590k
    coinbaseTx.vin.resize(1);
174
590k
    coinbaseTx.vin[0].prevout.SetNull();
175
590k
    coinbaseTx.vin[0].nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; // Make sure timelock is enforced.
176
590k
    coinbase_tx.sequence = coinbaseTx.vin[0].nSequence;
177
178
    // Add an output that spends the full coinbase reward.
179
590k
    coinbaseTx.vout.resize(1);
180
590k
    coinbaseTx.vout[0].scriptPubKey = m_options.coinbase_output_script;
181
    // Block subsidy + fees
182
590k
    const CAmount block_reward{nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus())};
183
590k
    coinbaseTx.vout[0].nValue = block_reward;
184
590k
    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
590k
    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
590k
    coinbase_tx.script_sig_prefix = coinbaseTx.vin[0].scriptSig;
196
590k
    if (nHeight <= 16) {
  Branch (196:9): [True: 84.4k, False: 505k]
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
84.4k
        coinbaseTx.vin[0].scriptSig << OP_0;
202
84.4k
    }
203
590k
    Assert(nHeight > 0);
204
590k
    coinbaseTx.nLockTime = static_cast<uint32_t>(nHeight - 1);
205
590k
    coinbase_tx.lock_time = coinbaseTx.nLockTime;
206
207
590k
    pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
208
590k
    m_chainstate.m_chainman.GenerateCoinbaseCommitment(*pblock, pindexPrev);
209
210
590k
    const CTransactionRef& final_coinbase{pblock->vtx[0]};
211
590k
    if (final_coinbase->HasWitness()) {
  Branch (211:9): [True: 590k, False: 0]
212
590k
        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
590k
        Assert(witness_stack.size() == 1 && witness_stack[0].size() == 32);
216
590k
        coinbase_tx.witness = uint256(witness_stack[0]);
217
590k
    }
218
590k
    if (const int witness_index = GetWitnessCommitmentIndex(*pblock); witness_index != NO_WITNESS_COMMITMENT) {
  Branch (218:71): [True: 590k, False: 0]
219
590k
        Assert(witness_index >= 0 && static_cast<size_t>(witness_index) < final_coinbase->vout.size());
220
590k
        coinbase_tx.required_outputs.push_back(final_coinbase->vout[witness_index]);
221
590k
    }
222
223
590k
    LogInfo("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
224
225
    // Fill in header
226
590k
    pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
227
590k
    UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
228
590k
    pblock->nBits          = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
229
590k
    pblock->nNonce         = 0;
230
231
590k
    if (m_options.test_block_validity) {
  Branch (231:9): [True: 590k, False: 0]
232
590k
        if (BlockValidationState state{TestBlockValidity(m_chainstate, *pblock, /*check_pow=*/false, /*check_merkle_root=*/false)}; !state.IsValid()) {
  Branch (232:133): [True: 0, False: 590k]
233
0
            throw std::runtime_error(strprintf("TestBlockValidity failed: %s", state.ToString()));
234
0
        }
235
590k
    }
236
590k
    const auto time_2{SteadyClock::now()};
237
238
590k
    LogDebug(BCLog::BENCH, "CreateNewBlock() chunks: %.2fms, validity: %.2fms (total %.2fms)\n",
239
590k
             Ticks<MillisecondsDouble>(time_1 - time_start),
240
590k
             Ticks<MillisecondsDouble>(time_2 - time_1),
241
590k
             Ticks<MillisecondsDouble>(time_2 - time_start));
242
243
590k
    return std::move(pblocktemplate);
244
590k
}
245
246
bool BlockAssembler::TestChunkBlockLimits(int64_t chunk_weight, int64_t chunk_sigops_cost) const
247
103k
{
248
    // block_max_weight has been flattened before block assembly limit checks.
249
103k
    Assert(m_options.block_max_weight);
250
103k
    if (nBlockWeight + chunk_weight >= m_options.block_max_weight) {
  Branch (250:9): [True: 29.4k, False: 73.8k]
251
29.4k
        return false;
252
29.4k
    }
253
73.8k
    if (nBlockSigOpsCost + chunk_sigops_cost >= MAX_BLOCK_SIGOPS_COST) {
  Branch (253:9): [True: 0, False: 73.8k]
254
0
        return false;
255
0
    }
256
73.8k
    return true;
257
73.8k
}
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
73.8k
{
263
83.4k
    for (const auto tx : txs) {
  Branch (263:24): [True: 83.4k, False: 73.8k]
264
83.4k
        if (!IsFinalTx(tx.get().GetTx(), nHeight, m_lock_time_cutoff)) {
  Branch (264:13): [True: 0, False: 83.4k]
265
0
            return false;
266
0
        }
267
83.4k
    }
268
73.8k
    return true;
269
73.8k
}
270
271
void BlockAssembler::AddToBlock(const CTxMemPoolEntry& entry)
272
83.4k
{
273
83.4k
    pblocktemplate->block.vtx.emplace_back(entry.GetSharedTx());
274
83.4k
    pblocktemplate->vTxFees.push_back(entry.GetFee());
275
83.4k
    pblocktemplate->vTxSigOpsCost.push_back(entry.GetSigOpCost());
276
83.4k
    nBlockWeight += entry.GetTxWeight();
277
83.4k
    ++nBlockTx;
278
83.4k
    nBlockSigOpsCost += entry.GetSigOpCost();
279
83.4k
    nFees += entry.GetFee();
280
281
83.4k
    if (*m_options.print_modified_fee) {
  Branch (281:9): [True: 0, False: 83.4k]
282
0
        LogInfo("fee rate %s txid %s\n",
283
0
                  CFeeRate(entry.GetModifiedFee(), entry.GetTxSize()).ToString(),
284
0
                  entry.GetTx().GetHash().ToString());
285
0
    }
286
83.4k
}
287
288
void BlockAssembler::addChunks()
289
590k
{
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
590k
    const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
294
590k
    constexpr int32_t BLOCK_FULL_ENOUGH_WEIGHT_DELTA = 4000;
295
590k
    int64_t nConsecutiveFailed = 0;
296
297
590k
    std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> selected_transactions;
298
590k
    selected_transactions.reserve(MAX_CLUSTER_COUNT_LIMIT);
299
590k
    FeePerWeight chunk_feerate;
300
301
    // This fills selected_transactions
302
590k
    chunk_feerate = m_mempool->GetBlockBuilderChunk(selected_transactions);
303
590k
    FeePerVSize chunk_feerate_vsize = ToFeePerVSize(chunk_feerate);
304
305
693k
    while (selected_transactions.size() > 0) {
  Branch (305:12): [True: 106k, False: 587k]
306
        // Check to see if min fee rate is still respected.
307
106k
        if (ByRatio{chunk_feerate_vsize} < ByRatio{m_options.block_min_fee_rate->GetFeePerVSize()}) {
  Branch (307:13): [True: 2.79k, False: 103k]
308
            // Everything else we might consider has a lower feerate
309
2.79k
            return;
310
2.79k
        }
311
312
103k
        int64_t chunk_sig_ops = 0;
313
103k
        int64_t chunk_weight = 0;
314
116k
        for (const auto& tx : selected_transactions) {
  Branch (314:29): [True: 116k, False: 103k]
315
116k
            chunk_sig_ops += tx.get().GetSigOpCost();
316
116k
            chunk_weight += tx.get().GetTxWeight();
317
116k
        }
318
319
        // Check to see if this chunk will fit.
320
103k
        if (!TestChunkBlockLimits(chunk_weight, chunk_sig_ops) || !TestChunkTransactions(selected_transactions)) {
  Branch (320:13): [True: 29.4k, False: 73.8k]
  Branch (320:67): [True: 0, False: 73.8k]
321
            // This chunk won't fit, so we skip it and will try the next best one.
322
29.4k
            m_mempool->SkipBuilderChunk();
323
29.4k
            ++nConsecutiveFailed;
324
325
            // block_max_weight has been flattened before block assembly limit checks.
326
29.4k
            Assert(m_options.block_max_weight);
327
29.4k
            if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight +
  Branch (327:17): [True: 0, False: 29.4k]
  Branch (327:66): [True: 0, False: 0]
328
0
                    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
0
                return;
331
0
            }
332
73.8k
        } else {
333
73.8k
            m_mempool->IncludeBuilderChunk();
334
335
            // This chunk will fit, so add it to the block.
336
73.8k
            nConsecutiveFailed = 0;
337
83.4k
            for (const auto& tx : selected_transactions) {
  Branch (337:33): [True: 83.4k, False: 73.8k]
338
83.4k
                AddToBlock(tx);
339
83.4k
            }
340
73.8k
            pblocktemplate->m_package_feerates.emplace_back(chunk_feerate_vsize);
341
73.8k
        }
342
343
103k
        selected_transactions.clear();
344
103k
        chunk_feerate = m_mempool->GetBlockBuilderChunk(selected_transactions);
345
103k
        chunk_feerate_vsize = ToFeePerVSize(chunk_feerate);
346
103k
    }
347
590k
}
348
349
void AddMerkleRootAndCoinbase(CBlock& block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce)
350
0
{
351
0
    if (block.vtx.size() == 0) {
  Branch (351:9): [True: 0, False: 0]
352
0
        block.vtx.emplace_back(coinbase);
353
0
    } else {
354
0
        block.vtx[0] = coinbase;
355
0
    }
356
0
    block.nVersion = version;
357
0
    block.nTime = timestamp;
358
0
    block.nNonce = nonce;
359
0
    block.hashMerkleRoot = BlockMerkleRoot(block);
360
361
    // Reset cached checks
362
0
    block.m_checked_witness_commitment = false;
363
0
    block.m_checked_merkle_root = false;
364
0
    block.fChecked = false;
365
0
}
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
0
    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
0
    {
380
0
        if (block->GetHash() != m_hash) return;
  Branch (380:13): [True: 0, False: 0]
381
        // ProcessNewBlock emits BlockChecked synchronously while holding cs_main,
382
        // so SubmitBlock can read these fields after ProcessNewBlock returns
383
        // without extra synchronization.
384
0
        m_found = true;
385
0
        m_state = state;
386
0
    }
387
};
388
} // namespace
389
390
bool SubmitBlock(ChainstateManager& chainman, const std::shared_ptr<const CBlock>& block, std::string& reason, std::string& debug)
391
0
{
392
0
    reason.clear();
393
0
    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
0
    auto sc = std::make_shared<SubmitBlockStateCatcher>(block->GetHash());
402
0
    CHECK_NONFATAL(chainman.m_options.signals)->RegisterSharedValidationInterface(sc);
403
0
    bool new_block;
404
0
    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
0
    CHECK_NONFATAL(chainman.m_options.signals)->UnregisterSharedValidationInterface(sc);
408
409
0
    if (!new_block && accepted) {
  Branch (409:9): [True: 0, False: 0]
  Branch (409:23): [True: 0, False: 0]
410
0
        reason = "duplicate";
411
0
    } else if (!accepted && (!sc->m_found || sc->m_state.IsValid())) {
  Branch (411:16): [True: 0, False: 0]
  Branch (411:30): [True: 0, False: 0]
  Branch (411:46): [True: 0, False: 0]
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
0
    } else if (!sc->m_found) {
  Branch (417:16): [True: 0, False: 0]
418
        // The block was accepted but not connected, for example if it does not
419
        // have more work than the current tip.
420
0
        reason = "inconclusive";
421
0
    } else if (!sc->m_state.IsValid()) {
  Branch (421:16): [True: 0, False: 0]
422
0
        reason = sc->m_state.GetRejectReason();
423
0
        debug = sc->m_state.GetDebugMessage();
424
0
    }
425
0
    const bool result{accepted && new_block && reason.empty()};
  Branch (425:23): [True: 0, False: 0]
  Branch (425:35): [True: 0, False: 0]
  Branch (425:48): [True: 0, False: 0]
426
0
    CHECK_NONFATAL(result == reason.empty());
427
0
    return result;
428
0
}
429
430
void InterruptWait(KernelNotifications& kernel_notifications, bool& interrupt_wait)
431
0
{
432
0
    LOCK(kernel_notifications.m_tip_block_mutex);
433
0
    interrupt_wait = true;
434
0
    kernel_notifications.m_tip_block_cv.notify_all();
435
0
}
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
0
{
445
    // Delay calculating the current template fees, just in case a new block
446
    // comes in before the next tick.
447
0
    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
0
    auto now{NodeClock::now()};
452
0
    const auto deadline = now + wait_options.timeout;
453
0
    const MillisecondsDouble tick{1000};
454
0
    const bool allow_min_difficulty{chainman.GetParams().GetConsensus().fPowAllowMinDifficultyBlocks};
455
456
0
    do {
457
0
        bool tip_changed{false};
458
0
        {
459
0
            WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
460
            // Note that wait_until() checks the predicate before waiting
461
0
            kernel_notifications.m_tip_block_cv.wait_until(lock, std::min(now + tick, deadline), [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
462
0
                AssertLockHeld(kernel_notifications.m_tip_block_mutex);
463
0
                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
0
                tip_changed = Assume(tip_block) && tip_block != block_template->block.hashPrevBlock;
  Branch (467:52): [True: 0, False: 0]
468
0
                return tip_changed || chainman.m_interrupt || interrupt_wait;
  Branch (468:24): [True: 0, False: 0]
  Branch (468:39): [True: 0, False: 0]
  Branch (468:63): [True: 0, False: 0]
469
0
            });
470
0
            if (interrupt_wait) {
  Branch (470:17): [True: 0, False: 0]
471
0
                interrupt_wait = false;
472
0
                return nullptr;
473
0
            }
474
0
        }
475
476
0
        if (chainman.m_interrupt) return nullptr;
  Branch (476:13): [True: 0, False: 0]
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
0
        LOCK(::cs_main);
482
483
        // On test networks return a minimum difficulty block after 20 minutes
484
0
        if (!tip_changed && allow_min_difficulty) {
  Branch (484:13): [True: 0, False: 0]
  Branch (484:29): [True: 0, False: 0]
485
0
            const NodeClock::time_point tip_time{std::chrono::seconds{chainman.ActiveChain().Tip()->GetBlockTime()}};
486
0
            if (now > tip_time + 20min) {
  Branch (486:17): [True: 0, False: 0]
487
0
                tip_changed = true;
488
0
            }
489
0
        }
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
0
        if (wait_options.fee_threshold < MAX_MONEY || tip_changed) {
  Branch (499:13): [True: 0, False: 0]
  Branch (499:55): [True: 0, False: 0]
500
0
            auto new_tmpl{BlockAssembler{
501
0
                chainman.ActiveChainstate(),
502
0
                mempool,
503
0
                create_options
504
0
                }.CreateNewBlock()};
505
506
            // If the tip changed, return the new template regardless of its fees.
507
0
            if (tip_changed) return new_tmpl;
  Branch (507:17): [True: 0, False: 0]
508
509
            // Calculate the original template total fees if we haven't already
510
0
            if (current_fees == -1) {
  Branch (510:17): [True: 0, False: 0]
511
0
                current_fees = std::accumulate(block_template->vTxFees.begin(), block_template->vTxFees.end(), CAmount{0});
512
0
            }
513
514
            // Check if fees increased enough to return the new template
515
0
            const CAmount new_fees = std::accumulate(new_tmpl->vTxFees.begin(), new_tmpl->vTxFees.end(), CAmount{0});
516
0
            Assume(wait_options.fee_threshold != MAX_MONEY);
517
0
            if (new_fees >= current_fees + wait_options.fee_threshold) return new_tmpl;
  Branch (517:17): [True: 0, False: 0]
518
0
        }
519
520
0
        now = NodeClock::now();
521
0
    } while (now < deadline);
  Branch (521:14): [True: 0, False: 0]
522
523
0
    return nullptr;
524
0
}
525
526
std::optional<BlockRef> GetTip(ChainstateManager& chainman)
527
576k
{
528
576k
    LOCK(::cs_main);
529
576k
    CBlockIndex* tip{chainman.ActiveChain().Tip()};
530
576k
    if (!tip) return {};
  Branch (530:9): [True: 0, False: 576k]
531
576k
    return BlockRef{tip->GetBlockHash(), tip->nHeight};
532
576k
}
533
534
bool CooldownIfHeadersAhead(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const BlockRef& last_tip, bool& interrupt_mining)
535
0
{
536
0
    uint256 last_tip_hash{last_tip.hash};
537
538
0
    while (const std::optional<int> remaining = chainman.BlocksAheadOfTip()) {
  Branch (538:37): [True: 0, False: 0]
539
0
        const int cooldown_seconds = std::clamp(*remaining, 3, 20);
540
0
        const auto cooldown_deadline{MockableSteadyClock::now() + std::chrono::seconds{cooldown_seconds}};
541
542
0
        {
543
0
            WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
544
0
            kernel_notifications.m_tip_block_cv.wait_until(lock, cooldown_deadline, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
545
0
                const auto tip_block = kernel_notifications.TipBlock();
546
0
                return chainman.m_interrupt || interrupt_mining || (tip_block && *tip_block != last_tip_hash);
  Branch (546:24): [True: 0, False: 0]
  Branch (546:48): [True: 0, False: 0]
  Branch (546:69): [True: 0, False: 0]
  Branch (546:82): [True: 0, False: 0]
547
0
            });
548
0
            if (chainman.m_interrupt || interrupt_mining) {
  Branch (548:17): [True: 0, False: 0]
  Branch (548:41): [True: 0, False: 0]
549
0
                interrupt_mining = false;
550
0
                return false;
551
0
            }
552
553
            // If the tip changed during the wait, extend the deadline
554
0
            const auto tip_block = kernel_notifications.TipBlock();
555
0
            if (tip_block && *tip_block != last_tip_hash) {
  Branch (555:17): [True: 0, False: 0]
  Branch (555:30): [True: 0, False: 0]
556
0
                last_tip_hash = *tip_block;
557
0
                continue;
558
0
            }
559
0
        }
560
561
        // No tip change and the cooldown window has expired.
562
0
        if (MockableSteadyClock::now() >= cooldown_deadline) break;
  Branch (562:13): [True: 0, False: 0]
563
0
    }
564
565
0
    return true;
566
0
}
567
568
std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const uint256& current_tip, MillisecondsDouble& timeout, bool& interrupt)
569
576k
{
570
576k
    Assume(timeout >= 0ms); // No internal callers should use a negative timeout
571
576k
    if (timeout < 0ms) timeout = 0ms;
  Branch (571:9): [True: 0, False: 576k]
572
576k
    if (timeout > std::chrono::years{100}) timeout = std::chrono::years{100}; // Upper bound to avoid UB in std::chrono
  Branch (572:9): [True: 576k, False: 0]
573
576k
    auto deadline{std::chrono::steady_clock::now() + timeout};
574
576k
    {
575
576k
        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
576k
        kernel_notifications.m_tip_block_cv.wait(lock, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
581
576k
            return kernel_notifications.TipBlock() || chainman.m_interrupt || interrupt;
  Branch (581:20): [True: 576k, False: 0]
  Branch (581:55): [True: 0, False: 0]
  Branch (581:79): [True: 0, False: 0]
582
576k
        });
583
576k
        if (chainman.m_interrupt || interrupt) {
  Branch (583:13): [True: 0, False: 576k]
  Branch (583:37): [True: 0, False: 576k]
584
0
            interrupt = false;
585
0
            return {};
586
0
        }
587
        // At this point TipBlock is set, so continue to wait until it is
588
        // different then `current_tip` provided by caller.
589
576k
        kernel_notifications.m_tip_block_cv.wait_until(lock, deadline, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
590
576k
            return Assume(kernel_notifications.TipBlock()) != current_tip || chainman.m_interrupt || interrupt;
  Branch (590:20): [True: 576k, False: 0]
  Branch (590:78): [True: 0, False: 0]
  Branch (590:102): [True: 0, False: 0]
591
576k
        });
592
576k
        if (chainman.m_interrupt || interrupt) {
  Branch (592:13): [True: 0, False: 576k]
  Branch (592:37): [True: 0, False: 576k]
593
0
            interrupt = false;
594
0
            return {};
595
0
        }
596
576k
    }
597
598
    // Must release m_tip_block_mutex before getTip() locks cs_main, to
599
    // avoid deadlocks.
600
576k
    return GetTip(chainman);
601
576k
}
602
603
} // namespace node