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);
indexed_modified_transaction_set::nth_index< 0 >::type::iterator modtxiter
peer m_getdata_requests erase(peer.m_getdata_requests.begin(), it)
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 IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
static Optional< int64_t > m_last_block_num_txs
std::deque< CInv >::iterator it
unsigned int nBlockMaxWeight
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
static const int WITNESS_SCALE_FACTOR
#define LogPrint(category,...)
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
void AddToBlock(CTxMemPool::txiter iter)
Add a tx to the block.
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...
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
CChain & ChainActive()
Please prefer the identical ChainstateManager::ActiveChain.
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
void onlyUnconfirmed(CTxMemPool::setEntries &testSet)
Remove confirmed (inBlock) entries from given set.
CTxMemPool::setEntries inBlock
std::unique_ptr< CBlockTemplate > pblocktemplate
bool fPowAllowMinDifficultyBlocks
static void LogPrintf(const char *fmt, const Args &... args)
std::set< txiter, CompareIteratorByHash > setEntries
static auto & nullopt
Substitute for C++17 std::nullopt DEPRECATED use std::nullopt in new code.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
bool ParseMoney(const std::string &money_string, CAmount &nRet)
Parse an amount denoted in full coins.
bool TestPackageTransactions(const CTxMemPool::setEntries &package) const
Perform checks on each transaction in a package: locktime, premature-witness, serialized size (if nec...
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms)
Determine what nVersion a new block should use.
static const int64_t MAX_BLOCK_SIGOPS_COST
The maximum allowed number of signature check operations in a block (network rule) ...
indexed_modified_transaction_set::index< ancestor_score >::type::iterator modtxscoreiter
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
BlockAssembler(const CTxMemPool &mempool, const CChainParams ¶ms)
int64_t CAmount
Amount in satoshis (Can be negative)
static BlockAssembler::Options DefaultOptions()
uint256 GetBlockHash() const
std::string ToString(const T &t)
Locale-independent version of std::to_string.
bool MineBlocksOnDemand() const
Whether it is possible to mine blocks on demand (no retargeting)
const CChainParams & chainparams
static constexpr unsigned int LOCKTIME_MEDIAN_TIME_PAST
Use GetMedianTimePast() instead of nTime for end point timestamp.
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock, const Consensus::Params ¶ms)
std::string ToString() const
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...
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
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Generate a new block, without valid proof-of-work.
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
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...
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 > CreateNewBlock(const CScript &scriptPubKeyIn)
Construct a new block template with coinbase to scriptPubKeyIn.
Parameters that influence chain consensus.
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.
static Optional< int64_t > m_last_block_weight
std::vector< CTxOut > vout
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
int64_t GetMedianTimePast() const
const CTxMemPool & m_mempool
uint64_t nSizeWithAncestors
static CTransactionRef MakeTransactionRef(Tx &&txIn)
int64_t GetTimeMicros()
Returns the system time (not mockable)
void IncrementExtraNonce(CBlock *pblock, const CBlockIndex *pindexPrev, unsigned int &nExtraNonce)
Modify the extranonce in a block.
CBlockIndex * LookupBlockIndex(const uint256 &hash)
uint64_t nBlockSigOpsCost
CAmount nModFeesWithAncestors
void RegenerateCommitments(CBlock &block)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed...
std::vector< CTransactionRef > vtx
void addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated) EXCLUSIVE_LOCKS_REQUIRED(m_mempool.cs)
Add transactions based on feerate including unconfirmed ancestors Increments nPackagesSelected / nDes...
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...
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
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...
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
int64_t GetAdjustedTime()
int64_t nSigOpCostWithAncestors
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Fee rate in satoshis per kilobyte: CAmount / kB.
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...
void resetBlock()
Clear the block's state and prepare for assembling a new block.
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...
int nHeight
height of the entry in the chain. The genesis block has height 0
const Consensus::Params & GetConsensus() const
static const bool DEFAULT_PRINTPRIORITY
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 unsigned int DEFAULT_BLOCK_MAX_WEIGHT
Default for -blockmaxweight, which controls the range of block weights the mining code will create...
static int64_t GetBlockWeight(const CBlock &block)
static constexpr unsigned int STANDARD_LOCKTIME_VERIFY_FLAGS
Used as the flags parameter to sequence and nLocktime checks in non-consensus code.
bool TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const
Test if a new package would "fit" in the block.
std::optional< T > Optional
Substitute for C++17 std::optional DEPRECATED use std::optional in new code.
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it...
CAmount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.