12#include <chainparams.h>
34#include <unordered_map>
39 const CBlockIndex *pindexPrev, int64_t adjustedTime) {
40 int64_t nOldTime = pblock->
nTime;
44 if (nOldTime < nNewTime) {
45 pblock->
nTime = nNewTime;
53 return nNewTime - nOldTime;
60 : blockFitter(fitter), chainParams(chainstate.m_chainman.GetParams()),
61 m_mempool(mempool), m_chainstate(chainstate), m_avalanche(
avalanche),
73std::unique_ptr<CBlockTemplate>
92 assert(pindexPrev !=
nullptr);
118 ->
bool { return a.tx->GetId() < b.tx->GetId(); });
124 pblock->
vtx.push_back(entry.
tx);
134 coinbaseTx.
vin.resize(1);
135 coinbaseTx.
vin[0].prevout = COutPoint();
136 coinbaseTx.
vout.resize(1);
137 coinbaseTx.
vout[0].scriptPubKey = scriptPubKeyIn;
138 coinbaseTx.
vout[0].nValue =
142 const Amount blockReward = coinbaseTx.
vout[0].nValue;
145 if (!whitelisted.empty()) {
148 coinbaseTx.
vout[0].nValue -= fund;
149 coinbaseTx.
vout.emplace_back(
153 std::vector<CScript> stakingRewardsPayoutScripts;
156 stakingRewardsPayoutScripts)) {
158 coinbaseTx.
vout[0].nValue -= stakingRewards;
159 coinbaseTx.
vout.emplace_back(stakingRewards,
160 stakingRewardsPayoutScripts[0]);
166 coinbaseTx.
vin[0].scriptSig
167 << std::vector<uint8_t>(
MIN_TX_SIZE - coinbaseSize - 1);
177 "CreateNewBlock(): total size: %u txs: %u fees: %ld sigChecks %d\n",
196 throw std::runtime_error(
strprintf(
"%s: TestBlockValidity failed: %s",
203 "CreateNewBlock() addTxs: %.2fms, validity: %.2fms (total %.2fms)\n",
204 0.001 * (nTime1 - nTimeStart), 0.001 * (nTime2 - nTime1),
205 0.001 * (nTime2 - nTimeStart));
211 pblocktemplate->entries.emplace_back(entry->GetSharedTx(), entry->GetFee(),
212 entry->GetSigChecks());
219 "fee rate %s txid %s\n",
221 entry->GetTx().GetId().ToString());
240 std::unordered_map<CTxMemPoolEntryRef, size_t> missingParentCount;
241 missingParentCount.reserve(mempool.
size() / 2);
244 std::unordered_set<CTxMemPoolEntryRef> skippedChildren;
246 auto hasMissingParents =
251 if (
auto pcIt = missingParentCount.find(entry);
252 pcIt != missingParentCount.end()) {
255 return pcIt->second != 0;
257 return !entry->GetMemPoolParentsConst().empty();
263 const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
264 int64_t nConsecutiveFailed = 0;
268 std::queue<CTxMemPoolEntryRef> backlog;
271 auto nextEntry = [&backlog, &mi](
bool &isFromBacklog) {
272 if (backlog.empty()) {
276 auto &entry = backlog.front();
279 isFromBacklog =
true;
284 while (!backlog.empty() ||
287 bool isFromBacklog =
false;
301 if (!isFromBacklog && hasMissingParents(entry)) {
302 skippedChildren.insert(entry);
308 entry->GetSigChecks())) {
309 ++nConsecutiveFailed;
310 if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES &&
321 if (!
CheckTx(entry->GetTx())) {
326 nConsecutiveFailed = 0;
339 for (
const auto &child : entry->GetMemPoolChildrenConst()) {
343 const auto &[parentCount,
_] = missingParentCount.try_emplace(
344 child, child.get()->GetMemPoolParentsConst().size());
347 const bool allParentsAdded = --parentCount->second == 0;
352 if (allParentsAdded && skippedChildren.count(child) > 0) {
bool IsMagneticAnomalyEnabled(const Consensus::Params ¶ms, int32_t nHeight)
Check if Nov 15, 2018 HF has activated using block height.
static constexpr Amount SATOSHI
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
BlockValidationOptions withCheckPoW(bool _checkPoW=true) const
BlockValidationOptions withCheckMerkleRoot(bool _checkMerkleRoot=true) const
std::vector< CTransactionRef > vtx
The block chain is a tree shaped structure starting with the genesis block at the root,...
int64_t GetMedianTimePast() const
BlockHash GetBlockHash() 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.
const Consensus::Params & GetConsensus() const
bool MineBlocksOnDemand() const
Whether it is possible to mine blocks on demand (no retargeting)
Fee rate in satoshis per kilobyte: Amount / kB.
std::string ToString() const
A mutable version of CTransaction.
std::vector< CTxOut > vout
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 TxId &txid) const
unsigned long size() const
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.
std::string ToString() const
bool getStakingRewardWinners(const BlockHash &prevBlockHash, std::vector< std::pair< ProofId, CScript > > &winners) const EXCLUSIVE_LOCKS_REQUIRED(!cs_stakingRewards)
Generate a new block, without valid proof-of-work.
Chainstate & m_chainstate
const CTxMemPool *const m_mempool
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn)
Construct a new block template with coinbase to scriptPubKeyIn.
const bool fPrintPriority
const CChainParams & chainParams
int64_t m_lock_time_cutoff
static std::optional< int64_t > m_last_block_size
std::unique_ptr< CBlockTemplate > pblocktemplate
bool CheckTx(const CTransaction &tx) const
Check the transaction for finality, etc before adding to block.
static std::optional< int64_t > m_last_block_num_txs
void AddToBlock(const CTxMemPoolEntryRef &entry)
Add a tx to the block.
void addTxs(const CTxMemPool &mempool) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs)
Add transactions from the mempool based on individual tx feerate.
BlockAssembler(const Config &config, Chainstate &chainstate, const CTxMemPool *mempool, const avalanche::Processor *avalanche=nullptr)
const avalanche::Processor *const m_avalanche
Check for block limits when adding transactions.
bool isBelowBlockMinFeeRate(const CFeeRate &txFeeRate) const
bool testTxFits(uint64_t txSize, int64_t txSigChecks) const
Test if a new Tx would "fit" in the block.
void resetBlock()
Clear the block's state and prepare for assembling a new block.
uint64_t getMaxGeneratedBlockSize() const
void addTx(size_t txSize, int64_t txSigChecks, Amount txFee)
Account for this tx.
static const uint64_t MIN_TX_SIZE
The minimum allowed size for a transaction, in bytes.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
#define LogPrint(category,...)
std::unordered_set< CTxDestination, TxDestinationHasher > GetMinerFundWhitelist(const Consensus::Params ¶ms)
Amount GetMinerFundAmount(const Consensus::Params ¶ms, const Amount &coinbaseValue, const CBlockIndex *pprev)
static const bool DEFAULT_PRINTPRIORITY
int64_t UpdateTime(CBlockHeader *pblock, const CChainParams &chainParams, const CBlockIndex *pindexPrev, int64_t adjustedTime)
uint32_t GetNextWorkRequired(const CBlockIndex *pindexPrev, const CBlockHeader *pblock, const CChainParams &chainParams)
static CTransactionRef MakeTransactionRef()
std::shared_ptr< const CTransaction > CTransactionRef
size_t GetSerializeSize(const T &t, int nVersion=0)
bool IsStakingRewardsActivated(const Consensus::Params ¶ms, const CBlockIndex *pprev)
Amount GetStakingRewardsAmount(const Amount &coinbaseValue)
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Parameters that influence chain consensus.
bool fPowAllowMinDifficultyBlocks
#define EXCLUSIVE_LOCKS_REQUIRED(...)
int64_t GetTimeMicros()
Returns the system time (not mockable)
NodeClock::time_point GetAdjustedTime()
bilingual_str _(const char *psz)
Translation function.
bool ContextualCheckTransaction(const Consensus::Params ¶ms, const CTransaction &tx, TxValidationState &state, int nHeight, int64_t nMedianTimePast)
Context dependent validity checks for non coinbase transactions.
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex &active_chain_tip, const Consensus::Params ¶ms, const CTransaction &tx, TxValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(bool TestBlockValidity(BlockValidationState &state, const CChainParams ¶ms, Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev, const std::function< NodeClock::time_point()> &adjusted_time_callback, BlockValidationOptions validationOptions) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
This is a variant of ContextualCheckTransaction which computes the contextual check for a transaction...
static const int PROTOCOL_VERSION
network protocol versioning
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms)
Determine what nVersion a new block should use.