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 : 50445 : int64_t GetMinimumTime(const CBlockIndex* pindexPrev, const int64_t difficulty_adjustment_interval)
36 : : {
37 : 50445 : int64_t min_time{pindexPrev->GetMedianTimePast() + 1};
38 : : // Height of block to be mined.
39 : 50445 : const int height{pindexPrev->nHeight + 1};
40 : : // Account for BIP94 timewarp rule on all networks. This makes future
41 : : // activation safer.
42 [ + + ]: 50445 : if (height % difficulty_adjustment_interval == 0) {
43 [ + + ]: 452 : min_time = std::max<int64_t>(min_time, pindexPrev->GetBlockTime() - MAX_TIMEWARP);
44 : : }
45 : 50445 : return min_time;
46 : : }
47 : :
48 : 48367 : int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
49 : : {
50 : 48367 : int64_t nOldTime = pblock->nTime;
51 [ + + ]: 48367 : int64_t nNewTime{std::max<int64_t>(GetMinimumTime(pindexPrev, consensusParams.DifficultyAdjustmentInterval()),
52 : 48367 : TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()))};
53 : :
54 [ + + ]: 48367 : if (nOldTime < nNewTime) {
55 : 37086 : pblock->nTime = nNewTime;
56 : : }
57 : :
58 : : // Updating time can change work required on testnet:
59 [ + + ]: 48367 : if (consensusParams.fPowAllowMinDifficultyBlocks) {
60 : 48219 : pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
61 : : }
62 : :
63 : 48367 : return nNewTime - nOldTime;
64 : : }
65 : :
66 : 6554 : void RegenerateCommitments(CBlock& block, ChainstateManager& chainman)
67 : : {
68 : 6554 : CMutableTransaction tx{*block.vtx.at(0)};
69 : 6554 : tx.vout.erase(tx.vout.begin() + GetWitnessCommitmentIndex(block));
70 [ + - + - : 13108 : block.vtx.at(0) = MakeTransactionRef(tx);
- + ]
71 : :
72 [ + - + - : 19662 : const CBlockIndex* prev_block = WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock));
+ - ]
73 [ + - ]: 6554 : chainman.GenerateCoinbaseCommitment(block, prev_block);
74 : :
75 [ + - ]: 6554 : block.hashMerkleRoot = BlockMerkleRoot(block);
76 : 6554 : }
77 : :
78 : 46279 : static BlockAssembler::Options ClampOptions(BlockAssembler::Options options)
79 : : {
80 [ + - ]: 46279 : options.block_reserved_weight = std::clamp<size_t>(options.block_reserved_weight, MINIMUM_BLOCK_RESERVED_WEIGHT, MAX_BLOCK_WEIGHT);
81 [ - + ]: 46279 : 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 [ + - ]: 46279 : options.nBlockMaxWeight = std::clamp<size_t>(options.nBlockMaxWeight, options.block_reserved_weight, MAX_BLOCK_WEIGHT);
85 : 46279 : return options;
86 : : }
87 : :
88 : 46279 : BlockAssembler::BlockAssembler(Chainstate& chainstate, const CTxMemPool* mempool, const Options& options)
89 : 46279 : : chainparams{chainstate.m_chainman.GetParams()},
90 [ + + ]: 46279 : m_mempool{options.use_mempool ? mempool : nullptr},
91 : 46279 : m_chainstate{chainstate},
92 [ + - + + ]: 46623 : m_options{ClampOptions(options)}
93 : : {
94 : 46279 : }
95 : :
96 : 38995 : void ApplyArgsManOptions(const ArgsManager& args, BlockAssembler::Options& options)
97 : : {
98 : : // Block resource limits
99 [ + - ]: 38995 : options.nBlockMaxWeight = args.GetIntArg("-blockmaxweight", options.nBlockMaxWeight);
100 [ + - + + ]: 77990 : if (const auto blockmintxfee{args.GetArg("-blockmintxfee")}) {
101 [ + - + - ]: 24 : if (const auto parsed{ParseMoney(*blockmintxfee)}) options.blockMinFeeRate = CFeeRate{*parsed};
102 : 0 : }
103 [ + - ]: 38995 : options.print_modified_fee = args.GetBoolArg("-printpriority", options.print_modified_fee);
104 [ + - ]: 38995 : options.block_reserved_weight = args.GetIntArg("-blockreservedweight", options.block_reserved_weight);
105 : 38995 : }
106 : :
107 : 46279 : void BlockAssembler::resetBlock()
108 : : {
109 : 46279 : inBlock.clear();
110 : :
111 : : // Reserve space for fixed-size block header, txs count, and coinbase tx.
112 : 46279 : nBlockWeight = m_options.block_reserved_weight;
113 : 46279 : nBlockSigOpsCost = m_options.coinbase_output_max_additional_sigops;
114 : :
115 : : // These counters do not include coinbase tx
116 : 46279 : nBlockTx = 0;
117 : 46279 : nFees = 0;
118 : 46279 : }
119 : :
120 : 46279 : std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock()
121 : : {
122 : 46279 : const auto time_start{SteadyClock::now()};
123 : :
124 : 46279 : resetBlock();
125 : :
126 [ - + ]: 46279 : pblocktemplate.reset(new CBlockTemplate());
127 : 46279 : 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 : 46279 : pblock->vtx.emplace_back();
132 : :
133 : 46279 : LOCK(::cs_main);
134 [ - + ]: 46279 : CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip();
135 [ - + ]: 46279 : assert(pindexPrev != nullptr);
136 : 46279 : nHeight = pindexPrev->nHeight + 1;
137 : :
138 [ + - ]: 46279 : 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 [ + + ]: 46279 : if (chainparams.MineBlocksOnDemand()) {
142 [ + - + - ]: 46137 : pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion);
143 : : }
144 : :
145 : 46279 : pblock->nTime = TicksSinceEpoch<std::chrono::seconds>(NodeClock::now());
146 : 46279 : m_lock_time_cutoff = pindexPrev->GetMedianTimePast();
147 : :
148 : 46279 : int nPackagesSelected = 0;
149 : 46279 : int nDescendantsUpdated = 0;
150 [ + + ]: 46279 : if (m_mempool) {
151 [ + - ]: 39723 : addPackageTxs(nPackagesSelected, nDescendantsUpdated);
152 : : }
153 : :
154 : 46279 : const auto time_1{SteadyClock::now()};
155 : :
156 [ + + ]: 46279 : m_last_block_num_txs = nBlockTx;
157 [ + + ]: 46279 : m_last_block_weight = nBlockWeight;
158 : :
159 : : // Create coinbase transaction.
160 [ + - ]: 46279 : CMutableTransaction coinbaseTx;
161 [ + - ]: 46279 : coinbaseTx.vin.resize(1);
162 : 46279 : coinbaseTx.vin[0].prevout.SetNull();
163 [ + - ]: 46279 : coinbaseTx.vin[0].nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; // Make sure timelock is enforced.
164 [ + - ]: 46279 : coinbaseTx.vout.resize(1);
165 : 46279 : coinbaseTx.vout[0].scriptPubKey = m_options.coinbase_output_script;
166 [ + - + - ]: 46279 : coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
167 [ + - + - ]: 46279 : coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
168 [ + - ]: 46279 : Assert(nHeight > 0);
169 : 46279 : coinbaseTx.nLockTime = static_cast<uint32_t>(nHeight - 1);
170 [ + - - + ]: 92558 : pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
171 [ + - ]: 46279 : pblocktemplate->vchCoinbaseCommitment = m_chainstate.m_chainman.GenerateCoinbaseCommitment(*pblock, pindexPrev);
172 : :
173 [ + - ]: 46279 : LogPrintf("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
174 : :
175 : : // Fill in header
176 : 46279 : pblock->hashPrevBlock = pindexPrev->GetBlockHash();
177 [ + - ]: 46279 : UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
178 [ + - ]: 46279 : pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
179 : 46279 : pblock->nNonce = 0;
180 : :
181 [ + - ]: 46279 : if (m_options.test_block_validity) {
182 [ + - + + ]: 46279 : if (BlockValidationState state{TestBlockValidity(m_chainstate, *pblock, /*check_pow=*/false, /*check_merkle_root=*/false)}; !state.IsValid()) {
183 [ + - + - : 10 : throw std::runtime_error(strprintf("TestBlockValidity failed: %s", state.ToString()));
+ - ]
184 : 46279 : }
185 : : }
186 : 46274 : const auto time_2{SteadyClock::now()};
187 : :
188 [ + - + - : 46274 : LogDebug(BCLog::BENCH, "CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n",
+ - ]
189 : : Ticks<MillisecondsDouble>(time_1 - time_start), nPackagesSelected, nDescendantsUpdated,
190 : : Ticks<MillisecondsDouble>(time_2 - time_1),
191 : : Ticks<MillisecondsDouble>(time_2 - time_start));
192 : :
193 : 46274 : return std::move(pblocktemplate);
194 [ + - ]: 92553 : }
195 : :
196 : 8377 : void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet)
197 : : {
198 [ + + ]: 33780 : for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
199 : : // Only test txs not already in the block
200 [ + - + - : 76209 : if (inBlock.count((*iit)->GetSharedTx()->GetHash())) {
+ - + + ]
201 : 22235 : testSet.erase(iit++);
202 : : } else {
203 : 3168 : iit++;
204 : : }
205 : : }
206 : 8377 : }
207 : :
208 : 46598 : bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
209 : : {
210 : : // TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
211 [ + + ]: 46598 : if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= m_options.nBlockMaxWeight) {
212 : : return false;
213 : : }
214 [ + + ]: 8393 : if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST) {
215 : 16 : return false;
216 : : }
217 : : return true;
218 : : }
219 : :
220 : : // Perform transaction-level checks before adding to block:
221 : : // - transaction finality (locktime)
222 : 8377 : bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package) const
223 : : {
224 [ + + ]: 19920 : for (CTxMemPool::txiter it : package) {
225 [ + + ]: 11545 : if (!IsFinalTx(it->GetTx(), nHeight, m_lock_time_cutoff)) {
226 : : return false;
227 : : }
228 : : }
229 : : return true;
230 : : }
231 : :
232 : 11543 : void BlockAssembler::AddToBlock(CTxMemPool::txiter iter)
233 : : {
234 [ + - + - ]: 23086 : pblocktemplate->block.vtx.emplace_back(iter->GetSharedTx());
235 : 11543 : pblocktemplate->vTxFees.push_back(iter->GetFee());
236 : 11543 : pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
237 [ + - ]: 11543 : nBlockWeight += iter->GetTxWeight();
238 : 11543 : ++nBlockTx;
239 [ + - ]: 11543 : nBlockSigOpsCost += iter->GetSigOpCost();
240 : 11543 : nFees += iter->GetFee();
241 [ + - + - : 23086 : inBlock.insert(iter->GetSharedTx()->GetHash());
+ - ]
242 : :
243 [ + + ]: 11543 : if (m_options.print_modified_fee) {
244 [ + - + - : 174 : LogPrintf("fee rate %s txid %s\n",
+ - + - ]
245 : : CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
246 : : iter->GetTx().GetHash().ToString());
247 : : }
248 : 11543 : }
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 : 8375 : static int UpdatePackagesForAdded(const CTxMemPool& mempool,
254 : : const CTxMemPool::setEntries& alreadyAdded,
255 : : indexed_modified_transaction_set& mapModifiedTx) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs)
256 : : {
257 : 8375 : AssertLockHeld(mempool.cs);
258 : :
259 : 8375 : int nDescendantsUpdated = 0;
260 [ + + ]: 19918 : for (CTxMemPool::txiter it : alreadyAdded) {
261 [ + - ]: 11543 : CTxMemPool::setEntries descendants;
262 [ + - ]: 11543 : mempool.CalculateDescendants(it, descendants);
263 : : // Insert all descendants (not yet in block) into the modified set
264 [ + + ]: 1045487 : for (CTxMemPool::txiter desc : descendants) {
265 [ + + ]: 1033944 : if (alreadyAdded.count(desc)) {
266 : 462876 : continue;
267 : : }
268 : 571068 : ++nDescendantsUpdated;
269 : 571068 : modtxiter mit = mapModifiedTx.find(desc);
270 [ + + ]: 571068 : if (mit == mapModifiedTx.end()) {
271 [ + - ]: 1894 : CTxMemPoolModifiedEntry modEntry(desc);
272 [ + - ]: 1894 : mit = mapModifiedTx.insert(modEntry).first;
273 : : }
274 [ + - ]: 1605012 : mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
275 : : }
276 : 11543 : }
277 : 8375 : return nDescendantsUpdated;
278 : : }
279 : :
280 : 8375 : void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, std::vector<CTxMemPool::txiter>& sortedEntries)
281 : : {
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 [ - + ]: 8375 : sortedEntries.clear();
287 : 8375 : sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
288 : 8375 : std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
289 : 8375 : }
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 : 39723 : void BlockAssembler::addPackageTxs(int& nPackagesSelected, int& nDescendantsUpdated)
302 : : {
303 : 39723 : const auto& mempool{*Assert(m_mempool)};
304 : 39723 : 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 [ + - ]: 39723 : indexed_modified_transaction_set mapModifiedTx;
309 : : // Keep track of entries that failed inclusion, to avoid duplicate work
310 : 39723 : std::set<Txid> failedTx;
311 : :
312 : 39723 : CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin();
313 : 39723 : 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 : 39723 : const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
319 : 39723 : constexpr int32_t BLOCK_FULL_ENOUGH_WEIGHT_DELTA = 4000;
320 : 39723 : int64_t nConsecutiveFailed = 0;
321 : :
322 [ + + + + ]: 90330 : 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 [ + + ]: 50664 : if (mi != mempool.mapTx.get<ancestor_score>().end()) {
337 [ - + ]: 50029 : auto it = mempool.mapTx.project<0>(mi);
338 [ - + ]: 50029 : assert(it != mempool.mapTx.end());
339 [ + + + - : 238637 : if (mapModifiedTx.count(it) || inBlock.count(it->GetSharedTx()->GetHash()) || failedTx.count(it->GetSharedTx()->GetHash())) {
+ - + + +
- + - + +
+ + ]
340 : 4020 : ++mi;
341 : 4020 : continue;
342 : : }
343 : : }
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 : 46644 : bool fUsingModified = false;
348 : :
349 : 46644 : modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
350 [ + + ]: 46644 : if (mi == mempool.mapTx.get<ancestor_score>().end()) {
351 : : // We're out of entries in mapTx; use the entry from mapModifiedTx
352 : 635 : iter = modit->iter;
353 : 635 : fUsingModified = true;
354 : : } else {
355 : : // Try to compare the mapTx entry to the mapModifiedTx entry
356 [ + + ]: 46009 : iter = mempool.mapTx.project<0>(mi);
357 [ + + + + ]: 46813 : if (modit != mapModifiedTx.get<ancestor_score>().end() &&
358 [ + - ]: 804 : 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 : 241 : iter = modit->iter;
363 : 241 : fUsingModified = true;
364 : : } else {
365 : : // Either no entry in mapModifiedTx, or it's worse than mapTx.
366 : : // Increment mi for the next loop iteration.
367 : 45768 : ++mi;
368 : : }
369 : : }
370 : :
371 : : // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
372 : : // contain anything that is inBlock.
373 [ + - + - : 93288 : assert(!inBlock.count(iter->GetSharedTx()->GetHash()));
- + ]
374 : :
375 [ + + ]: 46644 : uint64_t packageSize = iter->GetSizeWithAncestors();
376 [ + + ]: 46644 : CAmount packageFees = iter->GetModFeesWithAncestors();
377 [ + + ]: 46644 : int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
378 [ + + ]: 46644 : if (fUsingModified) {
379 : 876 : packageSize = modit->nSizeWithAncestors;
380 : 876 : packageFees = modit->nModFeesWithAncestors;
381 : 876 : packageSigOpsCost = modit->nSigOpCostWithAncestors;
382 : : }
383 : :
384 [ + - + + ]: 46644 : if (packageFees < m_options.blockMinFeeRate.GetFee(packageSize)) {
385 : : // Everything else we might consider has a lower fee rate
386 : 46 : return;
387 : : }
388 : :
389 [ + - + + ]: 46598 : if (!TestPackage(packageSize, packageSigOpsCost)) {
390 [ + + ]: 38221 : 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 : 54 : mapModifiedTx.get<ancestor_score>().erase(modit);
395 [ + - + - ]: 162 : failedTx.insert(iter->GetSharedTx()->GetHash());
396 : : }
397 : :
398 : 38221 : ++nConsecutiveFailed;
399 : :
400 [ + + ]: 38221 : if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight >
401 [ - + ]: 11 : 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 : : break;
404 : : }
405 : 38210 : continue;
406 : : }
407 : :
408 [ + - ]: 8377 : auto ancestors{mempool.AssumeCalculateMemPoolAncestors(__func__, *iter, CTxMemPool::Limits::NoLimits(), /*fSearchForParents=*/false)};
409 : :
410 [ + - ]: 8377 : onlyUnconfirmed(ancestors);
411 [ + - ]: 8377 : ancestors.insert(iter);
412 : :
413 : : // Test if all tx's are Final
414 [ + - + + ]: 8377 : if (!TestPackageTransactions(ancestors)) {
415 [ - + ]: 2 : if (fUsingModified) {
416 : 0 : mapModifiedTx.get<ancestor_score>().erase(modit);
417 [ # # # # ]: 0 : failedTx.insert(iter->GetSharedTx()->GetHash());
418 : : }
419 : 2 : continue;
420 : : }
421 : :
422 : : // This transaction will make it in; reset the failed counter.
423 : 8375 : nConsecutiveFailed = 0;
424 : :
425 : : // Package can be added. Sort the entries in a valid order.
426 : 8375 : std::vector<CTxMemPool::txiter> sortedEntries;
427 [ + - ]: 8375 : SortForBlock(ancestors, sortedEntries);
428 : :
429 [ - + + + ]: 19918 : for (size_t i = 0; i < sortedEntries.size(); ++i) {
430 [ + - ]: 11543 : AddToBlock(sortedEntries[i]);
431 : : // Erase from the modified set, if present
432 : 11543 : mapModifiedTx.erase(sortedEntries[i]);
433 : : }
434 : :
435 : 8375 : ++nPackagesSelected;
436 [ + - ]: 8375 : pblocktemplate->m_package_feerates.emplace_back(packageFees, static_cast<int32_t>(packageSize));
437 : :
438 : : // Update transactions that depend on each of these
439 [ + - ]: 8375 : nDescendantsUpdated += UpdatePackagesForAdded(mempool, ancestors, mapModifiedTx);
440 : 8377 : }
441 [ + - + - ]: 79446 : }
442 : :
443 : 55 : void AddMerkleRootAndCoinbase(CBlock& block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce)
444 : : {
445 [ - + - + ]: 55 : if (block.vtx.size() == 0) {
446 : 0 : block.vtx.emplace_back(coinbase);
447 : : } else {
448 : 55 : block.vtx[0] = coinbase;
449 : : }
450 : 55 : block.nVersion = version;
451 : 55 : block.nTime = timestamp;
452 : 55 : block.nNonce = nonce;
453 : 55 : block.hashMerkleRoot = BlockMerkleRoot(block);
454 : 55 : }
455 : :
456 : 60 : 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 : : {
463 : : // Delay calculating the current template fees, just in case a new block
464 : : // comes in before the next tick.
465 : 60 : 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 : 60 : auto now{NodeClock::now()};
470 : 60 : const auto deadline = now + options.timeout;
471 : 60 : const MillisecondsDouble tick{1000};
472 : 60 : const bool allow_min_difficulty{chainman.GetParams().GetConsensus().fPowAllowMinDifficultyBlocks};
473 : :
474 : 60 : do {
475 : 60 : bool tip_changed{false};
476 : 60 : {
477 : 60 : WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
478 : : // Note that wait_until() checks the predicate before waiting
479 [ + - ]: 60 : kernel_notifications.m_tip_block_cv.wait_until(lock, std::min(now + tick, deadline), [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
480 : 65 : AssertLockHeld(kernel_notifications.m_tip_block_mutex);
481 : 65 : 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 [ + - + + ]: 65 : tip_changed = Assume(tip_block) && tip_block != block_template->block.hashPrevBlock;
486 [ + + - + ]: 65 : return tip_changed || chainman.m_interrupt;
487 : : });
488 : 0 : }
489 : :
490 [ - + ]: 60 : 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 : 60 : LOCK(::cs_main);
496 : :
497 : : // On test networks return a minimum difficulty block after 20 minutes
498 [ + + + + ]: 60 : if (!tip_changed && allow_min_difficulty) {
499 [ + - - + ]: 6 : const NodeClock::time_point tip_time{std::chrono::seconds{chainman.ActiveChain().Tip()->GetBlockTime()}};
500 [ + + ]: 3 : if (now > tip_time + 20min) {
501 : 1 : tip_changed = true;
502 : : }
503 : : }
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 [ + + + - ]: 60 : if (options.fee_threshold < MAX_MONEY || tip_changed) {
514 : 60 : auto new_tmpl{BlockAssembler{
515 : : chainman.ActiveChainstate(),
516 : : mempool,
517 [ + - + - ]: 60 : assemble_options}
518 [ + - ]: 60 : .CreateNewBlock()};
519 : :
520 : : // If the tip changed, return the new template regardless of its fees.
521 [ + + ]: 60 : if (tip_changed) return new_tmpl;
522 : :
523 : : // Calculate the original template total fees if we haven't already
524 [ + - ]: 4 : if (current_fees == -1) {
525 : 4 : current_fees = 0;
526 [ + + ]: 10 : for (CAmount fee : block_template->vTxFees) {
527 : 6 : current_fees += fee;
528 : : }
529 : : }
530 : :
531 : 4 : CAmount new_fees = 0;
532 [ + + ]: 11 : for (CAmount fee : new_tmpl->vTxFees) {
533 : 8 : new_fees += fee;
534 : 8 : Assume(options.fee_threshold != MAX_MONEY);
535 [ + + ]: 8 : if (new_fees >= current_fees + options.fee_threshold) return new_tmpl;
536 : : }
537 [ + - ]: 60 : }
538 : :
539 [ + - ]: 3 : now = NodeClock::now();
540 [ - + ]: 60 : } while (now < deadline);
541 : :
542 : 3 : return nullptr;
543 : : }
544 : :
545 : 41605 : std::optional<BlockRef> GetTip(ChainstateManager& chainman)
546 : : {
547 : 41605 : LOCK(::cs_main);
548 [ + - - + ]: 41605 : CBlockIndex* tip{chainman.ActiveChain().Tip()};
549 [ - + ]: 41605 : if (!tip) return {};
550 : 41605 : return BlockRef{tip->GetBlockHash(), tip->nHeight};
551 : 41605 : }
552 : :
553 : 39072 : std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const uint256& current_tip, MillisecondsDouble& timeout)
554 : : {
555 : 39072 : Assume(timeout >= 0ms); // No internal callers should use a negative timeout
556 [ - + ]: 39072 : if (timeout < 0ms) timeout = 0ms;
557 [ + + ]: 39072 : if (timeout > std::chrono::years{100}) timeout = std::chrono::years{100}; // Upper bound to avoid UB in std::chrono
558 : 39072 : auto deadline{std::chrono::steady_clock::now() + timeout};
559 : 39072 : {
560 : 39072 : 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 [ + - ]: 39072 : kernel_notifications.m_tip_block_cv.wait(lock, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
566 [ - + - - ]: 39072 : return kernel_notifications.TipBlock() || chainman.m_interrupt;
567 : : });
568 [ + - - + : 39072 : 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 [ + - ]: 39072 : kernel_notifications.m_tip_block_cv.wait_until(lock, deadline, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
572 [ + + + + ]: 39092 : return Assume(kernel_notifications.TipBlock()) != current_tip || chainman.m_interrupt;
573 : : });
574 : 0 : }
575 [ + + ]: 39072 : if (chainman.m_interrupt) return {};
576 : :
577 : : // Must release m_tip_block_mutex before getTip() locks cs_main, to
578 : : // avoid deadlocks.
579 : 39071 : return GetTip(chainman);
580 : : }
581 : : } // namespace node
|