9#include <chainparams.h>
36 const int height{pindexPrev->
nHeight + 1};
39 if (height % difficulty_adjustment_interval == 0) {
47 int64_t nOldTime = pblock->
nTime;
51 if (nOldTime < nNewTime) {
52 pblock->
nTime = nNewTime;
60 return nNewTime - nOldTime;
87 : chainparams{chainstate.m_chainman.GetParams()},
88 m_mempool{options.use_mempool ? mempool : nullptr},
89 m_chainstate{chainstate},
98 if (
const auto blockmintxfee{
args.
GetArg(
"-blockmintxfee")}) {
101 options.print_modified_fee =
args.
GetBoolArg(
"-printpriority", options.print_modified_fee);
102 options.block_reserved_weight =
args.
GetIntArg(
"-blockreservedweight", options.block_reserved_weight);
105void BlockAssembler::resetBlock()
110 nBlockWeight = m_options.block_reserved_weight;
111 nBlockSigOpsCost = m_options.coinbase_output_max_additional_sigops;
118std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock()
120 const auto time_start{SteadyClock::now()};
125 CBlock*
const pblock = &pblocktemplate->block;
128 pblock->
vtx.emplace_back();
129 pblocktemplate->vTxFees.push_back(-1);
130 pblocktemplate->vTxSigOpsCost.push_back(-1);
133 CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip();
134 assert(pindexPrev !=
nullptr);
137 pblock->
nVersion = m_chainstate.m_chainman.m_versionbitscache.ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
140 if (chainparams.MineBlocksOnDemand()) {
147 int nPackagesSelected = 0;
148 int nDescendantsUpdated = 0;
150 addPackageTxs(nPackagesSelected, nDescendantsUpdated);
153 const auto time_1{SteadyClock::now()};
155 m_last_block_num_txs = nBlockTx;
156 m_last_block_weight = nBlockWeight;
160 coinbaseTx.
vin.resize(1);
161 coinbaseTx.
vin[0].prevout.SetNull();
162 coinbaseTx.
vout.resize(1);
163 coinbaseTx.
vout[0].scriptPubKey = m_options.coinbase_output_script;
167 pblocktemplate->vchCoinbaseCommitment = m_chainstate.m_chainman.GenerateCoinbaseCommitment(*pblock, pindexPrev);
168 pblocktemplate->vTxFees[0] = -nFees;
170 LogPrintf(
"CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n",
GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
174 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
180 if (m_options.test_block_validity && !
TestBlockValidity(state, chainparams, m_chainstate, *pblock, pindexPrev,
182 throw std::runtime_error(
strprintf(
"%s: TestBlockValidity failed: %s", __func__, state.
ToString()));
184 const auto time_2{SteadyClock::now()};
186 LogDebug(
BCLog::BENCH,
"CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n",
187 Ticks<MillisecondsDouble>(time_1 - time_start), nPackagesSelected, nDescendantsUpdated,
188 Ticks<MillisecondsDouble>(time_2 - time_1),
189 Ticks<MillisecondsDouble>(time_2 - time_start));
191 return std::move(pblocktemplate);
196 for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
198 if (inBlock.count((*iit)->GetSharedTx()->GetHash())) {
199 testSet.erase(iit++);
206bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost)
const
232 pblocktemplate->block.vtx.emplace_back(iter->GetSharedTx());
233 pblocktemplate->vTxFees.push_back(iter->GetFee());
234 pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
235 nBlockWeight += iter->GetTxWeight();
237 nBlockSigOpsCost += iter->GetSigOpCost();
238 nFees += iter->GetFee();
239 inBlock.insert(iter->GetSharedTx()->GetHash());
241 if (m_options.print_modified_fee) {
244 iter->GetTx().GetHash().ToString());
257 int nDescendantsUpdated = 0;
260 mempool.CalculateDescendants(it, descendants);
263 if (alreadyAdded.count(desc)) {
266 ++nDescendantsUpdated;
267 modtxiter mit = mapModifiedTx.find(desc);
268 if (mit == mapModifiedTx.end()) {
270 mit = mapModifiedTx.insert(modEntry).first;
275 return nDescendantsUpdated;
284 sortedEntries.clear();
285 sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
299void BlockAssembler::addPackageTxs(
int& nPackagesSelected,
int& nDescendantsUpdated)
301 const auto& mempool{*
Assert(m_mempool)};
308 std::set<Txid> failedTx;
310 CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<
ancestor_score>().begin();
316 const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
317 int64_t nConsecutiveFailed = 0;
319 while (mi != mempool.mapTx.get<
ancestor_score>().end() || !mapModifiedTx.empty()) {
334 auto it = mempool.mapTx.project<0>(mi);
335 assert(it != mempool.mapTx.end());
336 if (mapModifiedTx.count(it) || inBlock.count(it->GetSharedTx()->GetHash()) || failedTx.count(it->GetSharedTx()->GetHash())) {
344 bool fUsingModified =
false;
350 fUsingModified =
true;
353 iter = mempool.mapTx.project<0>(mi);
360 fUsingModified =
true;
370 assert(!inBlock.count(iter->GetSharedTx()->GetHash()));
372 uint64_t packageSize = iter->GetSizeWithAncestors();
373 CAmount packageFees = iter->GetModFeesWithAncestors();
374 int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
375 if (fUsingModified) {
376 packageSize = modit->nSizeWithAncestors;
377 packageFees = modit->nModFeesWithAncestors;
378 packageSigOpsCost = modit->nSigOpCostWithAncestors;
381 if (packageFees < m_options.blockMinFeeRate.GetFee(packageSize)) {
386 if (!TestPackage(packageSize, packageSigOpsCost)) {
387 if (fUsingModified) {
392 failedTx.insert(iter->GetSharedTx()->GetHash());
395 ++nConsecutiveFailed;
397 if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight >
398 m_options.nBlockMaxWeight - m_options.block_reserved_weight) {
407 onlyUnconfirmed(ancestors);
408 ancestors.insert(iter);
411 if (!TestPackageTransactions(ancestors)) {
412 if (fUsingModified) {
414 failedTx.insert(iter->GetSharedTx()->GetHash());
420 nConsecutiveFailed = 0;
423 std::vector<CTxMemPool::txiter> sortedEntries;
424 SortForBlock(ancestors, sortedEntries);
426 for (
size_t i = 0; i < sortedEntries.size(); ++i) {
427 AddToBlock(sortedEntries[i]);
429 mapModifiedTx.erase(sortedEntries[i]);
433 pblocktemplate->m_package_feerates.emplace_back(packageFees,
static_cast<int32_t
>(packageSize));
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 unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
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 GetMinimumTime(const CBlockIndex *pindexPrev, const int64_t difficulty_adjustment_interval)
Get the minimum time a miner should use in the next block.
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 MINIMUM_BLOCK_RESERVED_WEIGHT
This accounts for the block header, var_int encoding of the transaction count and a minimally viable ...
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.
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 block_reserved_weight
The default reserved weight for the fixed-size block header, transaction count and coinbase transacti...
size_t coinbase_output_max_additional_sigops
The maximum additional sigops which the pool will add in coinbase transaction 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)