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