29 int64_t nOldTime = pblock->
nTime;
32 if (nOldTime < nNewTime)
33 pblock->
nTime = nNewTime;
39 return nNewTime - nOldTime;
115 pblock->
vtx.emplace_back();
121 assert(pindexPrev !=
nullptr);
148 int nPackagesSelected = 0;
149 int nDescendantsUpdated = 0;
159 coinbaseTx.
vin.resize(1);
160 coinbaseTx.
vin[0].prevout.SetNull();
161 coinbaseTx.
vout.resize(1);
162 coinbaseTx.
vout[0].scriptPubKey = scriptPubKeyIn;
180 throw std::runtime_error(
strprintf(
"%s: TestBlockValidity failed: %s", __func__, state.
ToString()));
184 LogPrint(
BCLog::BENCH,
"CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n", 0.001 * (nTime1 - nTimeStart), nPackagesSelected, nDescendantsUpdated, 0.001 * (nTime2 - nTime1), 0.001 * (nTime2 - nTimeStart));
191 for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
194 testSet.erase(iit++);
235 nFees += iter->GetFee();
239 if (fPrintPriority) {
242 iter->GetTx().GetHash().ToString());
249 int nDescendantsUpdated = 0;
255 if (alreadyAdded.count(desc))
257 ++nDescendantsUpdated;
258 modtxiter mit = mapModifiedTx.find(desc);
259 if (mit == mapModifiedTx.end()) {
264 mapModifiedTx.insert(modEntry);
270 return nDescendantsUpdated;
285 return mapModifiedTx.count(
it) ||
inBlock.count(
it) || failedTx.count(
it);
294 sortedEntries.clear();
295 sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
321 CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi =
m_mempool.mapTx.
get<
ancestor_score>().begin();
327 const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
328 int64_t nConsecutiveFailed = 0;
340 bool fUsingModified =
false;
346 fUsingModified =
true;
356 fUsingModified =
true;
368 uint64_t packageSize = iter->GetSizeWithAncestors();
369 CAmount packageFees = iter->GetModFeesWithAncestors();
370 int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
371 if (fUsingModified) {
372 packageSize = modit->nSizeWithAncestors;
373 packageFees = modit->nModFeesWithAncestors;
374 packageSigOpsCost = modit->nSigOpCostWithAncestors;
382 if (!
TestPackage(packageSize, packageSigOpsCost)) {
383 if (fUsingModified) {
388 failedTx.insert(iter);
391 ++nConsecutiveFailed;
393 if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES &&
nBlockWeight >
402 uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
407 ancestors.insert(iter);
411 if (fUsingModified) {
413 failedTx.insert(iter);
419 nConsecutiveFailed = 0;
422 std::vector<CTxMemPool::txiter> sortedEntries;
425 for (
size_t i=0; i<sortedEntries.size(); ++i) {
428 mapModifiedTx.erase(sortedEntries[i]);
451 assert(txCoinbase.
vin[0].scriptSig.size() <= 100);
int64_t CAmount
Amount in satoshis (Can be negative)
const CChainParams & Params()
Return the currently selected parameters.
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
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.
Generate a new block, without valid proof-of-work.
int UpdatePackagesForAdded(const CTxMemPool::setEntries &alreadyAdded, indexed_modified_transaction_set &mapModifiedTx) EXCLUSIVE_LOCKS_REQUIRED(m_mempool.cs)
Add descendants of given transactions to mapModifiedTx with ancestor state updated assuming given tra...
void AddToBlock(CTxMemPool::txiter iter)
Add a tx to the block.
CTxMemPool::setEntries inBlock
void addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated) EXCLUSIVE_LOCKS_REQUIRED(m_mempool.cs)
Add transactions based on feerate including unconfirmed ancestors Increments nPackagesSelected / nDes...
void onlyUnconfirmed(CTxMemPool::setEntries &testSet)
Remove confirmed (inBlock) entries from given set.
static Optional< int64_t > m_last_block_weight
bool TestPackageTransactions(const CTxMemPool::setEntries &package)
Perform checks on each transaction in a package: locktime, premature-witness, serialized size (if nec...
const CTxMemPool & m_mempool
void resetBlock()
Clear the block's state and prepare for assembling a new block.
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.
std::unique_ptr< CBlockTemplate > pblocktemplate
BlockAssembler(const CTxMemPool &mempool, const CChainParams ¶ms)
const CChainParams & chainparams
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn)
Construct a new block template with coinbase to scriptPubKeyIn.
bool SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx) EXCLUSIVE_LOCKS_REQUIRED(m_mempool.cs)
Return true if given transaction from mapTx has already been evaluated, or if the transaction's cache...
unsigned int nBlockMaxWeight
static Optional< int64_t > m_last_block_num_txs
uint64_t nBlockSigOpsCost
bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
Test if a new package would "fit" in the block.
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.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
bool MineBlocksOnDemand() const
Whether it is possible to mine blocks on demand (no retargeting)
const Consensus::Params & GetConsensus() const
Fee rate in satoshis per kilobyte: CAmount / kB.
CAmount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
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 ...
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
bool CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents=true) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Try to calculate all in-mempool ancestors of entry.
std::set< txiter, CompareIteratorByHash > setEntries
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
std::string ToString() const
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 unsigned int LOCKTIME_MEDIAN_TIME_PAST
Use GetMedianTimePast() instead of nTime for end point timestamp.
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
static void LogPrintf(const char *fmt, const Args &... args)
#define LogPrint(category,...)
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
static BlockAssembler::Options DefaultOptions()
void RegenerateCommitments(CBlock &block)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed.
void IncrementExtraNonce(CBlock *pblock, const CBlockIndex *pindexPrev, unsigned int &nExtraNonce)
Modify the extranonce in a block.
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
indexed_modified_transaction_set::nth_index< 0 >::type::iterator modtxiter
static const bool DEFAULT_PRINTPRIORITY
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
indexed_modified_transaction_set::index< ancestor_score >::type::iterator modtxscoreiter
bool ParseMoney(const std::string &money_string, CAmount &nRet)
Parse an amount denoted in full coins.
peer m_getdata_requests erase(peer.m_getdata_requests.begin(), it)
std::deque< CInv >::iterator it
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
static auto & nullopt
Substitute for C++17 std::nullopt.
boost::optional< T > Optional
Substitute for C++17 std::optional.
static constexpr unsigned int STANDARD_LOCKTIME_VERIFY_FLAGS
Used as the flags parameter to sequence and nLocktime checks in non-consensus code.
static const unsigned int DEFAULT_BLOCK_MIN_TX_FEE
Default for -blockmintxfee, which sets the minimum feerate for a transaction in blocks created by min...
static const 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()
A mutable version of CTransaction.
std::vector< CTxOut > vout
uint64_t nSizeWithAncestors
CAmount nModFeesWithAncestors
int64_t nSigOpCostWithAncestors
Parameters that influence chain consensus.
bool fPowAllowMinDifficultyBlocks
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
int64_t GetTimeMicros()
Returns the system time (not mockable)
int64_t 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.
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms)
Determine what nVersion a new block should use.
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
std::vector< unsigned char > GenerateCoinbaseCommitment(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks...
CChain & ChainActive()
Please prefer the identical ChainstateManager::ActiveChain.
CBlockIndex * LookupBlockIndex(const uint256 &hash)
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, 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)
bool IsWitnessEnabled(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms)
Check whether witness commitments are required for a block, and whether to enforce NULLDUMMY (BIP 147...