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;
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);
96 void BlockAssembler::resetBlock()
101 nBlockWeight = m_options.coinbase_max_additional_weight;
102 nBlockSigOpsCost = m_options.coinbase_output_max_additional_sigops;
109 std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(
const CScript& scriptPubKeyIn)
111 const auto time_start{SteadyClock::now()};
117 if (!pblocktemplate.get()) {
120 CBlock*
const pblock = &pblocktemplate->block;
123 pblock->
vtx.emplace_back();
124 pblocktemplate->vTxFees.push_back(-1);
125 pblocktemplate->vTxSigOpsCost.push_back(-1);
128 CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip();
129 assert(pindexPrev !=
nullptr);
132 pblock->
nVersion = m_chainstate.m_chainman.m_versionbitscache.ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
135 if (chainparams.MineBlocksOnDemand()) {
142 int nPackagesSelected = 0;
143 int nDescendantsUpdated = 0;
146 addPackageTxs(*m_mempool, nPackagesSelected, nDescendantsUpdated);
149 const auto time_1{SteadyClock::now()};
151 m_last_block_num_txs = nBlockTx;
152 m_last_block_weight = nBlockWeight;
156 coinbaseTx.
vin.resize(1);
157 coinbaseTx.
vin[0].prevout.SetNull();
158 coinbaseTx.
vout.resize(1);
159 coinbaseTx.
vout[0].scriptPubKey = scriptPubKeyIn;
163 pblocktemplate->vchCoinbaseCommitment = m_chainstate.m_chainman.GenerateCoinbaseCommitment(*pblock, pindexPrev);
164 pblocktemplate->vTxFees[0] = -nFees;
166 LogPrintf(
"CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n",
GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
170 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
176 if (m_options.test_block_validity && !
TestBlockValidity(state, chainparams, m_chainstate, *pblock, pindexPrev,
178 throw std::runtime_error(
strprintf(
"%s: TestBlockValidity failed: %s", __func__, state.
ToString()));
180 const auto time_2{SteadyClock::now()};
182 LogPrint(
BCLog::BENCH,
"CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n",
183 Ticks<MillisecondsDouble>(time_1 - time_start), nPackagesSelected, nDescendantsUpdated,
184 Ticks<MillisecondsDouble>(time_2 - time_1),
185 Ticks<MillisecondsDouble>(time_2 - time_start));
187 return std::move(pblocktemplate);
192 for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
194 if (inBlock.count((*iit)->GetSharedTx()->GetHash())) {
195 testSet.erase(iit++);
202 bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost)
const 228 pblocktemplate->block.vtx.emplace_back(iter->GetSharedTx());
229 pblocktemplate->vTxFees.push_back(iter->GetFee());
230 pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
231 nBlockWeight += iter->GetTxWeight();
233 nBlockSigOpsCost += iter->GetSigOpCost();
234 nFees += iter->GetFee();
235 inBlock.insert(iter->GetSharedTx()->GetHash());
237 if (m_options.print_modified_fee) {
240 iter->GetTx().GetHash().ToString());
253 int nDescendantsUpdated = 0;
256 mempool.CalculateDescendants(it, descendants);
259 if (alreadyAdded.count(desc)) {
262 ++nDescendantsUpdated;
263 modtxiter mit = mapModifiedTx.find(desc);
264 if (mit == mapModifiedTx.end()) {
266 mit = mapModifiedTx.insert(modEntry).first;
271 return nDescendantsUpdated;
280 sortedEntries.clear();
281 sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
295 void BlockAssembler::addPackageTxs(
const CTxMemPool& mempool,
int& nPackagesSelected,
int& nDescendantsUpdated)
303 std::set<Txid> failedTx;
305 CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.
get<
ancestor_score>().begin();
311 const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
312 int64_t nConsecutiveFailed = 0;
314 while (mi != mempool.mapTx.
get<
ancestor_score>().end() || !mapModifiedTx.empty()) {
329 auto it = mempool.mapTx.project<0>(mi);
330 assert(it != mempool.mapTx.end());
331 if (mapModifiedTx.count(it) || inBlock.count(it->GetSharedTx()->GetHash()) || failedTx.count(it->GetSharedTx()->GetHash())) {
339 bool fUsingModified =
false;
345 fUsingModified =
true;
348 iter = mempool.mapTx.project<0>(mi);
355 fUsingModified =
true;
365 assert(!inBlock.count(iter->GetSharedTx()->GetHash()));
367 uint64_t packageSize = iter->GetSizeWithAncestors();
368 CAmount packageFees = iter->GetModFeesWithAncestors();
369 int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
370 if (fUsingModified) {
371 packageSize = modit->nSizeWithAncestors;
372 packageFees = modit->nModFeesWithAncestors;
373 packageSigOpsCost = modit->nSigOpCostWithAncestors;
376 if (packageFees < m_options.blockMinFeeRate.GetFee(packageSize)) {
381 if (!TestPackage(packageSize, packageSigOpsCost)) {
382 if (fUsingModified) {
387 failedTx.insert(iter->GetSharedTx()->GetHash());
390 ++nConsecutiveFailed;
392 if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight >
393 m_options.nBlockMaxWeight - m_options.coinbase_max_additional_weight) {
402 onlyUnconfirmed(ancestors);
403 ancestors.insert(iter);
406 if (!TestPackageTransactions(ancestors)) {
407 if (fUsingModified) {
409 failedTx.insert(iter->GetSharedTx()->GetHash());
415 nConsecutiveFailed = 0;
418 std::vector<CTxMemPool::txiter> sortedEntries;
419 SortForBlock(ancestors, sortedEntries);
421 for (
size_t i = 0; i < sortedEntries.size(); ++i) {
422 AddToBlock(sortedEntries[i]);
424 mapModifiedTx.erase(sortedEntries[i]);
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
static BlockAssembler::Options ClampOptions(BlockAssembler::Options options)
indexed_modified_transaction_set::index< ancestor_score >::type::iterator modtxscoreiter
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
static const int WITNESS_SCALE_FACTOR
#define LogPrint(category,...)
int64_t GetBlockTime() const
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
bool fPowAllowMinDifficultyBlocks
std::set< txiter, CompareIteratorByHash > setEntries
size_t coinbase_output_max_additional_sigops
The maximum additional sigops which the pool will add in coinbase transaction outputs.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
util::Result< void > ApplyArgsManOptions(const ArgsManager &args, BlockManager::Options &opts)
static const int64_t MAX_BLOCK_SIGOPS_COST
The maximum allowed number of signature check operations in a block (network rule) ...
setEntries AssumeCalculateMemPoolAncestors(std::string_view calling_fn_name, const CTxMemPoolEntry &entry, const Limits &limits, bool fSearchForParents=true) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Same as CalculateMemPoolAncestors, but always returns a (non-optional) setEntries.
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) ...
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
int64_t CAmount
Amount in satoshis (Can be negative)
uint256 GetBlockHash() const
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Chainstate stores and provides an API to update our local knowledge of the current best chain...
boost::multi_index_container< CTxMemPoolModifiedEntry, CTxMemPoolModifiedEntry_Indices > indexed_modified_transaction_set
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...
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock, const Consensus::Params ¶ms)
std::string ToString() const
size_t coinbase_max_additional_weight
The maximum additional weight which the pool will add to the coinbase scriptSig, witness and outputs...
std::optional< CAmount > ParseMoney(const std::string &money_string)
Parse an amount denoted in full coins.
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Parameters that influence chain consensus.
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
std::vector< CTxOut > vout
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
int64_t GetMedianTimePast() const
static CTransactionRef MakeTransactionRef(Tx &&txIn)
int64_t DifficultyAdjustmentInterval() const
const CChainParams & GetParams() const
static time_point now() noexcept
Return current system time or mocked time, if set.
bool enforce_BIP94
Enfore BIP94 timewarp attack mitigation.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
std::vector< CTransactionRef > vtx
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Auxiliary functions for transaction validation (ideally should not be exposed)
The block chain is a tree shaped structure starting with the genesis block at the root...
Serialized script, used inside transaction inputs and outputs.
BlockAssembler(Chainstate &chainstate, const CTxMemPool *mempool, const Options &options)
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.
indexed_modified_transaction_set::nth_index< 0 >::type::iterator modtxiter
static constexpr unsigned int DEFAULT_BLOCK_MAX_WEIGHT
Default for -blockmaxweight, which controls the range of block weights the mining code will create...
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
A mutable version of CTransaction.
CTransactionRef get(const uint256 &hash) const
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...
static constexpr MemPoolLimits NoLimits()
int nHeight
height of the entry in the chain. The genesis block has height 0
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...
int GetWitnessCommitmentIndex(const CBlock &block)
Compute at which vout of the block's coinbase transaction the witness commitment occurs, or -1 if not found.
static int64_t GetBlockWeight(const CBlock &block)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
void RegenerateCommitments(CBlock &block, ChainstateManager &chainman)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed...
std::string ToString(const T &t)
Locale-independent version of std::to_string.
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it...
#define Assert(val)
Identity function.
static constexpr int64_t MAX_TIMEWARP
Maximum number of seconds that the timestamp of the first block of a difficulty adjustment period is ...