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