9 #include <chainparams.h> 33 int64_t nOldTime = pblock->
nTime;
36 if (nOldTime < nNewTime) {
37 pblock->
nTime = nNewTime;
45 return nNewTime - nOldTime;
70 m_chainstate{chainstate},
79 if (
const auto blockmintxfee{
args.
GetArg(
"-blockmintxfee")}) {
108 const auto time_start{SteadyClock::now()};
120 pblock->
vtx.emplace_back();
126 assert(pindexPrev !=
nullptr);
139 int nPackagesSelected = 0;
140 int nDescendantsUpdated = 0;
146 const auto time_1{SteadyClock::now()};
153 coinbaseTx.
vin.resize(1);
154 coinbaseTx.
vin[0].prevout.SetNull();
155 coinbaseTx.
vout.resize(1);
156 coinbaseTx.
vout[0].scriptPubKey = scriptPubKeyIn;
175 throw std::runtime_error(
strprintf(
"%s: TestBlockValidity failed: %s", __func__, state.
ToString()));
177 const auto time_2{SteadyClock::now()};
179 LogPrint(
BCLog::BENCH,
"CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n",
180 Ticks<MillisecondsDouble>(time_1 - time_start), nPackagesSelected, nDescendantsUpdated,
181 Ticks<MillisecondsDouble>(time_2 - time_1),
182 Ticks<MillisecondsDouble>(time_2 - time_start));
189 for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
192 testSet.erase(iit++);
231 nFees += iter->GetFee();
235 if (fPrintPriority) {
238 iter->GetTx().GetHash().ToString());
251 int nDescendantsUpdated = 0;
254 mempool.CalculateDescendants(it, descendants);
257 if (alreadyAdded.count(desc)) {
260 ++nDescendantsUpdated;
261 modtxiter mit = mapModifiedTx.find(desc);
262 if (mit == mapModifiedTx.end()) {
264 mit = mapModifiedTx.insert(modEntry).first;
269 return nDescendantsUpdated;
278 sortedEntries.clear();
279 sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
303 CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.
get<
ancestor_score>().begin();
309 const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
310 int64_t nConsecutiveFailed = 0;
312 while (mi != mempool.mapTx.
get<
ancestor_score>().end() || !mapModifiedTx.empty()) {
327 auto it = mempool.mapTx.project<0>(mi);
328 assert(it != mempool.mapTx.end());
329 if (mapModifiedTx.count(it) ||
inBlock.count(it) || failedTx.count(it)) {
337 bool fUsingModified =
false;
343 fUsingModified =
true;
346 iter = mempool.mapTx.project<0>(mi);
353 fUsingModified =
true;
365 uint64_t packageSize = iter->GetSizeWithAncestors();
366 CAmount packageFees = iter->GetModFeesWithAncestors();
367 int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
368 if (fUsingModified) {
369 packageSize = modit->nSizeWithAncestors;
370 packageFees = modit->nModFeesWithAncestors;
371 packageSigOpsCost = modit->nSigOpCostWithAncestors;
379 if (!
TestPackage(packageSize, packageSigOpsCost)) {
380 if (fUsingModified) {
385 failedTx.insert(iter);
388 ++nConsecutiveFailed;
390 if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES &&
nBlockWeight >
401 ancestors.insert(iter);
405 if (fUsingModified) {
407 failedTx.insert(iter);
413 nConsecutiveFailed = 0;
416 std::vector<CTxMemPool::txiter> sortedEntries;
419 for (
size_t i = 0; i < sortedEntries.size(); ++i) {
422 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
void onlyUnconfirmed(CTxMemPool::setEntries &testSet)
Remove confirmed (inBlock) entries from given set.
#define LogPrint(category,...)
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Generate a new block, without valid proof-of-work.
CTxMemPool::setEntries inBlock
void resetBlock()
Clear the block's state and prepare for assembling a new block.
bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
Test if a new package would "fit" in the block.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
bool TestPackageTransactions(const CTxMemPool::setEntries &package) const
Perform checks on each transaction in a package: locktime, premature-witness, serialized size (if nec...
BlockAssembler(Chainstate &chainstate, const CTxMemPool *mempool)
void SortForBlock(const CTxMemPool::setEntries &package, std::vector< CTxMemPool::txiter > &sortedEntries)
Sort the package in an order that is valid to appear in a block.
static std::optional< int64_t > m_last_block_num_txs
bool fPowAllowMinDifficultyBlocks
std::set< txiter, CompareIteratorByHash > setEntries
void addPackageTxs(const CTxMemPool &mempool, int &nPackagesSelected, int &nDescendantsUpdated) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs)
Add transactions based on feerate including unconfirmed ancestors Increments nPackagesSelected / nDes...
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)
CChain m_chain
The current chain of blockheaders we consult and build on.
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.
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
int64_t m_lock_time_cutoff
void AddToBlock(CTxMemPool::txiter iter)
Add a tx to the block.
NodeClock::time_point GetAdjustedTime()
VersionBitsCache m_versionbitscache
Track versionbit status.
int64_t CAmount
Amount in satoshis (Can be negative)
uint256 GetBlockHash() const
std::string ToString(const T &t)
Locale-independent version of std::to_string.
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...
static BlockAssembler::Options ConfiguredOptions()
bool MineBlocksOnDemand() const
Whether it is possible to mine blocks on demand (no retargeting)
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
std::optional< CAmount > ParseMoney(const std::string &money_string)
Parse an amount denoted in full coins.
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn)
Construct a new block template with coinbase to scriptPubKeyIn.
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
void ApplyArgsManOptions(const ArgsManager &args, BlockAssembler::Options &options)
Apply -blockmintxfee and -blockmaxweight options from ArgsManager to BlockAssembler options...
Parameters that influence chain consensus.
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
std::vector< CTxOut > vout
Chainstate & m_chainstate
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
int64_t GetMedianTimePast() const
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Determine what nVersion a new block should use.
static CTransactionRef MakeTransactionRef(Tx &&txIn)
const CChainParams & GetParams() const
static std::optional< int64_t > m_last_block_weight
boost::multi_index_container< CTxMemPoolModifiedEntry, boost::multi_index::indexed_by< boost::multi_index::ordered_unique< modifiedentry_iter, CompareCTxMemPoolIter >, boost::multi_index::ordered_non_unique< boost::multi_index::tag< ancestor_score >, boost::multi_index::identity< CTxMemPoolModifiedEntry >, CompareTxMemPoolEntryByAncestorFee > >> indexed_modified_transaction_set
#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.
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.
const CChainParams & chainparams
indexed_modified_transaction_set::nth_index< 0 >::type::iterator modtxiter
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
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.
CAmount GetFee(uint32_t num_bytes) const
Return the fee in satoshis for the given vsize in vbytes.
A mutable version of CTransaction.
uint64_t nBlockSigOpsCost
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
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev, const std::function< NodeClock::time_point()> &adjusted_time_callback, bool fCheckPOW, bool fCheckMerkleRoot)
Check a block is completely valid from start to finish (only works on top of our current best block) ...
const Consensus::Params & GetConsensus() const
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::unique_ptr< CBlockTemplate > pblocktemplate
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 const bool DEFAULT_PRINTPRIORITY
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...
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it...
const CTxMemPool *const m_mempool