9 #include <chainparams.h>
33 int64_t nOldTime = pblock->
nTime;
36 if (nOldTime < nNewTime) {
37 pblock->
nTime = nNewTime;
45 return nNewTime - nOldTime;
68 : chainparams{chainstate.m_chainman.GetParams()},
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(); ) {
191 if (
inBlock.count((*iit)->GetSharedTx()->GetHash())) {
192 testSet.erase(iit++);
231 nFees += iter->GetFee();
232 inBlock.insert(iter->GetSharedTx()->GetHash());
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());
301 std::set<Txid> failedTx;
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->GetSharedTx()->GetHash()) || failedTx.count(it->GetSharedTx()->GetHash())) {
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->GetSharedTx()->GetHash());
388 ++nConsecutiveFailed;
390 if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES &&
nBlockWeight >
401 ancestors.insert(iter);
405 if (fUsingModified) {
407 failedTx.insert(iter->GetSharedTx()->GetHash());
413 nConsecutiveFailed = 0;
416 std::vector<CTxMemPool::txiter> sortedEntries;
419 for (
size_t i = 0; i < sortedEntries.size(); ++i) {
422 mapModifiedTx.erase(sortedEntries[i]);
int64_t CAmount
Amount in satoshis (Can be negative)
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 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.
bool MineBlocksOnDemand() const
Whether it is possible to mine blocks on demand (no retargeting)
const Consensus::Params & GetConsensus() const
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
std::string ToString(const FeeEstimateMode &fee_estimate_mode=FeeEstimateMode::BTC_KVB) const
CAmount GetFee(uint32_t num_bytes) const
Return the fee in satoshis for the given vsize in vbytes.
Serialized script, used inside transaction inputs and outputs.
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
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.
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
CTransactionRef get(const uint256 &hash) const
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.
CChain m_chain
The current chain of blockheaders we consult and build on.
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
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...
VersionBitsCache m_versionbitscache
Track versionbit status.
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
std::string ToString() const
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Determine what nVersion a new block should use.
Generate a new block, without valid proof-of-work.
Chainstate & m_chainstate
void onlyUnconfirmed(CTxMemPool::setEntries &testSet)
Remove confirmed (inBlock) entries from given set.
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.
const CTxMemPool *const m_mempool
bool TestPackageTransactions(const CTxMemPool::setEntries &package) const
Perform checks on each transaction in a package: locktime, premature-witness, serialized size (if nec...
const CChainParams & chainparams
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...
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn)
Construct a new block template with coinbase to scriptPubKeyIn.
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.
uint64_t nBlockSigOpsCost
BlockAssembler(Chainstate &chainstate, const CTxMemPool *mempool)
int64_t m_lock_time_cutoff
std::unordered_set< Txid, SaltedTxidHasher > inBlock
std::unique_ptr< CBlockTemplate > pblocktemplate
static std::optional< int64_t > m_last_block_num_txs
void AddToBlock(CTxMemPool::txiter iter)
Add a tx to the block.
static std::optional< int64_t > m_last_block_weight
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 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 LogPrint(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)
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.
static const bool DEFAULT_PRINTPRIORITY
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...
void ApplyArgsManOptions(const ArgsManager &args, BlockAssembler::Options &options)
Apply -blockmintxfee and -blockmaxweight options from ArgsManager to BlockAssembler options.
static BlockAssembler::Options ConfiguredOptions()
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
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 fPowAllowMinDifficultyBlocks
static constexpr MemPoolLimits NoLimits()
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
NodeClock::time_point GetAdjustedTime()
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, 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)