Coverage Report

Created: 2025-09-19 18:22

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-2022 The Bitcoin Core developers
3
// Distributed under the MIT software license, see the accompanying
4
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6
#include <node/miner.h>
7
8
#include <chain.h>
9
#include <chainparams.h>
10
#include <coins.h>
11
#include <common/args.h>
12
#include <consensus/amount.h>
13
#include <consensus/consensus.h>
14
#include <consensus/merkle.h>
15
#include <consensus/tx_verify.h>
16
#include <consensus/validation.h>
17
#include <deploymentstatus.h>
18
#include <logging.h>
19
#include <node/context.h>
20
#include <node/kernel_notifications.h>
21
#include <policy/feerate.h>
22
#include <policy/policy.h>
23
#include <pow.h>
24
#include <primitives/transaction.h>
25
#include <util/moneystr.h>
26
#include <util/signalinterrupt.h>
27
#include <util/time.h>
28
#include <validation.h>
29
30
#include <algorithm>
31
#include <utility>
32
33
namespace node {
34
35
int64_t GetMinimumTime(const CBlockIndex* pindexPrev, const int64_t difficulty_adjustment_interval)
36
0
{
37
0
    int64_t min_time{pindexPrev->GetMedianTimePast() + 1};
38
    // Height of block to be mined.
39
0
    const int height{pindexPrev->nHeight + 1};
40
    // Account for BIP94 timewarp rule on all networks. This makes future
41
    // activation safer.
42
0
    if (height % difficulty_adjustment_interval == 0) {
43
0
        min_time = std::max<int64_t>(min_time, pindexPrev->GetBlockTime() - MAX_TIMEWARP);
44
0
    }
45
0
    return min_time;
46
0
}
47
48
int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
49
0
{
50
0
    int64_t nOldTime = pblock->nTime;
51
0
    int64_t nNewTime{std::max<int64_t>(GetMinimumTime(pindexPrev, consensusParams.DifficultyAdjustmentInterval()),
52
0
                                       TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()))};
53
54
0
    if (nOldTime < nNewTime) {
55
0
        pblock->nTime = nNewTime;
56
0
    }
57
58
    // Updating time can change work required on testnet:
59
0
    if (consensusParams.fPowAllowMinDifficultyBlocks) {
60
0
        pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
61
0
    }
62
63
0
    return nNewTime - nOldTime;
64
0
}
65
66
void RegenerateCommitments(CBlock& block, ChainstateManager& chainman)
67
0
{
68
0
    CMutableTransaction tx{*block.vtx.at(0)};
69
0
    tx.vout.erase(tx.vout.begin() + GetWitnessCommitmentIndex(block));
70
0
    block.vtx.at(0) = MakeTransactionRef(tx);
71
72
0
    const CBlockIndex* prev_block = WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock));
73
0
    chainman.GenerateCoinbaseCommitment(block, prev_block);
74
75
0
    block.hashMerkleRoot = BlockMerkleRoot(block);
76
0
}
77
78
static BlockAssembler::Options ClampOptions(BlockAssembler::Options options)
79
0
{
80
0
    options.block_reserved_weight = std::clamp<size_t>(options.block_reserved_weight, MINIMUM_BLOCK_RESERVED_WEIGHT, MAX_BLOCK_WEIGHT);
81
0
    options.coinbase_output_max_additional_sigops = std::clamp<size_t>(options.coinbase_output_max_additional_sigops, 0, MAX_BLOCK_SIGOPS_COST);
82
    // Limit weight to between block_reserved_weight and MAX_BLOCK_WEIGHT for sanity:
83
    // block_reserved_weight can safely exceed -blockmaxweight, but the rest of the block template will be empty.
84
0
    options.nBlockMaxWeight = std::clamp<size_t>(options.nBlockMaxWeight, options.block_reserved_weight, MAX_BLOCK_WEIGHT);
85
0
    return options;
86
0
}
87
88
BlockAssembler::BlockAssembler(Chainstate& chainstate, const CTxMemPool* mempool, const Options& options)
89
0
    : chainparams{chainstate.m_chainman.GetParams()},
90
0
      m_mempool{options.use_mempool ? mempool : nullptr},
91
0
      m_chainstate{chainstate},
92
0
      m_options{ClampOptions(options)}
93
0
{
94
0
}
95
96
void ApplyArgsManOptions(const ArgsManager& args, BlockAssembler::Options& options)
97
0
{
98
    // Block resource limits
99
0
    options.nBlockMaxWeight = args.GetIntArg("-blockmaxweight", options.nBlockMaxWeight);
100
0
    if (const auto blockmintxfee{args.GetArg("-blockmintxfee")}) {
101
0
        if (const auto parsed{ParseMoney(*blockmintxfee)}) options.blockMinFeeRate = CFeeRate{*parsed};
102
0
    }
103
0
    options.print_modified_fee = args.GetBoolArg("-printpriority", options.print_modified_fee);
104
0
    options.block_reserved_weight = args.GetIntArg("-blockreservedweight", options.block_reserved_weight);
105
0
}
106
107
void BlockAssembler::resetBlock()
108
0
{
109
0
    inBlock.clear();
110
111
    // Reserve space for fixed-size block header, txs count, and coinbase tx.
112
0
    nBlockWeight = m_options.block_reserved_weight;
113
0
    nBlockSigOpsCost = m_options.coinbase_output_max_additional_sigops;
114
115
    // These counters do not include coinbase tx
116
0
    nBlockTx = 0;
117
0
    nFees = 0;
118
0
}
119
120
std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock()
121
0
{
122
0
    const auto time_start{SteadyClock::now()};
123
124
0
    resetBlock();
125
126
0
    pblocktemplate.reset(new CBlockTemplate());
127
0
    CBlock* const pblock = &pblocktemplate->block; // pointer for convenience
128
129
    // Add dummy coinbase tx as first transaction. It is skipped by the
130
    // getblocktemplate RPC and mining interface consumers must not use it.
131
0
    pblock->vtx.emplace_back();
132
133
0
    LOCK(::cs_main);
134
0
    CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip();
135
0
    assert(pindexPrev != nullptr);
136
0
    nHeight = pindexPrev->nHeight + 1;
137
138
0
    pblock->nVersion = m_chainstate.m_chainman.m_versionbitscache.ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
139
    // -regtest only: allow overriding block.nVersion with
140
    // -blockversion=N to test forking scenarios
141
0
    if (chainparams.MineBlocksOnDemand()) {
142
0
        pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion);
143
0
    }
144
145
0
    pblock->nTime = TicksSinceEpoch<std::chrono::seconds>(NodeClock::now());
146
0
    m_lock_time_cutoff = pindexPrev->GetMedianTimePast();
147
148
0
    int nPackagesSelected = 0;
149
0
    int nDescendantsUpdated = 0;
150
0
    if (m_mempool) {
151
0
        addPackageTxs(nPackagesSelected, nDescendantsUpdated);
152
0
    }
153
154
0
    const auto time_1{SteadyClock::now()};
155
156
0
    m_last_block_num_txs = nBlockTx;
157
0
    m_last_block_weight = nBlockWeight;
158
159
    // Create coinbase transaction.
160
0
    CMutableTransaction coinbaseTx;
161
0
    coinbaseTx.vin.resize(1);
162
0
    coinbaseTx.vin[0].prevout.SetNull();
163
0
    coinbaseTx.vin[0].nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; // Make sure timelock is enforced.
164
0
    coinbaseTx.vout.resize(1);
165
0
    coinbaseTx.vout[0].scriptPubKey = m_options.coinbase_output_script;
166
0
    coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
167
0
    coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
168
0
    Assert(nHeight > 0);
169
0
    coinbaseTx.nLockTime = static_cast<uint32_t>(nHeight - 1);
170
0
    pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
171
0
    pblocktemplate->vchCoinbaseCommitment = m_chainstate.m_chainman.GenerateCoinbaseCommitment(*pblock, pindexPrev);
172
173
0
    LogPrintf("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
174
175
    // Fill in header
176
0
    pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
177
0
    UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
178
0
    pblock->nBits          = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
179
0
    pblock->nNonce         = 0;
180
181
0
    if (m_options.test_block_validity) {
182
0
        if (BlockValidationState state{TestBlockValidity(m_chainstate, *pblock, /*check_pow=*/false, /*check_merkle_root=*/false)}; !state.IsValid()) {
183
0
            throw std::runtime_error(strprintf("TestBlockValidity failed: %s", state.ToString()));
184
0
        }
185
0
    }
186
0
    const auto time_2{SteadyClock::now()};
187
188
0
    LogDebug(BCLog::BENCH, "CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n",
189
0
             Ticks<MillisecondsDouble>(time_1 - time_start), nPackagesSelected, nDescendantsUpdated,
190
0
             Ticks<MillisecondsDouble>(time_2 - time_1),
191
0
             Ticks<MillisecondsDouble>(time_2 - time_start));
192
193
0
    return std::move(pblocktemplate);
194
0
}
195
196
void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet)
197
0
{
198
0
    for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
199
        // Only test txs not already in the block
200
0
        if (inBlock.count((*iit)->GetSharedTx()->GetHash())) {
201
0
            testSet.erase(iit++);
202
0
        } else {
203
0
            iit++;
204
0
        }
205
0
    }
206
0
}
207
208
bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
209
0
{
210
    // TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
211
0
    if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= m_options.nBlockMaxWeight) {
212
0
        return false;
213
0
    }
214
0
    if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST) {
215
0
        return false;
216
0
    }
217
0
    return true;
218
0
}
219
220
// Perform transaction-level checks before adding to block:
221
// - transaction finality (locktime)
222
bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package) const
223
0
{
224
0
    for (CTxMemPool::txiter it : package) {
225
0
        if (!IsFinalTx(it->GetTx(), nHeight, m_lock_time_cutoff)) {
226
0
            return false;
227
0
        }
228
0
    }
229
0
    return true;
230
0
}
231
232
void BlockAssembler::AddToBlock(CTxMemPool::txiter iter)
233
0
{
234
0
    pblocktemplate->block.vtx.emplace_back(iter->GetSharedTx());
235
0
    pblocktemplate->vTxFees.push_back(iter->GetFee());
236
0
    pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
237
0
    nBlockWeight += iter->GetTxWeight();
238
0
    ++nBlockTx;
239
0
    nBlockSigOpsCost += iter->GetSigOpCost();
240
0
    nFees += iter->GetFee();
241
0
    inBlock.insert(iter->GetSharedTx()->GetHash());
242
243
0
    if (m_options.print_modified_fee) {
244
0
        LogPrintf("fee rate %s txid %s\n",
245
0
                  CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
246
0
                  iter->GetTx().GetHash().ToString());
247
0
    }
248
0
}
249
250
/** Add descendants of given transactions to mapModifiedTx with ancestor
251
 * state updated assuming given transactions are inBlock. Returns number
252
 * of updated descendants. */
253
static int UpdatePackagesForAdded(const CTxMemPool& mempool,
254
                                  const CTxMemPool::setEntries& alreadyAdded,
255
                                  indexed_modified_transaction_set& mapModifiedTx) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs)
256
0
{
257
0
    AssertLockHeld(mempool.cs);
258
259
0
    int nDescendantsUpdated = 0;
260
0
    for (CTxMemPool::txiter it : alreadyAdded) {
261
0
        CTxMemPool::setEntries descendants;
262
0
        mempool.CalculateDescendants(it, descendants);
263
        // Insert all descendants (not yet in block) into the modified set
264
0
        for (CTxMemPool::txiter desc : descendants) {
265
0
            if (alreadyAdded.count(desc)) {
266
0
                continue;
267
0
            }
268
0
            ++nDescendantsUpdated;
269
0
            modtxiter mit = mapModifiedTx.find(desc);
270
0
            if (mit == mapModifiedTx.end()) {
271
0
                CTxMemPoolModifiedEntry modEntry(desc);
272
0
                mit = mapModifiedTx.insert(modEntry).first;
273
0
            }
274
0
            mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
275
0
        }
276
0
    }
277
0
    return nDescendantsUpdated;
278
0
}
279
280
void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, std::vector<CTxMemPool::txiter>& sortedEntries)
281
0
{
282
    // Sort package by ancestor count
283
    // If a transaction A depends on transaction B, then A's ancestor count
284
    // must be greater than B's.  So this is sufficient to validly order the
285
    // transactions for block inclusion.
286
0
    sortedEntries.clear();
287
0
    sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
288
0
    std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
289
0
}
290
291
// This transaction selection algorithm orders the mempool based
292
// on feerate of a transaction including all unconfirmed ancestors.
293
// Since we don't remove transactions from the mempool as we select them
294
// for block inclusion, we need an alternate method of updating the feerate
295
// of a transaction with its not-yet-selected ancestors as we go.
296
// This is accomplished by walking the in-mempool descendants of selected
297
// transactions and storing a temporary modified state in mapModifiedTxs.
298
// Each time through the loop, we compare the best transaction in
299
// mapModifiedTxs with the next transaction in the mempool to decide what
300
// transaction package to work on next.
301
void BlockAssembler::addPackageTxs(int& nPackagesSelected, int& nDescendantsUpdated)
302
0
{
303
0
    const auto& mempool{*Assert(m_mempool)};
304
0
    LOCK(mempool.cs);
305
306
    // mapModifiedTx will store sorted packages after they are modified
307
    // because some of their txs are already in the block
308
0
    indexed_modified_transaction_set mapModifiedTx;
309
    // Keep track of entries that failed inclusion, to avoid duplicate work
310
0
    std::set<Txid> failedTx;
311
312
0
    CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin();
313
0
    CTxMemPool::txiter iter;
314
315
    // Limit the number of attempts to add transactions to the block when it is
316
    // close to full; this is just a simple heuristic to finish quickly if the
317
    // mempool has a lot of entries.
318
0
    const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
319
0
    constexpr int32_t BLOCK_FULL_ENOUGH_WEIGHT_DELTA = 4000;
320
0
    int64_t nConsecutiveFailed = 0;
321
322
0
    while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty()) {
323
        // First try to find a new transaction in mapTx to evaluate.
324
        //
325
        // Skip entries in mapTx that are already in a block or are present
326
        // in mapModifiedTx (which implies that the mapTx ancestor state is
327
        // stale due to ancestor inclusion in the block)
328
        // Also skip transactions that we've already failed to add. This can happen if
329
        // we consider a transaction in mapModifiedTx and it fails: we can then
330
        // potentially consider it again while walking mapTx.  It's currently
331
        // guaranteed to fail again, but as a belt-and-suspenders check we put it in
332
        // failedTx and avoid re-evaluation, since the re-evaluation would be using
333
        // cached size/sigops/fee values that are not actually correct.
334
        /** Return true if given transaction from mapTx has already been evaluated,
335
         * or if the transaction's cached data in mapTx is incorrect. */
336
0
        if (mi != mempool.mapTx.get<ancestor_score>().end()) {
337
0
            auto it = mempool.mapTx.project<0>(mi);
338
0
            assert(it != mempool.mapTx.end());
339
0
            if (mapModifiedTx.count(it) || inBlock.count(it->GetSharedTx()->GetHash()) || failedTx.count(it->GetSharedTx()->GetHash())) {
340
0
                ++mi;
341
0
                continue;
342
0
            }
343
0
        }
344
345
        // Now that mi is not stale, determine which transaction to evaluate:
346
        // the next entry from mapTx, or the best from mapModifiedTx?
347
0
        bool fUsingModified = false;
348
349
0
        modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
350
0
        if (mi == mempool.mapTx.get<ancestor_score>().end()) {
351
            // We're out of entries in mapTx; use the entry from mapModifiedTx
352
0
            iter = modit->iter;
353
0
            fUsingModified = true;
354
0
        } else {
355
            // Try to compare the mapTx entry to the mapModifiedTx entry
356
0
            iter = mempool.mapTx.project<0>(mi);
357
0
            if (modit != mapModifiedTx.get<ancestor_score>().end() &&
358
0
                    CompareTxMemPoolEntryByAncestorFee()(*modit, CTxMemPoolModifiedEntry(iter))) {
359
                // The best entry in mapModifiedTx has higher score
360
                // than the one from mapTx.
361
                // Switch which transaction (package) to consider
362
0
                iter = modit->iter;
363
0
                fUsingModified = true;
364
0
            } else {
365
                // Either no entry in mapModifiedTx, or it's worse than mapTx.
366
                // Increment mi for the next loop iteration.
367
0
                ++mi;
368
0
            }
369
0
        }
370
371
        // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
372
        // contain anything that is inBlock.
373
0
        assert(!inBlock.count(iter->GetSharedTx()->GetHash()));
374
375
0
        uint64_t packageSize = iter->GetSizeWithAncestors();
376
0
        CAmount packageFees = iter->GetModFeesWithAncestors();
377
0
        int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
378
0
        if (fUsingModified) {
379
0
            packageSize = modit->nSizeWithAncestors;
380
0
            packageFees = modit->nModFeesWithAncestors;
381
0
            packageSigOpsCost = modit->nSigOpCostWithAncestors;
382
0
        }
383
384
0
        if (packageFees < m_options.blockMinFeeRate.GetFee(packageSize)) {
385
            // Everything else we might consider has a lower fee rate
386
0
            return;
387
0
        }
388
389
0
        if (!TestPackage(packageSize, packageSigOpsCost)) {
390
0
            if (fUsingModified) {
391
                // Since we always look at the best entry in mapModifiedTx,
392
                // we must erase failed entries so that we can consider the
393
                // next best entry on the next loop iteration
394
0
                mapModifiedTx.get<ancestor_score>().erase(modit);
395
0
                failedTx.insert(iter->GetSharedTx()->GetHash());
396
0
            }
397
398
0
            ++nConsecutiveFailed;
399
400
0
            if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight >
401
0
                    m_options.nBlockMaxWeight - BLOCK_FULL_ENOUGH_WEIGHT_DELTA) {
402
                // Give up if we're close to full and haven't succeeded in a while
403
0
                break;
404
0
            }
405
0
            continue;
406
0
        }
407
408
0
        auto ancestors{mempool.AssumeCalculateMemPoolAncestors(__func__, *iter, CTxMemPool::Limits::NoLimits(), /*fSearchForParents=*/false)};
409
410
0
        onlyUnconfirmed(ancestors);
411
0
        ancestors.insert(iter);
412
413
        // Test if all tx's are Final
414
0
        if (!TestPackageTransactions(ancestors)) {
415
0
            if (fUsingModified) {
416
0
                mapModifiedTx.get<ancestor_score>().erase(modit);
417
0
                failedTx.insert(iter->GetSharedTx()->GetHash());
418
0
            }
419
0
            continue;
420
0
        }
421
422
        // This transaction will make it in; reset the failed counter.
423
0
        nConsecutiveFailed = 0;
424
425
        // Package can be added. Sort the entries in a valid order.
426
0
        std::vector<CTxMemPool::txiter> sortedEntries;
427
0
        SortForBlock(ancestors, sortedEntries);
428
429
0
        for (size_t i = 0; i < sortedEntries.size(); ++i) {
430
0
            AddToBlock(sortedEntries[i]);
431
            // Erase from the modified set, if present
432
0
            mapModifiedTx.erase(sortedEntries[i]);
433
0
        }
434
435
0
        ++nPackagesSelected;
436
0
        pblocktemplate->m_package_feerates.emplace_back(packageFees, static_cast<int32_t>(packageSize));
437
438
        // Update transactions that depend on each of these
439
0
        nDescendantsUpdated += UpdatePackagesForAdded(mempool, ancestors, mapModifiedTx);
440
0
    }
441
0
}
442
443
void AddMerkleRootAndCoinbase(CBlock& block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce)
444
0
{
445
0
    if (block.vtx.size() == 0) {
446
0
        block.vtx.emplace_back(coinbase);
447
0
    } else {
448
0
        block.vtx[0] = coinbase;
449
0
    }
450
0
    block.nVersion = version;
451
0
    block.nTime = timestamp;
452
0
    block.nNonce = nonce;
453
0
    block.hashMerkleRoot = BlockMerkleRoot(block);
454
0
}
455
456
std::unique_ptr<CBlockTemplate> WaitAndCreateNewBlock(ChainstateManager& chainman,
457
                                                      KernelNotifications& kernel_notifications,
458
                                                      CTxMemPool* mempool,
459
                                                      const std::unique_ptr<CBlockTemplate>& block_template,
460
                                                      const BlockWaitOptions& options,
461
                                                      const BlockAssembler::Options& assemble_options)
462
0
{
463
    // Delay calculating the current template fees, just in case a new block
464
    // comes in before the next tick.
465
0
    CAmount current_fees = -1;
466
467
    // Alternate waiting for a new tip and checking if fees have risen.
468
    // The latter check is expensive so we only run it once per second.
469
0
    auto now{NodeClock::now()};
470
0
    const auto deadline = now + options.timeout;
471
0
    const MillisecondsDouble tick{1000};
472
0
    const bool allow_min_difficulty{chainman.GetParams().GetConsensus().fPowAllowMinDifficultyBlocks};
473
474
0
    do {
475
0
        bool tip_changed{false};
476
0
        {
477
0
            WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
478
            // Note that wait_until() checks the predicate before waiting
479
0
            kernel_notifications.m_tip_block_cv.wait_until(lock, std::min(now + tick, deadline), [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
480
0
                AssertLockHeld(kernel_notifications.m_tip_block_mutex);
481
0
                const auto tip_block{kernel_notifications.TipBlock()};
482
                // We assume tip_block is set, because this is an instance
483
                // method on BlockTemplate and no template could have been
484
                // generated before a tip exists.
485
0
                tip_changed = Assume(tip_block) && tip_block != block_template->block.hashPrevBlock;
486
0
                return tip_changed || chainman.m_interrupt;
487
0
            });
488
0
        }
489
490
0
        if (chainman.m_interrupt) return nullptr;
491
        // At this point the tip changed, a full tick went by or we reached
492
        // the deadline.
493
494
        // Must release m_tip_block_mutex before locking cs_main, to avoid deadlocks.
495
0
        LOCK(::cs_main);
496
497
        // On test networks return a minimum difficulty block after 20 minutes
498
0
        if (!tip_changed && allow_min_difficulty) {
499
0
            const NodeClock::time_point tip_time{std::chrono::seconds{chainman.ActiveChain().Tip()->GetBlockTime()}};
500
0
            if (now > tip_time + 20min) {
501
0
                tip_changed = true;
502
0
            }
503
0
        }
504
505
        /**
506
         * We determine if fees increased compared to the previous template by generating
507
         * a fresh template. There may be more efficient ways to determine how much
508
         * (approximate) fees for the next block increased, perhaps more so after
509
         * Cluster Mempool.
510
         *
511
         * We'll also create a new template if the tip changed during this iteration.
512
         */
513
0
        if (options.fee_threshold < MAX_MONEY || tip_changed) {
514
0
            auto new_tmpl{BlockAssembler{
515
0
                chainman.ActiveChainstate(),
516
0
                mempool,
517
0
                assemble_options}
518
0
                              .CreateNewBlock()};
519
520
            // If the tip changed, return the new template regardless of its fees.
521
0
            if (tip_changed) return new_tmpl;
522
523
            // Calculate the original template total fees if we haven't already
524
0
            if (current_fees == -1) {
525
0
                current_fees = 0;
526
0
                for (CAmount fee : block_template->vTxFees) {
527
0
                    current_fees += fee;
528
0
                }
529
0
            }
530
531
0
            CAmount new_fees = 0;
532
0
            for (CAmount fee : new_tmpl->vTxFees) {
533
0
                new_fees += fee;
534
0
                Assume(options.fee_threshold != MAX_MONEY);
535
0
                if (new_fees >= current_fees + options.fee_threshold) return new_tmpl;
536
0
            }
537
0
        }
538
539
0
        now = NodeClock::now();
540
0
    } while (now < deadline);
541
542
0
    return nullptr;
543
0
}
544
545
std::optional<BlockRef> GetTip(ChainstateManager& chainman)
546
0
{
547
0
    LOCK(::cs_main);
548
0
    CBlockIndex* tip{chainman.ActiveChain().Tip()};
549
0
    if (!tip) return {};
550
0
    return BlockRef{tip->GetBlockHash(), tip->nHeight};
551
0
}
552
553
std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const uint256& current_tip, MillisecondsDouble& timeout)
554
0
{
555
0
    Assume(timeout >= 0ms); // No internal callers should use a negative timeout
556
0
    if (timeout < 0ms) timeout = 0ms;
557
0
    if (timeout > std::chrono::years{100}) timeout = std::chrono::years{100}; // Upper bound to avoid UB in std::chrono
558
0
    auto deadline{std::chrono::steady_clock::now() + timeout};
559
0
    {
560
0
        WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
561
        // For callers convenience, wait longer than the provided timeout
562
        // during startup for the tip to be non-null. That way this function
563
        // always returns valid tip information when possible and only
564
        // returns null when shutting down, not when timing out.
565
0
        kernel_notifications.m_tip_block_cv.wait(lock, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
566
0
            return kernel_notifications.TipBlock() || chainman.m_interrupt;
567
0
        });
568
0
        if (chainman.m_interrupt) return {};
569
        // At this point TipBlock is set, so continue to wait until it is
570
        // different then `current_tip` provided by caller.
571
0
        kernel_notifications.m_tip_block_cv.wait_until(lock, deadline, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
572
0
            return Assume(kernel_notifications.TipBlock()) != current_tip || chainman.m_interrupt;
573
0
        });
574
0
    }
575
0
    if (chainman.m_interrupt) return {};
576
577
    // Must release m_tip_block_mutex before getTip() locks cs_main, to
578
    // avoid deadlocks.
579
0
    return GetTip(chainman);
580
0
}
581
} // namespace node