Bitcoin ABC 0.26.3
P2P Digital Currency
Loading...
Searching...
No Matches
miner.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2019 The Bitcoin Core developers
3// Copyright (c) 2020-2021 The Bitcoin developers
4// Distributed under the MIT software license, see the accompanying
5// file COPYING or http://www.opensource.org/licenses/mit-license.php.
6
7#include <node/miner.h>
8
10#include <avalanche/processor.h>
11#include <chain.h>
12#include <chainparams.h>
13#include <coins.h>
14#include <common/args.h>
15#include <config.h>
17#include <consensus/consensus.h>
18#include <consensus/merkle.h>
19#include <consensus/tx_verify.h>
21#include <minerfund.h>
23#include <policy/policy.h>
24#include <policy/settings.h>
25#include <pow/pow.h>
27#include <timedata.h>
28#include <util/moneystr.h>
29#include <validation.h>
30#include <versionbits.h>
31
32#include <algorithm>
33#include <queue>
34#include <unordered_map>
35#include <utility>
36
37namespace node {
40 int64_t nOldTime = pblock->nTime;
42 std::max<int64_t>(pindexPrev->GetMedianTimePast() + 1, adjustedTime)};
43
44 if (nOldTime < nNewTime) {
45 pblock->nTime = nNewTime;
46 }
47
48 // Updating time can change work required on testnet:
50 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainParams);
51 }
52
53 return nNewTime - nOldTime;
54}
55
57 : nExcessiveBlockSize(DEFAULT_MAX_BLOCK_SIZE),
58 nMaxGeneratedBlockSize(DEFAULT_MAX_GENERATED_BLOCK_SIZE),
59 blockMinFeeRate(DEFAULT_BLOCK_MIN_TX_FEE_PER_KB) {}
60
62 const CTxMemPool *mempool,
63 const Options &options,
65 : chainParams(chainstate.m_chainman.GetParams()), m_mempool(mempool),
68 gArgs.GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY)) {
70 // Limit size to between 1K and options.nExcessiveBlockSize -1K for sanity:
71 nMaxGeneratedBlockSize = std::max<uint64_t>(
72 1000, std::min<uint64_t>(options.nExcessiveBlockSize - 1000,
73 options.nMaxGeneratedBlockSize));
74 // Calculate the max consensus sigchecks for this block.
76 // Allow the full amount of signature check operations in lieu of a separate
77 // config option. (We are mining relayed transactions with validity cached
78 // by everyone else, and so the block will propagate quickly, regardless of
79 // how many sigchecks it contains.)
81}
82
84 // Block resource limits
85 // If -blockmaxsize is not given, limit to DEFAULT_MAX_GENERATED_BLOCK_SIZE
86 // If only one is given, only restrict the specified resource.
87 // If both are given, restrict both.
89
90 options.nExcessiveBlockSize = config.GetMaxBlockSize();
91
92 if (gArgs.IsArgSet("-blockmaxsize")) {
95 }
96
97 Amount n = Amount::zero();
98 if (gArgs.IsArgSet("-blockmintxfee") &&
99 ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n)) {
100 options.blockMinFeeRate = CFeeRate(n);
101 }
102
103 return options;
104}
105
110
112 // Reserve space for coinbase tx.
113 nBlockSize = 1000;
114 nBlockSigChecks = 100;
115
116 // These counters do not include coinbase tx.
117 nBlockTx = 0;
119}
120
121std::optional<int64_t> BlockAssembler::m_last_block_num_txs{std::nullopt};
122std::optional<int64_t> BlockAssembler::m_last_block_size{std::nullopt};
123
124std::unique_ptr<CBlockTemplate>
127
128 resetBlock();
129
130 pblocktemplate.reset(new CBlockTemplate());
131 if (!pblocktemplate.get()) {
132 return nullptr;
133 }
134
135 // Pointer for convenience.
136 CBlock *const pblock = &pblocktemplate->block;
137
138 // Add dummy coinbase tx as first transaction. It is updated at the end.
139 pblocktemplate->entries.emplace_back(CTransactionRef(), -SATOSHI, -1);
140
143 assert(pindexPrev != nullptr);
144 nHeight = pindexPrev->nHeight + 1;
145
147
149 // -regtest only: allow overriding block.nVersion with
150 // -blockversion=N to test forking scenarios
152 pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion);
153 }
154
156 m_lock_time_cutoff = pindexPrev->GetMedianTimePast();
157
158 if (m_mempool) {
159 LOCK(m_mempool->cs);
161 }
162
164 // If magnetic anomaly is enabled, we make sure transaction are
165 // canonically ordered.
166 std::sort(std::begin(pblocktemplate->entries) + 1,
167 std::end(pblocktemplate->entries),
168 [](const CBlockTemplateEntry &a, const CBlockTemplateEntry &b)
169 -> bool { return a.tx->GetId() < b.tx->GetId(); });
170 }
171
172 // Copy all the transactions refs into the block
173 pblock->vtx.reserve(pblocktemplate->entries.size());
174 for (const CBlockTemplateEntry &entry : pblocktemplate->entries) {
175 pblock->vtx.push_back(entry.tx);
176 }
177
179
182
183 // Create coinbase transaction.
185 coinbaseTx.vin.resize(1);
186 coinbaseTx.vin[0].prevout = COutPoint();
187 coinbaseTx.vout.resize(1);
188 coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
189 coinbaseTx.vout[0].nValue =
191 coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
192
193 const Amount blockReward = coinbaseTx.vout[0].nValue;
194
196 if (!whitelisted.empty()) {
197 const Amount fund =
199 coinbaseTx.vout[0].nValue -= fund;
200 coinbaseTx.vout.emplace_back(
202 }
203
204 std::vector<CScript> stakingRewardsPayoutScripts;
209 coinbaseTx.vout[0].nValue -= stakingRewards;
210 coinbaseTx.vout.emplace_back(stakingRewards,
212 }
213
214 // Make sure the coinbase is big enough.
217 coinbaseTx.vin[0].scriptSig
218 << std::vector<uint8_t>(MIN_TX_SIZE - coinbaseSize - 1);
219 }
220
222 pblocktemplate->entries[0].fees = -1 * nFees;
223 pblock->vtx[0] = pblocktemplate->entries[0].tx;
224
226
227 LogPrintf(
228 "CreateNewBlock(): total size: %u txs: %u fees: %ld sigChecks %d\n",
230
231 // Fill in header.
232 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
236 pblock->nNonce = 0;
237 pblocktemplate->entries[0].sigChecks = 0;
238
243 .withCheckPoW(false)
244 .withCheckMerkleRoot(false))) {
245 throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s",
246 __func__, state.ToString()));
247 }
249
250 LogPrint(
252 "CreateNewBlock() addTxs: %.2fms, validity: %.2fms (total %.2fms)\n",
253 0.001 * (nTime1 - nTimeStart), 0.001 * (nTime2 - nTime1),
254 0.001 * (nTime2 - nTimeStart));
255
256 return std::move(pblocktemplate);
257}
258
261 return false;
262 }
263
265 return false;
266 }
267
268 return true;
269}
270
272 pblocktemplate->entries.emplace_back(entry->GetSharedTx(), entry->GetFee(),
273 entry->GetSigChecks());
274 nBlockSize += entry->GetTxSize();
275 ++nBlockTx;
276 nBlockSigChecks += entry->GetSigChecks();
277 nFees += entry->GetFee();
278
279 if (fPrintPriority) {
280 LogPrintf(
281 "fee rate %s txid %s\n",
282 CFeeRate(entry->GetModifiedFee(), entry->GetTxSize()).ToString(),
283 entry->GetTx().GetId().ToString());
284 }
285}
286
287bool BlockAssembler::CheckTx(const CTransaction &tx) const {
288 TxValidationState state;
291}
292
298void BlockAssembler::addTxs(const CTxMemPool &mempool) {
299 // mapped_value is the number of mempool parents that are still needed for
300 // the entry. We decrement this count each time we add a parent of the entry
301 // to the block.
302 std::unordered_map<CTxMemPoolEntryRef, size_t> missingParentCount;
303 missingParentCount.reserve(mempool.size() / 2);
304
305 // set of children we skipped because we have not yet added their parents
306 std::unordered_set<CTxMemPoolEntryRef> skippedChildren;
307
308 auto hasMissingParents =
311 // If we've added any of this tx's parents already, then
312 // missingParentCount will have the current count
313 if (auto pcIt = missingParentCount.find(entry);
314 pcIt != missingParentCount.end()) {
315 // when pcIt->second reaches 0, we have added all of this
316 // tx's parents
317 return pcIt->second != 0;
318 }
319 return !entry->GetMemPoolParentsConst().empty();
320 };
321
322 // Limit the number of attempts to add transactions to the block when it is
323 // close to full; this is just a simple heuristic to finish quickly if the
324 // mempool has a lot of entries.
327
328 // Transactions where a parent has been added and need to be checked for
329 // inclusion.
330 std::queue<CTxMemPoolEntryRef> backlog;
331 auto mi = mempool.mapTx.get<modified_feerate>().begin();
332
333 auto nextEntry = [&backlog, &mi](bool &isFromBacklog) {
334 if (backlog.empty()) {
335 return *mi++;
336 }
337
338 auto &entry = backlog.front();
339 backlog.pop();
340
341 isFromBacklog = true;
342
343 return entry;
344 };
345
346 while (!backlog.empty() ||
347 mi != mempool.mapTx.get<modified_feerate>().end()) {
348 // Get a new or old transaction in mapTx to evaluate.
349 bool isFromBacklog = false;
351
352 if (entry->GetModifiedFeeRate() < blockMinFeeRate) {
353 // Since the txs are sorted by fee, bail early if there is none that
354 // can be included in the block anymore.
355 break;
356 }
357
358 // Check whether all of this tx's parents are already in the block. If
359 // not, pass on it until later.
360 //
361 // If it's from the backlog, then we know all parents are already in
362 // the block.
363 if (!isFromBacklog && hasMissingParents(entry)) {
364 skippedChildren.insert(entry);
365 continue;
366 }
367
368 // Check whether the tx will exceed the block limits.
369 if (!TestTxFits(entry->GetTxSize(), entry->GetSigChecks())) {
373 // Give up if we're close to full and haven't succeeded in a
374 // while.
375 break;
376 }
377 continue;
378 }
379
380 // Test transaction finality (locktime)
381 if (!CheckTx(entry->GetTx())) {
382 continue;
383 }
384
385 // This transaction will make it in; reset the failed counter.
387
388 // Tx can be added.
389 AddToBlock(entry);
390
391 // This tx's children may now be candidates for addition if they have
392 // higher scores than the tx at the cursor. We can only process a
393 // child once all of that tx's parents have been added, though. To
394 // avoid O(n^2) checking of dependencies, we store and decrement the
395 // number of mempool parents for each child. Although this code
396 // ends up taking O(n) time to process a single tx with n children,
397 // that's okay because the amount of time taken is proportional to the
398 // tx's byte size and fee paid.
399 for (const auto &child : entry->GetMemPoolChildrenConst()) {
400 // Remember this tx has missing parents.
401 // Create the map entry if it doesn't exist already, and init with
402 // the number of parents.
403 const auto &[parentCount, _] = missingParentCount.try_emplace(
404 child, child.get()->GetMemPoolParentsConst().size());
405 // We just added one parent, so decrement the counter and check if
406 // we have any missing parent remaining.
407 const bool allParentsAdded = --parentCount->second == 0;
408
409 // If all parents have been added to the block, and if this child
410 // has been previously skipped due to missing parents, enqueue it
411 // (if it hasn't been skipped it will come up in a later iteration)
412 if (allParentsAdded && skippedChildren.count(child) > 0) {
413 backlog.push(child);
414 }
415 }
416 }
417}
418} // namespace node
bool IsMagneticAnomalyEnabled(const Consensus::Params &params, int32_t nHeight)
Check if Nov 15, 2018 HF has activated using block height.
static constexpr Amount SATOSHI
Definition amount.h:143
ArgsManager gArgs
Definition args.cpp:38
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition args.cpp:381
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition args.cpp:526
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition args.cpp:494
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition block.h:23
Definition block.h:60
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition blockindex.h:25
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition chain.h:150
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition chainparams.h:80
const Consensus::Params & GetConsensus() const
Definition chainparams.h:92
bool MineBlocksOnDemand() const
Whether it is possible to mine blocks on demand (no retargeting)
Fee rate in satoshis per kilobyte: Amount / kB.
Definition feerate.h:21
std::string ToString() const
Definition feerate.cpp:57
A mutable version of CTransaction.
std::vector< CTxIn > vin
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition txmempool.h:212
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition txmempool.h:307
CTransactionRef get(const TxId &txid) const
unsigned long size() const
Definition txmempool.h:488
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition validation.h:699
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition validation.h:808
virtual uint64_t GetMaxBlockSize() const =0
Definition rcu.h:85
std::string ToString() const
Definition validation.h:125
bool getStakingRewardWinners(const BlockHash &prevBlockHash, std::vector< std::pair< ProofId, CScript > > &winners) const EXCLUSIVE_LOCKS_REQUIRED(!cs_stakingRewards)
Generate a new block, without valid proof-of-work.
Definition miner.h:53
Chainstate & m_chainstate
Definition miner.h:75
uint64_t nMaxGeneratedBlockSize
Definition miner.h:59
void resetBlock()
Clear the block's state and prepare for assembling a new block.
Definition miner.cpp:111
const CTxMemPool *const m_mempool
Definition miner.h:74
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn)
Construct a new block template with coinbase to scriptPubKeyIn.
Definition miner.cpp:125
CFeeRate blockMinFeeRate
Definition miner.h:61
const bool fPrintPriority
Definition miner.h:78
uint64_t nBlockTx
Definition miner.h:65
const CChainParams & chainParams
Definition miner.h:72
int64_t m_lock_time_cutoff
Definition miner.h:71
static std::optional< int64_t > m_last_block_size
Definition miner.h:102
std::unique_ptr< CBlockTemplate > pblocktemplate
Definition miner.h:56
bool CheckTx(const CTransaction &tx) const
Check the transaction for finality, etc before adding to block.
Definition miner.cpp:287
static std::optional< int64_t > m_last_block_num_txs
Definition miner.h:101
void AddToBlock(const CTxMemPoolEntryRef &entry)
Add a tx to the block.
Definition miner.cpp:271
void addTxs(const CTxMemPool &mempool) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs)
Add transactions from the mempool based on individual tx feerate.
Definition miner.cpp:298
uint64_t nBlockSigChecks
Definition miner.h:66
BlockAssembler(const Config &config, Chainstate &chainstate, const CTxMemPool *mempool, const avalanche::Processor *avalanche=nullptr)
Definition miner.cpp:106
uint64_t nBlockSize
Definition miner.h:64
bool TestTxFits(uint64_t txSize, int64_t txSigChecks) const
Test if a new Tx would "fit" in the block.
Definition miner.cpp:259
uint64_t nMaxGeneratedBlockSigChecks
Definition miner.h:60
const avalanche::Processor *const m_avalanche
Definition miner.h:76
static const uint64_t MIN_TX_SIZE
The minimum allowed size for a transaction, in bytes.
Definition consensus.h:16
static const uint64_t DEFAULT_MAX_BLOCK_SIZE
Default setting for maximum allowed size for a block, in bytes.
Definition consensus.h:20
uint64_t GetMaxBlockSigChecksCount(uint64_t maxBlockSize)
Compute the maximum number of sigchecks that can be contained in a block given the MAXIMUM block size...
Definition consensus.h:47
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition cs_main.cpp:7
#define LogPrint(category,...)
Definition logging.h:211
#define LogPrintf(...)
Definition logging.h:207
std::unordered_set< CTxDestination, TxDestinationHasher > GetMinerFundWhitelist(const Consensus::Params &params)
Definition minerfund.cpp:51
Amount GetMinerFundAmount(const Consensus::Params &params, const Amount &coinbaseValue, const CBlockIndex *pprev)
Definition minerfund.cpp:22
bool ParseMoney(const std::string &money_string, Amount &nRet)
Parse an amount denoted in full coins.
Definition moneystr.cpp:37
@ BENCH
Definition logging.h:44
Definition init.h:28
static const bool DEFAULT_PRINTPRIORITY
Definition miner.h:35
int64_t UpdateTime(CBlockHeader *pblock, const CChainParams &chainParams, const CBlockIndex *pindexPrev, int64_t adjustedTime)
Definition miner.cpp:38
static BlockAssembler::Options DefaultOptions(const Config &config)
Definition miner.cpp:83
static constexpr uint64_t DEFAULT_MAX_GENERATED_BLOCK_SIZE
Default for -blockmaxsize, which controls the maximum size of block the mining code will create.
Definition policy.h:25
static constexpr Amount DEFAULT_BLOCK_MIN_TX_FEE_PER_KB(1000 *SATOSHI)
Default for -blockmintxfee, which sets the minimum feerate for a transaction in blocks created by min...
uint32_t GetNextWorkRequired(const CBlockIndex *pindexPrev, const CBlockHeader *pblock, const CChainParams &chainParams)
Definition pow.cpp:21
static CTransactionRef MakeTransactionRef()
std::shared_ptr< const CTransaction > CTransactionRef
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
Definition random.h:85
@ OP_0
Definition script.h:49
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition serialize.h:1258
bool IsStakingRewardsActivated(const Consensus::Params &params, const CBlockIndex *pprev)
Amount GetStakingRewardsAmount(const Amount &coinbaseValue)
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition standard.cpp:240
static constexpr Amount zero() noexcept
Definition amount.h:32
Parameters that influence chain consensus.
Definition params.h:34
bool fPowAllowMinDifficultyBlocks
Definition params.h:77
uint64_t nMaxGeneratedBlockSize
Definition miner.h:84
Definition miner.h:37
#define LOCK(cs)
Definition sync.h:306
#define EXCLUSIVE_LOCKS_REQUIRED(...)
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition time.cpp:105
NodeClock::time_point GetAdjustedTime()
Definition timedata.cpp:35
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
bilingual_str _(const char *psz)
Translation function.
Definition translation.h:68
bool ContextualCheckTransaction(const Consensus::Params &params, const CTransaction &tx, TxValidationState &state, int nHeight, int64_t nMedianTimePast)
Context dependent validity checks for non coinbase transactions.
Definition tx_verify.cpp:41
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
assert(!tx.IsCoinBase())
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex &active_chain_tip, const Consensus::Params &params, const CTransaction &tx, TxValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(bool TestBlockValidity(BlockValidationState &state, const CChainParams &params, Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev, const std::function< NodeClock::time_point()> &adjusted_time_callback, BlockValidationOptions validationOptions) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
This is a variant of ContextualCheckTransaction which computes the contextual check for a transaction...
Definition validation.h:593
static const int PROTOCOL_VERSION
network protocol versioning
Definition version.h:11
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Determine what nVersion a new block should use.