/tmp/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 <node/blockstorage.h> |
18 | | #include <node/mining_args.h> |
19 | | #include <node/mining_types.h> |
20 | | #include <policy/feerate.h> |
21 | | #include <policy/policy.h> |
22 | | #include <pow.h> |
23 | | #include <primitives/block.h> |
24 | | #include <primitives/transaction.h> |
25 | | #include <script/script.h> |
26 | | #include <sync.h> |
27 | | #include <tinyformat.h> |
28 | | #include <txgraph.h> |
29 | | #include <txmempool.h> |
30 | | #include <uint256.h> |
31 | | #include <util/check.h> |
32 | | #include <util/feefrac.h> |
33 | | #include <util/log.h> |
34 | | #include <util/result.h> |
35 | | #include <util/time.h> |
36 | | #include <util/translation.h> |
37 | | #include <validation.h> |
38 | | #include <versionbits.h> |
39 | | |
40 | | #include <algorithm> |
41 | | #include <cstddef> |
42 | | #include <functional> |
43 | | #include <span> |
44 | | #include <stdexcept> |
45 | | #include <string> |
46 | | #include <utility> |
47 | | |
48 | | namespace node { |
49 | | |
50 | | int64_t GetMinimumTime(const CBlockIndex* pindexPrev, const int64_t difficulty_adjustment_interval) |
51 | 44.2k | { |
52 | 44.2k | int64_t min_time{pindexPrev->GetMedianTimePast() + 1}; |
53 | | // Height of block to be mined. |
54 | 44.2k | const int height{pindexPrev->nHeight + 1}; |
55 | | // Account for BIP94 timewarp rule on all networks. This makes future |
56 | | // activation safer. |
57 | 44.2k | if (height % difficulty_adjustment_interval == 0) { |
58 | 202 | min_time = std::max<int64_t>(min_time, pindexPrev->GetBlockTime() - MAX_TIMEWARP); |
59 | 202 | } |
60 | | // Account for the BIP54 Murch-Zawy rule on all networks: the last block of |
61 | | // a difficulty adjustment period may not be earlier than its first block. |
62 | 44.2k | if (height % difficulty_adjustment_interval == difficulty_adjustment_interval - 1) { |
63 | 200 | const int first_height{height - static_cast<int>(difficulty_adjustment_interval) + 1}; |
64 | 200 | const CBlockIndex* first_block{Assert(pindexPrev->GetAncestor(first_height))}; |
65 | 200 | min_time = std::max<int64_t>(min_time, first_block->GetBlockTime()); |
66 | 200 | } |
67 | 44.2k | return min_time; |
68 | 44.2k | } |
69 | | |
70 | | int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev) |
71 | 44.1k | { |
72 | 44.1k | int64_t nOldTime = pblock->nTime; |
73 | 44.1k | int64_t nNewTime{std::max<int64_t>(GetMinimumTime(pindexPrev, consensusParams.DifficultyAdjustmentInterval()), |
74 | 44.1k | TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()))}; |
75 | | |
76 | 44.1k | if (nOldTime < nNewTime) { |
77 | 32.3k | pblock->nTime = nNewTime; |
78 | 32.3k | } |
79 | | |
80 | | // Updating time can change work required on testnet: |
81 | 44.1k | if (consensusParams.fPowAllowMinDifficultyBlocks) { |
82 | 44.0k | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams); |
83 | 44.0k | } |
84 | | |
85 | 44.1k | return nNewTime - nOldTime; |
86 | 44.1k | } |
87 | | |
88 | | void RegenerateCommitments(CBlock& block, ChainstateManager& chainman) |
89 | 8.81k | { |
90 | 8.81k | CMutableTransaction tx{*block.vtx.at(0)}; |
91 | 8.81k | tx.vout.erase(tx.vout.begin() + GetWitnessCommitmentIndex(block)); |
92 | 8.81k | block.vtx.at(0) = MakeTransactionRef(tx); |
93 | | |
94 | 8.81k | const CBlockIndex* prev_block = WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock)); |
95 | 8.81k | chainman.GenerateCoinbaseCommitment(block, prev_block); |
96 | | |
97 | 8.81k | block.hashMerkleRoot = BlockMerkleRoot(block); |
98 | 8.81k | } |
99 | | |
100 | | BlockAssembler::BlockAssembler(Chainstate& chainstate, |
101 | | const CTxMemPool* mempool, |
102 | | BlockCreateOptions options) |
103 | 44.0k | : chainparams{chainstate.m_chainman.GetParams()}, |
104 | 44.0k | m_mempool{options.use_mempool ? mempool : nullptr}, |
105 | 44.0k | m_chainstate{chainstate}, |
106 | 44.0k | m_options{[&] { |
107 | 44.0k | if (auto result{CheckMiningOptions(options, /*use_argnames=*/false)}; !result) { |
108 | 4 | throw std::runtime_error(util::ErrorString(result).original); |
109 | 4 | } |
110 | 44.0k | return FlattenMiningOptions(std::move(options)); |
111 | 44.0k | }()} |
112 | 44.0k | { |
113 | 44.0k | } |
114 | | |
115 | | void BlockAssembler::resetBlock() |
116 | 44.0k | { |
117 | | // Reserve space for fixed-size block header, txs count, and coinbase tx. |
118 | 44.0k | nBlockWeight = *Assert(m_options.block_reserved_weight); |
119 | 44.0k | nBlockSigOpsCost = m_options.coinbase_output_max_additional_sigops; |
120 | | |
121 | | // These counters do not include coinbase tx |
122 | 44.0k | nBlockTx = 0; |
123 | 44.0k | nFees = 0; |
124 | 44.0k | } |
125 | | |
126 | | std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock() |
127 | 44.0k | { |
128 | 44.0k | const auto time_start{SteadyClock::now()}; |
129 | | |
130 | 44.0k | resetBlock(); |
131 | | |
132 | 44.0k | pblocktemplate.reset(new CBlockTemplate()); |
133 | 44.0k | CBlock* const pblock = &pblocktemplate->block; // pointer for convenience |
134 | | |
135 | | // Add dummy coinbase tx as first transaction. It is skipped by the |
136 | | // getblocktemplate RPC and mining interface consumers must not use it. |
137 | 44.0k | pblock->vtx.emplace_back(); |
138 | | |
139 | 44.0k | LOCK(::cs_main); |
140 | 44.0k | CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip(); |
141 | 44.0k | assert(pindexPrev != nullptr); |
142 | 44.0k | nHeight = pindexPrev->nHeight + 1; |
143 | | |
144 | 44.0k | pblock->nVersion = m_chainstate.m_chainman.m_versionbitscache.ComputeBlockVersion(pindexPrev, chainparams.GetConsensus()); |
145 | | // -regtest only: allow overriding block.nVersion with |
146 | | // -blockversion=N to test forking scenarios |
147 | 44.0k | if (chainparams.MineBlocksOnDemand()) { |
148 | 43.9k | pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion); |
149 | 43.9k | } |
150 | | |
151 | 44.0k | pblock->nTime = TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()); |
152 | 44.0k | m_lock_time_cutoff = pindexPrev->GetMedianTimePast(); |
153 | | |
154 | 44.0k | if (m_mempool) { |
155 | 35.2k | LOCK(m_mempool->cs); |
156 | 35.2k | m_mempool->StartBlockBuilding(); |
157 | 35.2k | addChunks(); |
158 | 35.2k | m_mempool->StopBlockBuilding(); |
159 | 35.2k | } |
160 | | |
161 | 44.0k | const auto time_1{SteadyClock::now()}; |
162 | | |
163 | 44.0k | m_last_block_num_txs = nBlockTx; |
164 | 44.0k | m_last_block_weight = nBlockWeight; |
165 | | |
166 | | // Create coinbase transaction. |
167 | 44.0k | CMutableTransaction coinbaseTx; |
168 | | |
169 | | // Construct coinbase transaction struct in parallel |
170 | 44.0k | CoinbaseTx& coinbase_tx{pblocktemplate->m_coinbase_tx}; |
171 | 44.0k | coinbase_tx.version = coinbaseTx.version; |
172 | | |
173 | 44.0k | coinbaseTx.vin.resize(1); |
174 | 44.0k | coinbaseTx.vin[0].prevout.SetNull(); |
175 | 44.0k | coinbaseTx.vin[0].nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; // Make sure timelock is enforced. |
176 | 44.0k | coinbase_tx.sequence = coinbaseTx.vin[0].nSequence; |
177 | | |
178 | | // Add an output that spends the full coinbase reward. |
179 | 44.0k | coinbaseTx.vout.resize(1); |
180 | 44.0k | coinbaseTx.vout[0].scriptPubKey = m_options.coinbase_output_script; |
181 | | // Block subsidy + fees |
182 | 44.0k | const CAmount block_reward{nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus())}; |
183 | 44.0k | coinbaseTx.vout[0].nValue = block_reward; |
184 | 44.0k | coinbase_tx.block_reward_remaining = block_reward; |
185 | | |
186 | | // Start the coinbase scriptSig with the block height as required by BIP34. |
187 | | // Mining clients are expected to append extra data to this prefix, so |
188 | | // increasing its length would reduce the space they can use and may break |
189 | | // existing clients. |
190 | 44.0k | coinbaseTx.vin[0].scriptSig = CScript() << nHeight; |
191 | | // Set script_sig_prefix here, so IPC mining clients are not affected by |
192 | | // the optional scriptSig padding below. They provide their own extraNonce, |
193 | | // and in a typical setup a pool name or realistic extraNonce already makes |
194 | | // the scriptSig long enough. |
195 | 44.0k | coinbase_tx.script_sig_prefix = coinbaseTx.vin[0].scriptSig; |
196 | 44.0k | if (nHeight <= 16) { |
197 | | // For blocks at heights <= 16, the BIP34-encoded height alone is only |
198 | | // one byte. Consensus requires coinbase scriptSigs to be at least two |
199 | | // bytes long (bad-cb-length), so an OP_0 is always appended at those |
200 | | // heights. |
201 | 2.94k | coinbaseTx.vin[0].scriptSig << OP_0; |
202 | 2.94k | } |
203 | 44.0k | Assert(nHeight > 0); |
204 | 44.0k | coinbaseTx.nLockTime = static_cast<uint32_t>(nHeight - 1); |
205 | 44.0k | coinbase_tx.lock_time = coinbaseTx.nLockTime; |
206 | | |
207 | 44.0k | pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx)); |
208 | 44.0k | m_chainstate.m_chainman.GenerateCoinbaseCommitment(*pblock, pindexPrev); |
209 | | |
210 | 44.0k | const CTransactionRef& final_coinbase{pblock->vtx[0]}; |
211 | 44.0k | if (final_coinbase->HasWitness()) { |
212 | 43.3k | const auto& witness_stack{final_coinbase->vin[0].scriptWitness.stack}; |
213 | | // Consensus requires the coinbase witness stack to have exactly one |
214 | | // element of 32 bytes. |
215 | 43.3k | Assert(witness_stack.size() == 1 && witness_stack[0].size() == 32); |
216 | 43.3k | coinbase_tx.witness = uint256(witness_stack[0]); |
217 | 43.3k | } |
218 | 44.0k | if (const int witness_index = GetWitnessCommitmentIndex(*pblock); witness_index != NO_WITNESS_COMMITMENT) { |
219 | 44.0k | Assert(witness_index >= 0 && static_cast<size_t>(witness_index) < final_coinbase->vout.size()); |
220 | 44.0k | coinbase_tx.required_outputs.push_back(final_coinbase->vout[witness_index]); |
221 | 44.0k | } |
222 | | |
223 | 44.0k | LogDebug(BCLog::MINING, "CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost); |
224 | | |
225 | | // Fill in header |
226 | 44.0k | pblock->hashPrevBlock = pindexPrev->GetBlockHash(); |
227 | 44.0k | UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); |
228 | 44.0k | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus()); |
229 | 44.0k | pblock->nNonce = 0; |
230 | | |
231 | 44.0k | if (m_options.test_block_validity) { |
232 | 43.6k | if (BlockValidationState state{TestBlockValidity(m_chainstate, *pblock, /*check_pow=*/false, /*check_merkle_root=*/false)}; !state.IsValid()) { |
233 | 5 | throw std::runtime_error(strprintf("TestBlockValidity failed: %s", state.ToString())); |
234 | 5 | } |
235 | 43.6k | } |
236 | 44.0k | const auto time_2{SteadyClock::now()}; |
237 | | |
238 | 44.0k | LogDebug(BCLog::BENCH, "CreateNewBlock() chunks: %.2fms, validity: %.2fms (total %.2fms)\n", |
239 | 44.0k | Ticks<MillisecondsDouble>(time_1 - time_start), |
240 | 44.0k | Ticks<MillisecondsDouble>(time_2 - time_1), |
241 | 44.0k | Ticks<MillisecondsDouble>(time_2 - time_start)); |
242 | | |
243 | 44.0k | return std::move(pblocktemplate); |
244 | 44.0k | } |
245 | | |
246 | | bool BlockAssembler::TestChunkBlockLimits(int64_t chunk_weight, int64_t chunk_sigops_cost) const |
247 | 91.1k | { |
248 | | // block_max_weight has been flattened before block assembly limit checks. |
249 | 91.1k | Assert(m_options.block_max_weight); |
250 | 91.1k | if (nBlockWeight + chunk_weight >= m_options.block_max_weight) { |
251 | 39.9k | return false; |
252 | 39.9k | } |
253 | 51.1k | if (nBlockSigOpsCost + chunk_sigops_cost >= MAX_BLOCK_SIGOPS_COST) { |
254 | 2 | return false; |
255 | 2 | } |
256 | 51.1k | return true; |
257 | 51.1k | } |
258 | | |
259 | | // Perform transaction-level checks before adding to block: |
260 | | // - transaction finality (locktime) |
261 | | bool BlockAssembler::TestChunkTransactions(const std::vector<CTxMemPoolEntryRef>& txs) const |
262 | 51.1k | { |
263 | 52.5k | for (const auto tx : txs) { |
264 | 52.5k | if (!IsFinalTx(tx.get().GetTx(), nHeight, m_lock_time_cutoff)) { |
265 | 2 | return false; |
266 | 2 | } |
267 | 52.5k | } |
268 | 51.1k | return true; |
269 | 51.1k | } |
270 | | |
271 | | void BlockAssembler::AddToBlock(const CTxMemPoolEntry& entry) |
272 | 52.5k | { |
273 | 52.5k | pblocktemplate->block.vtx.emplace_back(entry.GetSharedTx()); |
274 | 52.5k | pblocktemplate->vTxFees.push_back(entry.GetFee()); |
275 | 52.5k | pblocktemplate->vTxSigOpsCost.push_back(entry.GetSigOpCost()); |
276 | 52.5k | nBlockWeight += entry.GetTxWeight(); |
277 | 52.5k | ++nBlockTx; |
278 | 52.5k | nBlockSigOpsCost += entry.GetSigOpCost(); |
279 | 52.5k | nFees += entry.GetFee(); |
280 | | |
281 | 52.5k | if (*m_options.print_modified_fee) { |
282 | 88 | LogInfo("fee rate %s txid %s\n", |
283 | 88 | CFeeRate(entry.GetModifiedFee(), entry.GetTxSize()).ToString(), |
284 | 88 | entry.GetTx().GetHash().ToString()); |
285 | 88 | } |
286 | 52.5k | } |
287 | | |
288 | | void BlockAssembler::addChunks() |
289 | 35.2k | { |
290 | | // Limit the number of attempts to add transactions to the block when it is |
291 | | // close to full; this is just a simple heuristic to finish quickly if the |
292 | | // mempool has a lot of entries. |
293 | 35.2k | const int64_t MAX_CONSECUTIVE_FAILURES = 1000; |
294 | 35.2k | constexpr int32_t BLOCK_FULL_ENOUGH_WEIGHT_DELTA = 4000; |
295 | 35.2k | int64_t nConsecutiveFailed = 0; |
296 | | |
297 | 35.2k | std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> selected_transactions; |
298 | 35.2k | selected_transactions.reserve(MAX_CLUSTER_COUNT_LIMIT); |
299 | 35.2k | FeePerWeight chunk_feerate; |
300 | | |
301 | | // This fills selected_transactions |
302 | 35.2k | chunk_feerate = m_mempool->GetBlockBuilderChunk(selected_transactions); |
303 | 35.2k | FeePerVSize chunk_feerate_vsize = ToFeePerVSize(chunk_feerate); |
304 | | |
305 | 126k | while (selected_transactions.size() > 0) { |
306 | | // Check to see if min fee rate is still respected. |
307 | 91.2k | if (ByRatio{chunk_feerate_vsize} < ByRatio{m_options.block_min_fee_rate->GetFeePerVSize()}) { |
308 | | // Everything else we might consider has a lower feerate |
309 | 48 | return; |
310 | 48 | } |
311 | | |
312 | 91.1k | int64_t chunk_sig_ops = 0; |
313 | 91.1k | int64_t chunk_weight = 0; |
314 | 94.6k | for (const auto& tx : selected_transactions) { |
315 | 94.6k | chunk_sig_ops += tx.get().GetSigOpCost(); |
316 | 94.6k | chunk_weight += tx.get().GetTxWeight(); |
317 | 94.6k | } |
318 | | |
319 | | // Check to see if this chunk will fit. |
320 | 91.1k | if (!TestChunkBlockLimits(chunk_weight, chunk_sig_ops) || !TestChunkTransactions(selected_transactions)) { |
321 | | // This chunk won't fit, so we skip it and will try the next best one. |
322 | 39.9k | m_mempool->SkipBuilderChunk(); |
323 | 39.9k | ++nConsecutiveFailed; |
324 | | |
325 | | // block_max_weight has been flattened before block assembly limit checks. |
326 | 39.9k | Assert(m_options.block_max_weight); |
327 | 39.9k | if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight + |
328 | 15 | BLOCK_FULL_ENOUGH_WEIGHT_DELTA > *m_options.block_max_weight) { |
329 | | // Give up if we're close to full and haven't succeeded in a while |
330 | 15 | return; |
331 | 15 | } |
332 | 51.1k | } else { |
333 | 51.1k | m_mempool->IncludeBuilderChunk(); |
334 | | |
335 | | // This chunk will fit, so add it to the block. |
336 | 51.1k | nConsecutiveFailed = 0; |
337 | 52.5k | for (const auto& tx : selected_transactions) { |
338 | 52.5k | AddToBlock(tx); |
339 | 52.5k | } |
340 | 51.1k | pblocktemplate->m_package_feerates.emplace_back(chunk_feerate_vsize); |
341 | 51.1k | } |
342 | | |
343 | 91.1k | selected_transactions.clear(); |
344 | 91.1k | chunk_feerate = m_mempool->GetBlockBuilderChunk(selected_transactions); |
345 | 91.1k | chunk_feerate_vsize = ToFeePerVSize(chunk_feerate); |
346 | 91.1k | } |
347 | 35.2k | } |
348 | | |
349 | | void AddMerkleRootAndCoinbase(CBlock& block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce) |
350 | 77 | { |
351 | 77 | if (block.vtx.size() == 0) { |
352 | 0 | block.vtx.emplace_back(coinbase); |
353 | 77 | } else { |
354 | 77 | block.vtx[0] = coinbase; |
355 | 77 | } |
356 | 77 | block.nVersion = version; |
357 | 77 | block.nTime = timestamp; |
358 | 77 | block.nNonce = nonce; |
359 | 77 | block.hashMerkleRoot = BlockMerkleRoot(block); |
360 | | |
361 | | // Reset cached checks |
362 | 77 | block.m_checked_witness_commitment = false; |
363 | 77 | block.m_checked_merkle_root = false; |
364 | 77 | block.fChecked = false; |
365 | 77 | } |
366 | | |
367 | | } // namespace node |