9#include <chainparams.h>
39 const int height{pindexPrev->
nHeight + 1};
42 if (height % difficulty_adjustment_interval == 0) {
50 int64_t nOldTime = pblock->
nTime;
54 if (nOldTime < nNewTime) {
55 pblock->
nTime = nNewTime;
63 return nNewTime - nOldTime;
89 : chainparams{chainstate.m_chainman.GetParams()},
90 m_mempool{options.use_mempool ? mempool : nullptr},
91 m_chainstate{chainstate},
100 if (
const auto blockmintxfee{
args.
GetArg(
"-blockmintxfee")}) {
103 options.print_modified_fee =
args.
GetBoolArg(
"-printpriority", options.print_modified_fee);
104 options.block_reserved_weight =
args.
GetIntArg(
"-blockreservedweight", options.block_reserved_weight);
107void BlockAssembler::resetBlock()
112 nBlockWeight = m_options.block_reserved_weight;
113 nBlockSigOpsCost = m_options.coinbase_output_max_additional_sigops;
120std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock()
122 const auto time_start{SteadyClock::now()};
127 CBlock*
const pblock = &pblocktemplate->block;
131 pblock->
vtx.emplace_back();
134 CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip();
135 assert(pindexPrev !=
nullptr);
138 pblock->
nVersion = m_chainstate.m_chainman.m_versionbitscache.ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
141 if (chainparams.MineBlocksOnDemand()) {
148 int nPackagesSelected = 0;
149 int nDescendantsUpdated = 0;
151 addPackageTxs(nPackagesSelected, nDescendantsUpdated);
154 const auto time_1{SteadyClock::now()};
156 m_last_block_num_txs = nBlockTx;
157 m_last_block_weight = nBlockWeight;
161 coinbaseTx.
vin.resize(1);
162 coinbaseTx.
vin[0].prevout.SetNull();
164 coinbaseTx.
vout.resize(1);
165 coinbaseTx.
vout[0].scriptPubKey = m_options.coinbase_output_script;
171 pblocktemplate->vchCoinbaseCommitment = m_chainstate.m_chainman.GenerateCoinbaseCommitment(*pblock, pindexPrev);
173 LogPrintf(
"CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n",
GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
177 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
181 if (m_options.test_block_validity) {
183 throw std::runtime_error(
strprintf(
"TestBlockValidity failed: %s", state.ToString()));
186 const auto time_2{SteadyClock::now()};
188 LogDebug(
BCLog::BENCH,
"CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n",
189 Ticks<MillisecondsDouble>(time_1 - time_start), nPackagesSelected, nDescendantsUpdated,
190 Ticks<MillisecondsDouble>(time_2 - time_1),
191 Ticks<MillisecondsDouble>(time_2 - time_start));
193 return std::move(pblocktemplate);
198 for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
200 if (inBlock.count((*iit)->GetSharedTx()->GetHash())) {
201 testSet.erase(iit++);
208bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost)
const
234 pblocktemplate->block.vtx.emplace_back(iter->GetSharedTx());
235 pblocktemplate->vTxFees.push_back(iter->GetFee());
236 pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
237 nBlockWeight += iter->GetTxWeight();
239 nBlockSigOpsCost += iter->GetSigOpCost();
240 nFees += iter->GetFee();
241 inBlock.insert(iter->GetSharedTx()->GetHash());
243 if (m_options.print_modified_fee) {
246 iter->GetTx().GetHash().ToString());
259 int nDescendantsUpdated = 0;
262 mempool.CalculateDescendants(it, descendants);
265 if (alreadyAdded.count(desc)) {
268 ++nDescendantsUpdated;
269 modtxiter mit = mapModifiedTx.find(desc);
270 if (mit == mapModifiedTx.end()) {
272 mit = mapModifiedTx.insert(modEntry).first;
277 return nDescendantsUpdated;
286 sortedEntries.clear();
287 sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
301void BlockAssembler::addPackageTxs(
int& nPackagesSelected,
int& nDescendantsUpdated)
303 const auto& mempool{*
Assert(m_mempool)};
310 std::set<Txid> failedTx;
312 CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<
ancestor_score>().begin();
318 const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
319 constexpr int32_t BLOCK_FULL_ENOUGH_WEIGHT_DELTA = 4000;
320 int64_t nConsecutiveFailed = 0;
322 while (mi != mempool.mapTx.get<
ancestor_score>().end() || !mapModifiedTx.empty()) {
337 auto it = mempool.mapTx.project<0>(mi);
338 assert(it != mempool.mapTx.end());
339 if (mapModifiedTx.count(it) || inBlock.count(it->GetSharedTx()->GetHash()) || failedTx.count(it->GetSharedTx()->GetHash())) {
347 bool fUsingModified =
false;
353 fUsingModified =
true;
356 iter = mempool.mapTx.project<0>(mi);
363 fUsingModified =
true;
373 assert(!inBlock.count(iter->GetSharedTx()->GetHash()));
375 uint64_t packageSize = iter->GetSizeWithAncestors();
376 CAmount packageFees = iter->GetModFeesWithAncestors();
377 int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
378 if (fUsingModified) {
379 packageSize = modit->nSizeWithAncestors;
380 packageFees = modit->nModFeesWithAncestors;
381 packageSigOpsCost = modit->nSigOpCostWithAncestors;
384 if (packageFees < m_options.blockMinFeeRate.GetFee(packageSize)) {
389 if (!TestPackage(packageSize, packageSigOpsCost)) {
390 if (fUsingModified) {
395 failedTx.insert(iter->GetSharedTx()->GetHash());
398 ++nConsecutiveFailed;
400 if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight >
401 m_options.nBlockMaxWeight - BLOCK_FULL_ENOUGH_WEIGHT_DELTA) {
410 onlyUnconfirmed(ancestors);
411 ancestors.insert(iter);
414 if (!TestPackageTransactions(ancestors)) {
415 if (fUsingModified) {
417 failedTx.insert(iter->GetSharedTx()->GetHash());
423 nConsecutiveFailed = 0;
426 std::vector<CTxMemPool::txiter> sortedEntries;
427 SortForBlock(ancestors, sortedEntries);
429 for (
size_t i = 0; i < sortedEntries.size(); ++i) {
430 AddToBlock(sortedEntries[i]);
432 mapModifiedTx.erase(sortedEntries[i]);
436 pblocktemplate->m_package_feerates.emplace_back(packageFees,
static_cast<int32_t
>(packageSize));
445 if (block.
vtx.size() == 0) {
446 block.
vtx.emplace_back(coinbase);
448 block.
vtx[0] = coinbase;
451 block.
nTime = timestamp;
459 const std::unique_ptr<CBlockTemplate>& block_template,
470 const auto deadline = now + options.
timeout;
475 bool tip_changed{
false};
480 AssertLockHeld(kernel_notifications.m_tip_block_mutex);
481 const auto tip_block{kernel_notifications.TipBlock()};
485 tip_changed =
Assume(tip_block) && tip_block != block_template->block.hashPrevBlock;
498 if (!tip_changed && allow_min_difficulty) {
500 if (now > tip_time + 20min) {
521 if (tip_changed)
return new_tmpl;
524 if (current_fees == -1) {
535 if (new_fees >= current_fees + options.
fee_threshold)
return new_tmpl;
540 }
while (now < deadline);
550 return BlockRef{tip->GetBlockHash(), tip->nHeight};
556 if (timeout < 0ms) timeout = 0ms;
557 if (timeout > std::chrono::years{100}) timeout = std::chrono::years{100};
558 auto deadline{std::chrono::steady_clock::now() + timeout};
566 return kernel_notifications.TipBlock() || chainman.m_interrupt;
572 return Assume(kernel_notifications.TipBlock()) != current_tip || chainman.m_interrupt;
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
int64_t CAmount
Amount in satoshis (Can be negative)
#define Assert(val)
Identity function.
#define Assume(val)
Assume is the 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
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
const Consensus::Params & GetConsensus() const
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
std::string ToString(const FeeEstimateMode &fee_estimate_mode=FeeEstimateMode::BTC_KVB) const
Serialized script, used inside transaction inputs and outputs.
static const uint32_t MAX_SEQUENCE_NONFINAL
This is the maximum sequence number that enables both nLockTime and OP_CHECKLOCKTIMEVERIFY (BIP 65).
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...
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
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...
const util::SignalInterrupt & m_interrupt
const CChainParams & GetParams() const
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Generate a new block, without valid proof-of-work.
BlockAssembler(Chainstate &chainstate, const CTxMemPool *mempool, const Options &options)
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
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,...)
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...
std::optional< BlockRef > WaitTipChanged(ChainstateManager &chainman, KernelNotifications &kernel_notifications, const uint256 ¤t_tip, MillisecondsDouble &timeout)
std::unique_ptr< CBlockTemplate > WaitAndCreateNewBlock(ChainstateManager &chainman, KernelNotifications &kernel_notifications, CTxMemPool *mempool, const std::unique_ptr< CBlockTemplate > &block_template, const BlockWaitOptions &options, const BlockAssembler::Options &assemble_options)
Return a new block template when fees rise to a certain threshold or after a new tip; return nullopt ...
void AddMerkleRootAndCoinbase(CBlock &block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce)
std::optional< BlockRef > GetTip(ChainstateManager &chainman)
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)
std::shared_ptr< const CTransaction > CTransactionRef
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.
std::chrono::time_point< NodeClock > time_point
Hash/height pair to help track and identify blocks.
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.
MillisecondsDouble timeout
How long to wait before returning nullptr instead of a new template.
CAmount fee_threshold
The wait method will not return a new template unless it has fees at least fee_threshold sats higher ...
#define WAIT_LOCK(cs, name)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
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.
std::chrono::duration< double, std::chrono::milliseconds::period > MillisecondsDouble
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
BlockValidationState TestBlockValidity(Chainstate &chainstate, const CBlock &block, const bool check_pow, const bool check_merkle_root)
Verify a block, including transactions.