/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 <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 | | #include <numeric> |
33 | | |
34 | | namespace node { |
35 | | |
36 | | int64_t GetMinimumTime(const CBlockIndex* pindexPrev, const int64_t difficulty_adjustment_interval) |
37 | 0 | { |
38 | 0 | int64_t min_time{pindexPrev->GetMedianTimePast() + 1}; |
39 | | // Height of block to be mined. |
40 | 0 | const int height{pindexPrev->nHeight + 1}; |
41 | | // Account for BIP94 timewarp rule on all networks. This makes future |
42 | | // activation safer. |
43 | 0 | if (height % difficulty_adjustment_interval == 0) { |
44 | 0 | min_time = std::max<int64_t>(min_time, pindexPrev->GetBlockTime() - MAX_TIMEWARP); |
45 | 0 | } |
46 | 0 | return min_time; |
47 | 0 | } |
48 | | |
49 | | int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev) |
50 | 0 | { |
51 | 0 | int64_t nOldTime = pblock->nTime; |
52 | 0 | int64_t nNewTime{std::max<int64_t>(GetMinimumTime(pindexPrev, consensusParams.DifficultyAdjustmentInterval()), |
53 | 0 | TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()))}; |
54 | |
|
55 | 0 | if (nOldTime < nNewTime) { |
56 | 0 | pblock->nTime = nNewTime; |
57 | 0 | } |
58 | | |
59 | | // Updating time can change work required on testnet: |
60 | 0 | if (consensusParams.fPowAllowMinDifficultyBlocks) { |
61 | 0 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams); |
62 | 0 | } |
63 | |
|
64 | 0 | return nNewTime - nOldTime; |
65 | 0 | } |
66 | | |
67 | | void RegenerateCommitments(CBlock& block, ChainstateManager& chainman) |
68 | 0 | { |
69 | 0 | CMutableTransaction tx{*block.vtx.at(0)}; |
70 | 0 | tx.vout.erase(tx.vout.begin() + GetWitnessCommitmentIndex(block)); |
71 | 0 | block.vtx.at(0) = MakeTransactionRef(tx); |
72 | |
|
73 | 0 | const CBlockIndex* prev_block = WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock)); Line | Count | Source | 297 | 0 | #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) |
|
74 | 0 | chainman.GenerateCoinbaseCommitment(block, prev_block); |
75 | |
|
76 | 0 | block.hashMerkleRoot = BlockMerkleRoot(block); |
77 | 0 | } |
78 | | |
79 | | static BlockAssembler::Options ClampOptions(BlockAssembler::Options options) |
80 | 0 | { |
81 | | // Apply DEFAULT_BLOCK_RESERVED_WEIGHT when the caller left it unset. |
82 | 0 | options.block_reserved_weight = std::clamp<size_t>(options.block_reserved_weight.value_or(DEFAULT_BLOCK_RESERVED_WEIGHT), MINIMUM_BLOCK_RESERVED_WEIGHT, MAX_BLOCK_WEIGHT); |
83 | 0 | options.coinbase_output_max_additional_sigops = std::clamp<size_t>(options.coinbase_output_max_additional_sigops, 0, MAX_BLOCK_SIGOPS_COST); |
84 | | // Limit weight to between block_reserved_weight and MAX_BLOCK_WEIGHT for sanity: |
85 | | // block_reserved_weight can safely exceed -blockmaxweight, but the rest of the block template will be empty. |
86 | 0 | options.nBlockMaxWeight = std::clamp<size_t>(options.nBlockMaxWeight, *options.block_reserved_weight, MAX_BLOCK_WEIGHT); |
87 | 0 | return options; |
88 | 0 | } |
89 | | |
90 | | BlockAssembler::BlockAssembler(Chainstate& chainstate, const CTxMemPool* mempool, const Options& options) |
91 | 0 | : chainparams{chainstate.m_chainman.GetParams()}, |
92 | 0 | m_mempool{options.use_mempool ? mempool : nullptr}, |
93 | 0 | m_chainstate{chainstate}, |
94 | 0 | m_options{ClampOptions(options)} |
95 | 0 | { |
96 | 0 | } |
97 | | |
98 | | void ApplyArgsManOptions(const ArgsManager& args, BlockAssembler::Options& options) |
99 | 0 | { |
100 | | // Block resource limits |
101 | 0 | options.nBlockMaxWeight = args.GetIntArg("-blockmaxweight", options.nBlockMaxWeight); |
102 | 0 | if (const auto blockmintxfee{args.GetArg("-blockmintxfee")}) { |
103 | 0 | if (const auto parsed{ParseMoney(*blockmintxfee)}) options.blockMinFeeRate = CFeeRate{*parsed}; |
104 | 0 | } |
105 | 0 | options.print_modified_fee = args.GetBoolArg("-printpriority", options.print_modified_fee); |
106 | 0 | if (!options.block_reserved_weight) { |
107 | 0 | options.block_reserved_weight = args.GetIntArg("-blockreservedweight"); |
108 | 0 | } |
109 | 0 | } |
110 | | |
111 | | void BlockAssembler::resetBlock() |
112 | 0 | { |
113 | | // Reserve space for fixed-size block header, txs count, and coinbase tx. |
114 | 0 | nBlockWeight = *Assert(m_options.block_reserved_weight); Line | Count | Source | 113 | 0 | #define Assert(val) inline_assertion_check<true>(val, std::source_location::current(), #val) |
|
115 | 0 | nBlockSigOpsCost = m_options.coinbase_output_max_additional_sigops; |
116 | | |
117 | | // These counters do not include coinbase tx |
118 | 0 | nBlockTx = 0; |
119 | 0 | nFees = 0; |
120 | 0 | } |
121 | | |
122 | | std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock() |
123 | 0 | { |
124 | 0 | const auto time_start{SteadyClock::now()}; |
125 | |
|
126 | 0 | resetBlock(); |
127 | |
|
128 | 0 | pblocktemplate.reset(new CBlockTemplate()); |
129 | 0 | CBlock* const pblock = &pblocktemplate->block; // pointer for convenience |
130 | | |
131 | | // Add dummy coinbase tx as first transaction. It is skipped by the |
132 | | // getblocktemplate RPC and mining interface consumers must not use it. |
133 | 0 | pblock->vtx.emplace_back(); |
134 | |
|
135 | 0 | LOCK(::cs_main); Line | Count | Source | 266 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
136 | 0 | CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip(); |
137 | 0 | assert(pindexPrev != nullptr); |
138 | 0 | nHeight = pindexPrev->nHeight + 1; |
139 | |
|
140 | 0 | pblock->nVersion = m_chainstate.m_chainman.m_versionbitscache.ComputeBlockVersion(pindexPrev, chainparams.GetConsensus()); |
141 | | // -regtest only: allow overriding block.nVersion with |
142 | | // -blockversion=N to test forking scenarios |
143 | 0 | if (chainparams.MineBlocksOnDemand()) { |
144 | 0 | pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion); |
145 | 0 | } |
146 | |
|
147 | 0 | pblock->nTime = TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()); |
148 | 0 | m_lock_time_cutoff = pindexPrev->GetMedianTimePast(); |
149 | |
|
150 | 0 | if (m_mempool) { |
151 | 0 | LOCK(m_mempool->cs); Line | Count | Source | 266 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
152 | 0 | m_mempool->StartBlockBuilding(); |
153 | 0 | addChunks(); |
154 | 0 | m_mempool->StopBlockBuilding(); |
155 | 0 | } |
156 | |
|
157 | 0 | const auto time_1{SteadyClock::now()}; |
158 | |
|
159 | 0 | m_last_block_num_txs = nBlockTx; |
160 | 0 | m_last_block_weight = nBlockWeight; |
161 | | |
162 | | // Create coinbase transaction. |
163 | 0 | CMutableTransaction coinbaseTx; |
164 | | |
165 | | // Construct coinbase transaction struct in parallel |
166 | 0 | CoinbaseTx& coinbase_tx{pblocktemplate->m_coinbase_tx}; |
167 | 0 | coinbase_tx.version = coinbaseTx.version; |
168 | |
|
169 | 0 | coinbaseTx.vin.resize(1); |
170 | 0 | coinbaseTx.vin[0].prevout.SetNull(); |
171 | 0 | coinbaseTx.vin[0].nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; // Make sure timelock is enforced. |
172 | 0 | coinbase_tx.sequence = coinbaseTx.vin[0].nSequence; |
173 | | |
174 | | // Add an output that spends the full coinbase reward. |
175 | 0 | coinbaseTx.vout.resize(1); |
176 | 0 | coinbaseTx.vout[0].scriptPubKey = m_options.coinbase_output_script; |
177 | | // Block subsidy + fees |
178 | 0 | const CAmount block_reward{nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus())}; |
179 | 0 | coinbaseTx.vout[0].nValue = block_reward; |
180 | 0 | coinbase_tx.block_reward_remaining = block_reward; |
181 | | |
182 | | // Start the coinbase scriptSig with the block height as required by BIP34. |
183 | | // Mining clients are expected to append extra data to this prefix, so |
184 | | // increasing its length would reduce the space they can use and may break |
185 | | // existing clients. |
186 | 0 | coinbaseTx.vin[0].scriptSig = CScript() << nHeight; |
187 | 0 | if (m_options.include_dummy_extranonce) { |
188 | | // For blocks at heights <= 16, the BIP34-encoded height alone is only |
189 | | // one byte. Consensus requires coinbase scriptSigs to be at least two |
190 | | // bytes long (bad-cb-length), so tests and regtest include a dummy |
191 | | // extraNonce (OP_0) |
192 | 0 | coinbaseTx.vin[0].scriptSig << OP_0; |
193 | 0 | } |
194 | 0 | coinbase_tx.script_sig_prefix = coinbaseTx.vin[0].scriptSig; |
195 | 0 | Assert(nHeight > 0); Line | Count | Source | 113 | 0 | #define Assert(val) inline_assertion_check<true>(val, std::source_location::current(), #val) |
|
196 | 0 | coinbaseTx.nLockTime = static_cast<uint32_t>(nHeight - 1); |
197 | 0 | coinbase_tx.lock_time = coinbaseTx.nLockTime; |
198 | |
|
199 | 0 | pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx)); |
200 | 0 | m_chainstate.m_chainman.GenerateCoinbaseCommitment(*pblock, pindexPrev); |
201 | |
|
202 | 0 | const CTransactionRef& final_coinbase{pblock->vtx[0]}; |
203 | 0 | if (final_coinbase->HasWitness()) { |
204 | 0 | const auto& witness_stack{final_coinbase->vin[0].scriptWitness.stack}; |
205 | | // Consensus requires the coinbase witness stack to have exactly one |
206 | | // element of 32 bytes. |
207 | 0 | Assert(witness_stack.size() == 1 && witness_stack[0].size() == 32); Line | Count | Source | 113 | 0 | #define Assert(val) inline_assertion_check<true>(val, std::source_location::current(), #val) |
|
208 | 0 | coinbase_tx.witness = uint256(witness_stack[0]); |
209 | 0 | } |
210 | 0 | if (const int witness_index = GetWitnessCommitmentIndex(*pblock); witness_index != NO_WITNESS_COMMITMENT) { |
211 | 0 | Assert(witness_index >= 0 && static_cast<size_t>(witness_index) < final_coinbase->vout.size()); Line | Count | Source | 113 | 0 | #define Assert(val) inline_assertion_check<true>(val, std::source_location::current(), #val) |
|
212 | 0 | coinbase_tx.required_outputs.push_back(final_coinbase->vout[witness_index]); |
213 | 0 | } |
214 | |
|
215 | 0 | LogInfo("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);Line | Count | Source | 95 | 0 | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 89 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__) |
|
|
216 | | |
217 | | // Fill in header |
218 | 0 | pblock->hashPrevBlock = pindexPrev->GetBlockHash(); |
219 | 0 | UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); |
220 | 0 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus()); |
221 | 0 | pblock->nNonce = 0; |
222 | |
|
223 | 0 | if (m_options.test_block_validity) { |
224 | | // if nHeight <= 16, and include_dummy_extranonce=false this will fail due to bad-cb-length. |
225 | 0 | if (BlockValidationState state{TestBlockValidity(m_chainstate, *pblock, /*check_pow=*/false, /*check_merkle_root=*/false)}; !state.IsValid()) { |
226 | 0 | throw std::runtime_error(strprintf("TestBlockValidity failed: %s", state.ToString()));Line | Count | Source | 1172 | 0 | #define strprintf tfm::format |
|
227 | 0 | } |
228 | 0 | } |
229 | 0 | const auto time_2{SteadyClock::now()}; |
230 | |
|
231 | 0 | LogDebug(BCLog::BENCH, "CreateNewBlock() chunks: %.2fms, validity: %.2fms (total %.2fms)\n", Line | Count | Source | 115 | 0 | #define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, BCLog::Level::Debug, __VA_ARGS__) Line | Count | Source | 106 | 0 | do { \ | 107 | 0 | if (util::log::ShouldLog((category), (level))) { \ | 108 | 0 | bool rate_limit{level >= BCLog::Level::Info}; \ | 109 | 0 | Assume(!rate_limit); /*Only called with the levels below*/ \ Line | Count | Source | 125 | 0 | #define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val) |
| 110 | 0 | LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \ Line | Count | Source | 89 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__) |
| 111 | 0 | } \ | 112 | 0 | } while (0) |
|
|
232 | 0 | Ticks<MillisecondsDouble>(time_1 - time_start), |
233 | 0 | Ticks<MillisecondsDouble>(time_2 - time_1), |
234 | 0 | Ticks<MillisecondsDouble>(time_2 - time_start)); |
235 | |
|
236 | 0 | return std::move(pblocktemplate); |
237 | 0 | } |
238 | | |
239 | | bool BlockAssembler::TestChunkBlockLimits(FeePerWeight chunk_feerate, int64_t chunk_sigops_cost) const |
240 | 0 | { |
241 | 0 | if (nBlockWeight + chunk_feerate.size >= m_options.nBlockMaxWeight) { |
242 | 0 | return false; |
243 | 0 | } |
244 | 0 | if (nBlockSigOpsCost + chunk_sigops_cost >= MAX_BLOCK_SIGOPS_COST) { |
245 | 0 | return false; |
246 | 0 | } |
247 | 0 | return true; |
248 | 0 | } |
249 | | |
250 | | // Perform transaction-level checks before adding to block: |
251 | | // - transaction finality (locktime) |
252 | | bool BlockAssembler::TestChunkTransactions(const std::vector<CTxMemPoolEntryRef>& txs) const |
253 | 0 | { |
254 | 0 | for (const auto tx : txs) { |
255 | 0 | if (!IsFinalTx(tx.get().GetTx(), nHeight, m_lock_time_cutoff)) { |
256 | 0 | return false; |
257 | 0 | } |
258 | 0 | } |
259 | 0 | return true; |
260 | 0 | } |
261 | | |
262 | | void BlockAssembler::AddToBlock(const CTxMemPoolEntry& entry) |
263 | 0 | { |
264 | 0 | pblocktemplate->block.vtx.emplace_back(entry.GetSharedTx()); |
265 | 0 | pblocktemplate->vTxFees.push_back(entry.GetFee()); |
266 | 0 | pblocktemplate->vTxSigOpsCost.push_back(entry.GetSigOpCost()); |
267 | 0 | nBlockWeight += entry.GetTxWeight(); |
268 | 0 | ++nBlockTx; |
269 | 0 | nBlockSigOpsCost += entry.GetSigOpCost(); |
270 | 0 | nFees += entry.GetFee(); |
271 | |
|
272 | 0 | if (m_options.print_modified_fee) { |
273 | 0 | LogInfo("fee rate %s txid %s\n",Line | Count | Source | 95 | 0 | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 89 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__) |
|
|
274 | 0 | CFeeRate(entry.GetModifiedFee(), entry.GetTxSize()).ToString(), |
275 | 0 | entry.GetTx().GetHash().ToString()); |
276 | 0 | } |
277 | 0 | } |
278 | | |
279 | | void BlockAssembler::addChunks() |
280 | 0 | { |
281 | | // Limit the number of attempts to add transactions to the block when it is |
282 | | // close to full; this is just a simple heuristic to finish quickly if the |
283 | | // mempool has a lot of entries. |
284 | 0 | const int64_t MAX_CONSECUTIVE_FAILURES = 1000; |
285 | 0 | constexpr int32_t BLOCK_FULL_ENOUGH_WEIGHT_DELTA = 4000; |
286 | 0 | int64_t nConsecutiveFailed = 0; |
287 | |
|
288 | 0 | std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> selected_transactions; |
289 | 0 | selected_transactions.reserve(MAX_CLUSTER_COUNT_LIMIT); |
290 | 0 | FeePerWeight chunk_feerate; |
291 | | |
292 | | // This fills selected_transactions |
293 | 0 | chunk_feerate = m_mempool->GetBlockBuilderChunk(selected_transactions); |
294 | 0 | FeePerVSize chunk_feerate_vsize = ToFeePerVSize(chunk_feerate); |
295 | |
|
296 | 0 | while (selected_transactions.size() > 0) { |
297 | | // Check to see if min fee rate is still respected. |
298 | 0 | if (chunk_feerate_vsize << m_options.blockMinFeeRate.GetFeePerVSize()) { |
299 | | // Everything else we might consider has a lower feerate |
300 | 0 | return; |
301 | 0 | } |
302 | | |
303 | 0 | int64_t chunk_sig_ops = 0; |
304 | 0 | for (const auto& tx : selected_transactions) { |
305 | 0 | chunk_sig_ops += tx.get().GetSigOpCost(); |
306 | 0 | } |
307 | | |
308 | | // Check to see if this chunk will fit. |
309 | 0 | if (!TestChunkBlockLimits(chunk_feerate, chunk_sig_ops) || !TestChunkTransactions(selected_transactions)) { |
310 | | // This chunk won't fit, so we skip it and will try the next best one. |
311 | 0 | m_mempool->SkipBuilderChunk(); |
312 | 0 | ++nConsecutiveFailed; |
313 | |
|
314 | 0 | if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight + |
315 | 0 | BLOCK_FULL_ENOUGH_WEIGHT_DELTA > m_options.nBlockMaxWeight) { |
316 | | // Give up if we're close to full and haven't succeeded in a while |
317 | 0 | return; |
318 | 0 | } |
319 | 0 | } else { |
320 | 0 | m_mempool->IncludeBuilderChunk(); |
321 | | |
322 | | // This chunk will fit, so add it to the block. |
323 | 0 | nConsecutiveFailed = 0; |
324 | 0 | for (const auto& tx : selected_transactions) { |
325 | 0 | AddToBlock(tx); |
326 | 0 | } |
327 | 0 | pblocktemplate->m_package_feerates.emplace_back(chunk_feerate_vsize); |
328 | 0 | } |
329 | | |
330 | 0 | selected_transactions.clear(); |
331 | 0 | chunk_feerate = m_mempool->GetBlockBuilderChunk(selected_transactions); |
332 | 0 | chunk_feerate_vsize = ToFeePerVSize(chunk_feerate); |
333 | 0 | } |
334 | 0 | } |
335 | | |
336 | | void AddMerkleRootAndCoinbase(CBlock& block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce) |
337 | 0 | { |
338 | 0 | if (block.vtx.size() == 0) { |
339 | 0 | block.vtx.emplace_back(coinbase); |
340 | 0 | } else { |
341 | 0 | block.vtx[0] = coinbase; |
342 | 0 | } |
343 | 0 | block.nVersion = version; |
344 | 0 | block.nTime = timestamp; |
345 | 0 | block.nNonce = nonce; |
346 | 0 | block.hashMerkleRoot = BlockMerkleRoot(block); |
347 | | |
348 | | // Reset cached checks |
349 | 0 | block.m_checked_witness_commitment = false; |
350 | 0 | block.m_checked_merkle_root = false; |
351 | 0 | block.fChecked = false; |
352 | 0 | } |
353 | | |
354 | | void InterruptWait(KernelNotifications& kernel_notifications, bool& interrupt_wait) |
355 | 0 | { |
356 | 0 | LOCK(kernel_notifications.m_tip_block_mutex); Line | Count | Source | 266 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
357 | 0 | interrupt_wait = true; |
358 | 0 | kernel_notifications.m_tip_block_cv.notify_all(); |
359 | 0 | } |
360 | | |
361 | | std::unique_ptr<CBlockTemplate> WaitAndCreateNewBlock(ChainstateManager& chainman, |
362 | | KernelNotifications& kernel_notifications, |
363 | | CTxMemPool* mempool, |
364 | | const std::unique_ptr<CBlockTemplate>& block_template, |
365 | | const BlockWaitOptions& options, |
366 | | const BlockAssembler::Options& assemble_options, |
367 | | bool& interrupt_wait) |
368 | 0 | { |
369 | | // Delay calculating the current template fees, just in case a new block |
370 | | // comes in before the next tick. |
371 | 0 | CAmount current_fees = -1; |
372 | | |
373 | | // Alternate waiting for a new tip and checking if fees have risen. |
374 | | // The latter check is expensive so we only run it once per second. |
375 | 0 | auto now{NodeClock::now()}; |
376 | 0 | const auto deadline = now + options.timeout; |
377 | 0 | const MillisecondsDouble tick{1000}; |
378 | 0 | const bool allow_min_difficulty{chainman.GetParams().GetConsensus().fPowAllowMinDifficultyBlocks}; |
379 | |
|
380 | 0 | do { |
381 | 0 | bool tip_changed{false}; |
382 | 0 | { |
383 | 0 | WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock); Line | Count | Source | 272 | 0 | #define WAIT_LOCK(cs, name) UniqueLock name(LOCK_ARGS(cs)) Line | Count | Source | 270 | 0 | #define LOCK_ARGS(cs) MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__ |
|
|
384 | | // Note that wait_until() checks the predicate before waiting |
385 | 0 | kernel_notifications.m_tip_block_cv.wait_until(lock, std::min(now + tick, deadline), [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) { |
386 | 0 | AssertLockHeld(kernel_notifications.m_tip_block_mutex); Line | Count | Source | 142 | 0 | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
387 | 0 | const auto tip_block{kernel_notifications.TipBlock()}; |
388 | | // We assume tip_block is set, because this is an instance |
389 | | // method on BlockTemplate and no template could have been |
390 | | // generated before a tip exists. |
391 | 0 | tip_changed = Assume(tip_block) && tip_block != block_template->block.hashPrevBlock; Line | Count | Source | 125 | 0 | #define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val) |
|
392 | 0 | return tip_changed || chainman.m_interrupt || interrupt_wait; |
393 | 0 | }); |
394 | 0 | if (interrupt_wait) { |
395 | 0 | interrupt_wait = false; |
396 | 0 | return nullptr; |
397 | 0 | } |
398 | 0 | } |
399 | | |
400 | 0 | if (chainman.m_interrupt) return nullptr; |
401 | | // At this point the tip changed, a full tick went by or we reached |
402 | | // the deadline. |
403 | | |
404 | | // Must release m_tip_block_mutex before locking cs_main, to avoid deadlocks. |
405 | 0 | LOCK(::cs_main); Line | Count | Source | 266 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
406 | | |
407 | | // On test networks return a minimum difficulty block after 20 minutes |
408 | 0 | if (!tip_changed && allow_min_difficulty) { |
409 | 0 | const NodeClock::time_point tip_time{std::chrono::seconds{chainman.ActiveChain().Tip()->GetBlockTime()}}; |
410 | 0 | if (now > tip_time + 20min) { |
411 | 0 | tip_changed = true; |
412 | 0 | } |
413 | 0 | } |
414 | | |
415 | | /** |
416 | | * We determine if fees increased compared to the previous template by generating |
417 | | * a fresh template. There may be more efficient ways to determine how much |
418 | | * (approximate) fees for the next block increased, perhaps more so after |
419 | | * Cluster Mempool. |
420 | | * |
421 | | * We'll also create a new template if the tip changed during this iteration. |
422 | | */ |
423 | 0 | if (options.fee_threshold < MAX_MONEY || tip_changed) { |
424 | 0 | auto new_tmpl{BlockAssembler{ |
425 | 0 | chainman.ActiveChainstate(), |
426 | 0 | mempool, |
427 | 0 | assemble_options} |
428 | 0 | .CreateNewBlock()}; |
429 | | |
430 | | // If the tip changed, return the new template regardless of its fees. |
431 | 0 | if (tip_changed) return new_tmpl; |
432 | | |
433 | | // Calculate the original template total fees if we haven't already |
434 | 0 | if (current_fees == -1) { |
435 | 0 | current_fees = std::accumulate(block_template->vTxFees.begin(), block_template->vTxFees.end(), CAmount{0}); |
436 | 0 | } |
437 | | |
438 | | // Check if fees increased enough to return the new template |
439 | 0 | const CAmount new_fees = std::accumulate(new_tmpl->vTxFees.begin(), new_tmpl->vTxFees.end(), CAmount{0}); |
440 | 0 | Assume(options.fee_threshold != MAX_MONEY); Line | Count | Source | 125 | 0 | #define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val) |
|
441 | 0 | if (new_fees >= current_fees + options.fee_threshold) return new_tmpl; |
442 | 0 | } |
443 | | |
444 | 0 | now = NodeClock::now(); |
445 | 0 | } while (now < deadline); |
446 | | |
447 | 0 | return nullptr; |
448 | 0 | } |
449 | | |
450 | | std::optional<BlockRef> GetTip(ChainstateManager& chainman) |
451 | 0 | { |
452 | 0 | LOCK(::cs_main); Line | Count | Source | 266 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
453 | 0 | CBlockIndex* tip{chainman.ActiveChain().Tip()}; |
454 | 0 | if (!tip) return {}; |
455 | 0 | return BlockRef{tip->GetBlockHash(), tip->nHeight}; |
456 | 0 | } |
457 | | |
458 | | bool CooldownIfHeadersAhead(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const BlockRef& last_tip, bool& interrupt_mining) |
459 | 0 | { |
460 | 0 | uint256 last_tip_hash{last_tip.hash}; |
461 | |
|
462 | 0 | while (const std::optional<int> remaining = chainman.BlocksAheadOfTip()) { |
463 | 0 | const int cooldown_seconds = std::clamp(*remaining, 3, 20); |
464 | 0 | const auto cooldown_deadline{MockableSteadyClock::now() + std::chrono::seconds{cooldown_seconds}}; |
465 | |
|
466 | 0 | { |
467 | 0 | WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock); Line | Count | Source | 272 | 0 | #define WAIT_LOCK(cs, name) UniqueLock name(LOCK_ARGS(cs)) Line | Count | Source | 270 | 0 | #define LOCK_ARGS(cs) MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__ |
|
|
468 | 0 | kernel_notifications.m_tip_block_cv.wait_until(lock, cooldown_deadline, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) { |
469 | 0 | const auto tip_block = kernel_notifications.TipBlock(); |
470 | 0 | return chainman.m_interrupt || interrupt_mining || (tip_block && *tip_block != last_tip_hash); |
471 | 0 | }); |
472 | 0 | if (chainman.m_interrupt || interrupt_mining) { |
473 | 0 | interrupt_mining = false; |
474 | 0 | return false; |
475 | 0 | } |
476 | | |
477 | | // If the tip changed during the wait, extend the deadline |
478 | 0 | const auto tip_block = kernel_notifications.TipBlock(); |
479 | 0 | if (tip_block && *tip_block != last_tip_hash) { |
480 | 0 | last_tip_hash = *tip_block; |
481 | 0 | continue; |
482 | 0 | } |
483 | 0 | } |
484 | | |
485 | | // No tip change and the cooldown window has expired. |
486 | 0 | if (MockableSteadyClock::now() >= cooldown_deadline) break; |
487 | 0 | } |
488 | | |
489 | 0 | return true; |
490 | 0 | } |
491 | | |
492 | | std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const uint256& current_tip, MillisecondsDouble& timeout, bool& interrupt) |
493 | 0 | { |
494 | 0 | Assume(timeout >= 0ms); // No internal callers should use a negative timeout Line | Count | Source | 125 | 0 | #define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val) |
|
495 | 0 | if (timeout < 0ms) timeout = 0ms; |
496 | 0 | if (timeout > std::chrono::years{100}) timeout = std::chrono::years{100}; // Upper bound to avoid UB in std::chrono |
497 | 0 | auto deadline{std::chrono::steady_clock::now() + timeout}; |
498 | 0 | { |
499 | 0 | WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock); Line | Count | Source | 272 | 0 | #define WAIT_LOCK(cs, name) UniqueLock name(LOCK_ARGS(cs)) Line | Count | Source | 270 | 0 | #define LOCK_ARGS(cs) MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__ |
|
|
500 | | // For callers convenience, wait longer than the provided timeout |
501 | | // during startup for the tip to be non-null. That way this function |
502 | | // always returns valid tip information when possible and only |
503 | | // returns null when shutting down, not when timing out. |
504 | 0 | kernel_notifications.m_tip_block_cv.wait(lock, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) { |
505 | 0 | return kernel_notifications.TipBlock() || chainman.m_interrupt || interrupt; |
506 | 0 | }); |
507 | 0 | if (chainman.m_interrupt || interrupt) { |
508 | 0 | interrupt = false; |
509 | 0 | return {}; |
510 | 0 | } |
511 | | // At this point TipBlock is set, so continue to wait until it is |
512 | | // different then `current_tip` provided by caller. |
513 | 0 | kernel_notifications.m_tip_block_cv.wait_until(lock, deadline, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) { |
514 | 0 | return Assume(kernel_notifications.TipBlock()) != current_tip || chainman.m_interrupt || interrupt; Line | Count | Source | 125 | 0 | #define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val) |
|
515 | 0 | }); |
516 | 0 | if (chainman.m_interrupt || interrupt) { |
517 | 0 | interrupt = false; |
518 | 0 | return {}; |
519 | 0 | } |
520 | 0 | } |
521 | | |
522 | | // Must release m_tip_block_mutex before getTip() locks cs_main, to |
523 | | // avoid deadlocks. |
524 | 0 | return GetTip(chainman); |
525 | 0 | } |
526 | | |
527 | | } // namespace node |