Bitcoin ABC 0.31.1
P2P Digital Currency
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
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 {
38int64_t UpdateTime(CBlockHeader *pblock, const CChainParams &chainParams,
39 const CBlockIndex *pindexPrev, int64_t adjustedTime) {
40 int64_t nOldTime = pblock->nTime;
41 int64_t nNewTime{
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 Chainstate &chainstate,
58 const CTxMemPool *mempool,
60 : blockFitter(fitter), chainParams(chainstate.m_chainman.GetParams()),
61 m_mempool(mempool), m_chainstate(chainstate), m_avalanche(avalanche),
62 fPrintPriority(
63 gArgs.GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY)) {}
64
66 const CTxMemPool *mempool,
68 : BlockAssembler(BlockFitter(config), chainstate, mempool, avalanche) {}
69
70std::optional<int64_t> BlockAssembler::m_last_block_num_txs{std::nullopt};
71std::optional<int64_t> BlockAssembler::m_last_block_size{std::nullopt};
72
73std::unique_ptr<CBlockTemplate>
74BlockAssembler::CreateNewBlock(const CScript &scriptPubKeyIn) {
75 int64_t nTimeStart = GetTimeMicros();
76
78
79 pblocktemplate.reset(new CBlockTemplate());
80 if (!pblocktemplate.get()) {
81 return nullptr;
82 }
83
84 // Pointer for convenience.
85 CBlock *const pblock = &pblocktemplate->block;
86
87 // Add dummy coinbase tx as first transaction. It is updated at the end.
88 pblocktemplate->entries.emplace_back(CTransactionRef(), -SATOSHI, -1);
89
91 CBlockIndex *pindexPrev = m_chainstate.m_chain.Tip();
92 assert(pindexPrev != nullptr);
93 nHeight = pindexPrev->nHeight + 1;
94
95 const Consensus::Params &consensusParams = chainParams.GetConsensus();
96
97 pblock->nVersion = ComputeBlockVersion(pindexPrev, consensusParams);
98 // -regtest only: allow overriding block.nVersion with
99 // -blockversion=N to test forking scenarios
101 pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion);
102 }
103
104 pblock->nTime = TicksSinceEpoch<std::chrono::seconds>(GetAdjustedTime());
106
107 if (m_mempool) {
108 LOCK(m_mempool->cs);
110 }
111
112 if (IsMagneticAnomalyEnabled(consensusParams, pindexPrev)) {
113 // If magnetic anomaly is enabled, we make sure transaction are
114 // canonically ordered.
115 std::sort(std::begin(pblocktemplate->entries) + 1,
116 std::end(pblocktemplate->entries),
117 [](const CBlockTemplateEntry &a, const CBlockTemplateEntry &b)
118 -> bool { return a.tx->GetId() < b.tx->GetId(); });
119 }
120
121 // Copy all the transactions refs into the block
122 pblock->vtx.reserve(pblocktemplate->entries.size());
123 for (const CBlockTemplateEntry &entry : pblocktemplate->entries) {
124 pblock->vtx.push_back(entry.tx);
125 }
126
127 int64_t nTime1 = GetTimeMicros();
128
131
132 // Create coinbase transaction.
133 CMutableTransaction coinbaseTx;
134 coinbaseTx.vin.resize(1);
135 coinbaseTx.vin[0].prevout = COutPoint();
136 coinbaseTx.vout.resize(1);
137 coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
138 coinbaseTx.vout[0].nValue =
139 blockFitter.nFees + GetBlockSubsidy(nHeight, consensusParams);
140 coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
141
142 const Amount blockReward = coinbaseTx.vout[0].nValue;
143
144 const auto whitelisted = GetMinerFundWhitelist(consensusParams);
145 if (!whitelisted.empty()) {
146 const Amount fund =
147 GetMinerFundAmount(consensusParams, blockReward, pindexPrev);
148 coinbaseTx.vout[0].nValue -= fund;
149 coinbaseTx.vout.emplace_back(
150 fund, GetScriptForDestination(*whitelisted.begin()));
151 }
152
153 std::vector<CScript> stakingRewardsPayoutScripts;
154 if (m_avalanche && IsStakingRewardsActivated(consensusParams, pindexPrev) &&
156 stakingRewardsPayoutScripts)) {
157 const Amount stakingRewards = GetStakingRewardsAmount(blockReward);
158 coinbaseTx.vout[0].nValue -= stakingRewards;
159 coinbaseTx.vout.emplace_back(stakingRewards,
160 stakingRewardsPayoutScripts[0]);
161 }
162
163 // Make sure the coinbase is big enough.
164 uint64_t coinbaseSize = ::GetSerializeSize(coinbaseTx, PROTOCOL_VERSION);
165 if (coinbaseSize < MIN_TX_SIZE) {
166 coinbaseTx.vin[0].scriptSig
167 << std::vector<uint8_t>(MIN_TX_SIZE - coinbaseSize - 1);
168 }
169
170 pblocktemplate->entries[0].tx = MakeTransactionRef(coinbaseTx);
171 pblocktemplate->entries[0].fees = -1 * blockFitter.nFees;
172 pblock->vtx[0] = pblocktemplate->entries[0].tx;
173
174 uint64_t nSerializeSize = GetSerializeSize(*pblock, PROTOCOL_VERSION);
175
176 LogPrintf(
177 "CreateNewBlock(): total size: %u txs: %u fees: %ld sigChecks %d\n",
178 nSerializeSize, blockFitter.nBlockTx, blockFitter.nFees,
180
181 // Fill in header.
182 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
183 UpdateTime(pblock, chainParams, pindexPrev,
184 TicksSinceEpoch<std::chrono::seconds>(GetAdjustedTime()));
185 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainParams);
186 pblock->nNonce = 0;
187 pblocktemplate->entries[0].sigChecks = 0;
188
191 state, chainParams, m_chainstate, *pblock, pindexPrev,
194 .withCheckPoW(false)
195 .withCheckMerkleRoot(false))) {
196 throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s",
197 __func__, state.ToString()));
198 }
199 int64_t nTime2 = GetTimeMicros();
200
201 LogPrint(
203 "CreateNewBlock() addTxs: %.2fms, validity: %.2fms (total %.2fms)\n",
204 0.001 * (nTime1 - nTimeStart), 0.001 * (nTime2 - nTime1),
205 0.001 * (nTime2 - nTimeStart));
206
207 return std::move(pblocktemplate);
208}
209
211 pblocktemplate->entries.emplace_back(entry->GetSharedTx(), entry->GetFee(),
212 entry->GetSigChecks());
213
214 blockFitter.addTx(entry->GetTxSize(), entry->GetSigChecks(),
215 entry->GetFee());
216
217 if (fPrintPriority) {
218 LogPrintf(
219 "fee rate %s txid %s\n",
220 CFeeRate(entry->GetModifiedFee(), entry->GetTxSize()).ToString(),
221 entry->GetTx().GetId().ToString());
222 }
223}
224
225bool BlockAssembler::CheckTx(const CTransaction &tx) const {
226 TxValidationState state;
229}
230
236void BlockAssembler::addTxs(const CTxMemPool &mempool) {
237 // mapped_value is the number of mempool parents that are still needed for
238 // the entry. We decrement this count each time we add a parent of the entry
239 // to the block.
240 std::unordered_map<CTxMemPoolEntryRef, size_t> missingParentCount;
241 missingParentCount.reserve(mempool.size() / 2);
242
243 // set of children we skipped because we have not yet added their parents
244 std::unordered_set<CTxMemPoolEntryRef> skippedChildren;
245
246 auto hasMissingParents =
247 [&missingParentCount](const CTxMemPoolEntryRef &entry)
249 // If we've added any of this tx's parents already, then
250 // missingParentCount will have the current count
251 if (auto pcIt = missingParentCount.find(entry);
252 pcIt != missingParentCount.end()) {
253 // when pcIt->second reaches 0, we have added all of this
254 // tx's parents
255 return pcIt->second != 0;
256 }
257 return !entry->GetMemPoolParentsConst().empty();
258 };
259
260 // Limit the number of attempts to add transactions to the block when it is
261 // close to full; this is just a simple heuristic to finish quickly if the
262 // mempool has a lot of entries.
263 const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
264 int64_t nConsecutiveFailed = 0;
265
266 // Transactions where a parent has been added and need to be checked for
267 // inclusion.
268 std::queue<CTxMemPoolEntryRef> backlog;
269 auto mi = mempool.mapTx.get<modified_feerate>().begin();
270
271 auto nextEntry = [&backlog, &mi](bool &isFromBacklog) {
272 if (backlog.empty()) {
273 return *mi++;
274 }
275
276 auto &entry = backlog.front();
277 backlog.pop();
278
279 isFromBacklog = true;
280
281 return entry;
282 };
283
284 while (!backlog.empty() ||
285 mi != mempool.mapTx.get<modified_feerate>().end()) {
286 // Get a new or old transaction in mapTx to evaluate.
287 bool isFromBacklog = false;
288 const CTxMemPoolEntryRef &entry = nextEntry(isFromBacklog);
289
290 if (blockFitter.isBelowBlockMinFeeRate(entry->GetModifiedFeeRate())) {
291 // Since the txs are sorted by fee, bail early if there is none that
292 // can be included in the block anymore.
293 break;
294 }
295
296 // Check whether all of this tx's parents are already in the block. If
297 // not, pass on it until later.
298 //
299 // If it's from the backlog, then we know all parents are already in
300 // the block.
301 if (!isFromBacklog && hasMissingParents(entry)) {
302 skippedChildren.insert(entry);
303 continue;
304 }
305
306 // Check whether the tx will exceed the block limits.
307 if (!blockFitter.testTxFits(entry->GetTxSize(),
308 entry->GetSigChecks())) {
309 ++nConsecutiveFailed;
310 if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES &&
313 // Give up if we're close to full and haven't succeeded in a
314 // while.
315 break;
316 }
317 continue;
318 }
319
320 // Test transaction finality (locktime)
321 if (!CheckTx(entry->GetTx())) {
322 continue;
323 }
324
325 // This transaction will make it in; reset the failed counter.
326 nConsecutiveFailed = 0;
327
328 // Tx can be added.
329 AddToBlock(entry);
330
331 // This tx's children may now be candidates for addition if they have
332 // higher scores than the tx at the cursor. We can only process a
333 // child once all of that tx's parents have been added, though. To
334 // avoid O(n^2) checking of dependencies, we store and decrement the
335 // number of mempool parents for each child. Although this code
336 // ends up taking O(n) time to process a single tx with n children,
337 // that's okay because the amount of time taken is proportional to the
338 // tx's byte size and fee paid.
339 for (const auto &child : entry->GetMemPoolChildrenConst()) {
340 // Remember this tx has missing parents.
341 // Create the map entry if it doesn't exist already, and init with
342 // the number of parents.
343 const auto &[parentCount, _] = missingParentCount.try_emplace(
344 child, child.get()->GetMemPoolParentsConst().size());
345 // We just added one parent, so decrement the counter and check if
346 // we have any missing parent remaining.
347 const bool allParentsAdded = --parentCount->second == 0;
348
349 // If all parents have been added to the block, and if this child
350 // has been previously skipped due to missing parents, enqueue it
351 // (if it hasn't been skipped it will come up in a later iteration)
352 if (allParentsAdded && skippedChildren.count(child) > 0) {
353 backlog.push(child);
354 }
355 }
356 }
357}
358} // namespace node
bool IsMagneticAnomalyEnabled(const Consensus::Params &params, int32_t nHeight)
Check if Nov 15, 2018 HF has activated using block height.
Definition: activation.cpp:37
static constexpr Amount SATOSHI
Definition: amount.h:143
ArgsManager gArgs
Definition: args.cpp:38
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: args.cpp:526
BlockValidationOptions withCheckPoW(bool _checkPoW=true) const
Definition: validation.h:140
BlockValidationOptions withCheckMerkleRoot(bool _checkMerkleRoot=true) const
Definition: validation.h:147
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:23
uint32_t nNonce
Definition: block.h:31
uint32_t nBits
Definition: block.h:30
uint32_t nTime
Definition: block.h:29
BlockHash hashPrevBlock
Definition: block.h:27
int32_t nVersion
Definition: block.h:26
Definition: block.h:60
std::vector< CTransactionRef > vtx
Definition: block.h:63
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
int64_t GetMedianTimePast() const
Definition: blockindex.h:191
BlockHash GetBlockHash() const
Definition: blockindex.h:130
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:38
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:85
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:97
bool MineBlocksOnDemand() const
Whether it is possible to mine blocks on demand (no retargeting)
Definition: chainparams.h:130
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.
Definition: transaction.h:274
std::vector< CTxOut > vout
Definition: transaction.h:277
std::vector< CTxIn > vin
Definition: transaction.h:276
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:214
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:310
CTransactionRef get(const TxId &txid) const
Definition: txmempool.cpp:603
unsigned long size() const
Definition: txmempool.h:491
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:700
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:799
Definition: config.h:19
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)
Definition: processor.cpp:964
Generate a new block, without valid proof-of-work.
Definition: miner.h:54
Chainstate & m_chainstate
Definition: miner.h:67
const CTxMemPool *const m_mempool
Definition: miner.h:66
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn)
Construct a new block template with coinbase to scriptPubKeyIn.
Definition: miner.cpp:74
const bool fPrintPriority
Definition: miner.h:70
const CChainParams & chainParams
Definition: miner.h:64
int64_t m_lock_time_cutoff
Definition: miner.h:63
static std::optional< int64_t > m_last_block_size
Definition: miner.h:89
std::unique_ptr< CBlockTemplate > pblocktemplate
Definition: miner.h:57
bool CheckTx(const CTransaction &tx) const
Check the transaction for finality, etc before adding to block.
Definition: miner.cpp:225
static std::optional< int64_t > m_last_block_num_txs
Definition: miner.h:88
void AddToBlock(const CTxMemPoolEntryRef &entry)
Add a tx to the block.
Definition: miner.cpp:210
void addTxs(const CTxMemPool &mempool) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs)
Add transactions from the mempool based on individual tx feerate.
Definition: miner.cpp:236
BlockAssembler(const Config &config, Chainstate &chainstate, const CTxMemPool *mempool, const avalanche::Processor *avalanche=nullptr)
Definition: miner.cpp:65
BlockFitter blockFitter
Definition: miner.h:59
const avalanche::Processor *const m_avalanche
Definition: miner.h:68
Check for block limits when adding transactions.
Definition: blockfitter.h:17
bool isBelowBlockMinFeeRate(const CFeeRate &txFeeRate) const
bool testTxFits(uint64_t txSize, int64_t txSigChecks) const
Test if a new Tx would "fit" in the block.
Definition: blockfitter.cpp:91
void resetBlock()
Clear the block's state and prepare for assembling a new block.
Definition: blockfitter.cpp:66
uint64_t nBlockSize
Definition: blockfitter.h:28
uint64_t getMaxGeneratedBlockSize() const
Definition: blockfitter.h:43
uint64_t nBlockTx
Definition: blockfitter.h:29
uint64_t nBlockSigChecks
Definition: blockfitter.h:30
void addTx(size_t txSize, int64_t txSigChecks, Amount txFee)
Account for this tx.
Definition: blockfitter.cpp:76
static const uint64_t MIN_TX_SIZE
The minimum allowed size for a transaction, in bytes.
Definition: consensus.h:16
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:238
#define LogPrintf(...)
Definition: logging.h:227
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
@ BENCH
Definition: logging.h:44
Definition: init.h:31
static const bool DEFAULT_PRINTPRIORITY
Definition: miner.h:36
int64_t UpdateTime(CBlockHeader *pblock, const CChainParams &chainParams, const CBlockIndex *pindexPrev, int64_t adjustedTime)
Definition: miner.cpp:38
uint32_t GetNextWorkRequired(const CBlockIndex *pindexPrev, const CBlockHeader *pblock, const CChainParams &chainParams)
Definition: pow.cpp:21
static CTransactionRef MakeTransactionRef()
Definition: transaction.h:316
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:315
@ 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
Definition: amount.h:19
Parameters that influence chain consensus.
Definition: params.h:34
bool fPowAllowMinDifficultyBlocks
Definition: params.h:77
Definition: miner.h:38
CTransactionRef tx
Definition: miner.h:39
#define LOCK(cs)
Definition: sync.h:306
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
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...
Definition: tinyformat.h:1202
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:594
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.
Definition: versionbits.cpp:8