9#include <chainparams.h>
33 int64_t nOldTime = pblock->
nTime;
38 const int height{pindexPrev->
nHeight + 1};
44 if (nOldTime < nNewTime) {
45 pblock->
nTime = nNewTime;
53 return nNewTime - nOldTime;
79 : chainparams{chainstate.m_chainman.GetParams()},
80 m_mempool{options.use_mempool ? mempool : nullptr},
81 m_chainstate{chainstate},
90 if (
const auto blockmintxfee{
args.
GetArg(
"-blockmintxfee")}) {
93 options.print_modified_fee =
args.
GetBoolArg(
"-printpriority", options.print_modified_fee);
96void BlockAssembler::resetBlock()
101 nBlockWeight = m_options.coinbase_max_additional_weight;
102 nBlockSigOpsCost = m_options.coinbase_output_max_additional_sigops;
109std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock()
111 const auto time_start{SteadyClock::now()};
116 CBlock*
const pblock = &pblocktemplate->block;
119 pblock->
vtx.emplace_back();
120 pblocktemplate->vTxFees.push_back(-1);
121 pblocktemplate->vTxSigOpsCost.push_back(-1);
124 CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip();
125 assert(pindexPrev !=
nullptr);
128 pblock->
nVersion = m_chainstate.m_chainman.m_versionbitscache.ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
131 if (chainparams.MineBlocksOnDemand()) {
138 int nPackagesSelected = 0;
139 int nDescendantsUpdated = 0;
141 addPackageTxs(nPackagesSelected, nDescendantsUpdated);
144 const auto time_1{SteadyClock::now()};
146 m_last_block_num_txs = nBlockTx;
147 m_last_block_weight = nBlockWeight;
151 coinbaseTx.
vin.resize(1);
152 coinbaseTx.
vin[0].prevout.SetNull();
153 coinbaseTx.
vout.resize(1);
154 coinbaseTx.
vout[0].scriptPubKey = m_options.coinbase_output_script;
158 pblocktemplate->vchCoinbaseCommitment = m_chainstate.m_chainman.GenerateCoinbaseCommitment(*pblock, pindexPrev);
159 pblocktemplate->vTxFees[0] = -nFees;
161 LogPrintf(
"CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n",
GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
165 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
171 if (m_options.test_block_validity && !
TestBlockValidity(state, chainparams, m_chainstate, *pblock, pindexPrev,
173 throw std::runtime_error(
strprintf(
"%s: TestBlockValidity failed: %s", __func__, state.
ToString()));
175 const auto time_2{SteadyClock::now()};
177 LogDebug(
BCLog::BENCH,
"CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n",
178 Ticks<MillisecondsDouble>(time_1 - time_start), nPackagesSelected, nDescendantsUpdated,
179 Ticks<MillisecondsDouble>(time_2 - time_1),
180 Ticks<MillisecondsDouble>(time_2 - time_start));
182 return std::move(pblocktemplate);
187 for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
189 if (inBlock.count((*iit)->GetSharedTx()->GetHash())) {
190 testSet.erase(iit++);
197bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost)
const
223 pblocktemplate->block.vtx.emplace_back(iter->GetSharedTx());
224 pblocktemplate->vTxFees.push_back(iter->GetFee());
225 pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
226 nBlockWeight += iter->GetTxWeight();
228 nBlockSigOpsCost += iter->GetSigOpCost();
229 nFees += iter->GetFee();
230 inBlock.insert(iter->GetSharedTx()->GetHash());
232 if (m_options.print_modified_fee) {
235 iter->GetTx().GetHash().ToString());
248 int nDescendantsUpdated = 0;
251 mempool.CalculateDescendants(it, descendants);
254 if (alreadyAdded.count(desc)) {
257 ++nDescendantsUpdated;
258 modtxiter mit = mapModifiedTx.find(desc);
259 if (mit == mapModifiedTx.end()) {
261 mit = mapModifiedTx.insert(modEntry).first;
266 return nDescendantsUpdated;
275 sortedEntries.clear();
276 sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
290void BlockAssembler::addPackageTxs(
int& nPackagesSelected,
int& nDescendantsUpdated)
292 const auto& mempool{*
Assert(m_mempool)};
299 std::set<Txid> failedTx;
301 CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<
ancestor_score>().begin();
307 const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
308 int64_t nConsecutiveFailed = 0;
310 while (mi != mempool.mapTx.get<
ancestor_score>().end() || !mapModifiedTx.empty()) {
325 auto it = mempool.mapTx.project<0>(mi);
326 assert(it != mempool.mapTx.end());
327 if (mapModifiedTx.count(it) || inBlock.count(it->GetSharedTx()->GetHash()) || failedTx.count(it->GetSharedTx()->GetHash())) {
335 bool fUsingModified =
false;
341 fUsingModified =
true;
344 iter = mempool.mapTx.project<0>(mi);
351 fUsingModified =
true;
361 assert(!inBlock.count(iter->GetSharedTx()->GetHash()));
363 uint64_t packageSize = iter->GetSizeWithAncestors();
364 CAmount packageFees = iter->GetModFeesWithAncestors();
365 int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
366 if (fUsingModified) {
367 packageSize = modit->nSizeWithAncestors;
368 packageFees = modit->nModFeesWithAncestors;
369 packageSigOpsCost = modit->nSigOpCostWithAncestors;
372 if (packageFees < m_options.blockMinFeeRate.GetFee(packageSize)) {
377 if (!TestPackage(packageSize, packageSigOpsCost)) {
378 if (fUsingModified) {
383 failedTx.insert(iter->GetSharedTx()->GetHash());
386 ++nConsecutiveFailed;
388 if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight >
389 m_options.nBlockMaxWeight - m_options.coinbase_max_additional_weight) {
398 onlyUnconfirmed(ancestors);
399 ancestors.insert(iter);
402 if (!TestPackageTransactions(ancestors)) {
403 if (fUsingModified) {
405 failedTx.insert(iter->GetSharedTx()->GetHash());
411 nConsecutiveFailed = 0;
414 std::vector<CTxMemPool::txiter> sortedEntries;
415 SortForBlock(ancestors, sortedEntries);
417 for (
size_t i = 0; i < sortedEntries.size(); ++i) {
418 AddToBlock(sortedEntries[i]);
420 mapModifiedTx.erase(sortedEntries[i]);
int64_t CAmount
Amount in satoshis (Can be negative)
#define Assert(val)
Identity function.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
std::vector< CTransactionRef > vtx
The block chain is a tree shaped structure starting with the genesis block at the root,...
uint256 GetBlockHash() const
int64_t GetBlockTime() const
int64_t GetMedianTimePast() const
int nHeight
height of the entry in the chain. The genesis block has height 0
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
std::string ToString(const FeeEstimateMode &fee_estimate_mode=FeeEstimateMode::BTC_KVB) const
Serialized script, used inside transaction inputs and outputs.
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
std::set< txiter, CompareIteratorByHash > setEntries
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
std::vector< unsigned char > GenerateCoinbaseCommitment(CBlock &block, const CBlockIndex *pindexPrev) const
Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks...
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
std::string ToString() const
BlockAssembler(Chainstate &chainstate, const CTxMemPool *mempool, const Options &options)
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
static int64_t GetBlockWeight(const CBlock &block)
int GetWitnessCommitmentIndex(const CBlock &block)
Compute at which vout of the block's coinbase transaction the witness commitment occurs,...
static constexpr int64_t MAX_TIMEWARP
Maximum number of seconds that the timestamp of the first block of a difficulty adjustment period is ...
static const int64_t MAX_BLOCK_SIGOPS_COST
The maximum allowed number of signature check operations in a block (network rule)
static const int WITNESS_SCALE_FACTOR
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
#define LogDebug(category,...)
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
std::optional< CAmount > ParseMoney(const std::string &money_string)
Parse an amount denoted in full coins.
static BlockAssembler::Options ClampOptions(BlockAssembler::Options options)
boost::multi_index_container< CTxMemPoolModifiedEntry, CTxMemPoolModifiedEntry_Indices > indexed_modified_transaction_set
indexed_modified_transaction_set::nth_index< 0 >::type::iterator modtxiter
void RegenerateCommitments(CBlock &block, ChainstateManager &chainman)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed.
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
indexed_modified_transaction_set::index< ancestor_score >::type::iterator modtxscoreiter
util::Result< void > ApplyArgsManOptions(const ArgsManager &args, BlockManager::Options &opts)
static int UpdatePackagesForAdded(const CTxMemPool &mempool, const CTxMemPool::setEntries &alreadyAdded, indexed_modified_transaction_set &mapModifiedTx) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs)
Add descendants of given transactions to mapModifiedTx with ancestor state updated assuming given tra...
static constexpr unsigned int DEFAULT_BLOCK_MAX_WEIGHT
Default for -blockmaxweight, which controls the range of block weights the mining code will create.
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock, const Consensus::Params ¶ms)
static CTransactionRef MakeTransactionRef(Tx &&txIn)
A mutable version of CTransaction.
std::vector< CTxOut > vout
Parameters that influence chain consensus.
bool enforce_BIP94
Enforce BIP94 timewarp attack mitigation.
int64_t DifficultyAdjustmentInterval() const
bool fPowAllowMinDifficultyBlocks
static time_point now() noexcept
Return current system time or mocked time, if set.
static constexpr MemPoolLimits NoLimits()
size_t coinbase_output_max_additional_sigops
The maximum additional sigops which the pool will add in coinbase transaction outputs.
size_t coinbase_max_additional_weight
The maximum additional weight which the pool will add to the coinbase scriptSig, witness and outputs.
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Auxiliary functions for transaction validation (ideally should not be exposed)
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
Check if transaction is final and can be included in a block with the specified height and time.
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
Check a block is completely valid from start to finish (only works on top of our current best block)