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;
124std::unique_ptr<CBlockTemplate>
143 assert(pindexPrev !=
nullptr);
169 ->
bool { return a.tx->GetId() < b.tx->GetId(); });
175 pblock->
vtx.push_back(entry.
tx);
185 coinbaseTx.
vin.resize(1);
186 coinbaseTx.
vin[0].prevout = COutPoint();
187 coinbaseTx.
vout.resize(1);
188 coinbaseTx.
vout[0].scriptPubKey = scriptPubKeyIn;
189 coinbaseTx.
vout[0].nValue =
193 const Amount blockReward = coinbaseTx.
vout[0].nValue;
196 if (!whitelisted.empty()) {
199 coinbaseTx.
vout[0].nValue -= fund;
200 coinbaseTx.
vout.emplace_back(
204 std::vector<CScript> stakingRewardsPayoutScripts;
207 stakingRewardsPayoutScripts)) {
209 coinbaseTx.
vout[0].nValue -= stakingRewards;
210 coinbaseTx.
vout.emplace_back(stakingRewards,
211 stakingRewardsPayoutScripts[0]);
217 coinbaseTx.
vin[0].scriptSig
218 << std::vector<uint8_t>(
MIN_TX_SIZE - coinbaseSize - 1);
228 "CreateNewBlock(): total size: %u txs: %u fees: %ld sigChecks %d\n",
244 .withCheckMerkleRoot(
false))) {
245 throw std::runtime_error(
strprintf(
"%s: TestBlockValidity failed: %s",
252 "CreateNewBlock() addTxs: %.2fms, validity: %.2fms (total %.2fms)\n",
253 0.001 * (nTime1 - nTimeStart), 0.001 * (nTime2 - nTime1),
254 0.001 * (nTime2 - nTimeStart));
272 pblocktemplate->entries.emplace_back(entry->GetSharedTx(), entry->GetFee(),
273 entry->GetSigChecks());
277 nFees += entry->GetFee();
281 "fee rate %s txid %s\n",
283 entry->GetTx().GetId().ToString());
302 std::unordered_map<CTxMemPoolEntryRef, size_t> missingParentCount;
303 missingParentCount.reserve(mempool.
size() / 2);
306 std::unordered_set<CTxMemPoolEntryRef> skippedChildren;
308 auto hasMissingParents =
313 if (
auto pcIt = missingParentCount.find(entry);
314 pcIt != missingParentCount.end()) {
317 return pcIt->second != 0;
319 return !entry->GetMemPoolParentsConst().empty();
325 const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
326 int64_t nConsecutiveFailed = 0;
330 std::queue<CTxMemPoolEntryRef> backlog;
333 auto nextEntry = [&backlog, &mi](
bool &isFromBacklog) {
334 if (backlog.empty()) {
338 auto &entry = backlog.front();
341 isFromBacklog =
true;
346 while (!backlog.empty() ||
349 bool isFromBacklog =
false;
363 if (!isFromBacklog && hasMissingParents(entry)) {
364 skippedChildren.insert(entry);
369 if (!
TestTxFits(entry->GetTxSize(), entry->GetSigChecks())) {
370 ++nConsecutiveFailed;
371 if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES &&
381 if (!
CheckTx(entry->GetTx())) {
386 nConsecutiveFailed = 0;
399 for (
const auto &child : entry->GetMemPoolChildrenConst()) {
403 const auto &[parentCount,
_] = missingParentCount.try_emplace(
404 child, child.get()->GetMemPoolParentsConst().size());
407 const bool allParentsAdded = --parentCount->second == 0;
412 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
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
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.
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.
virtual uint64_t GetMaxBlockSize() const =0
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
uint64_t nMaxGeneratedBlockSize
void resetBlock()
Clear the block's state and prepare for assembling a new block.
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)
bool TestTxFits(uint64_t txSize, int64_t txSigChecks) const
Test if a new Tx would "fit" in the block.
uint64_t nMaxGeneratedBlockSigChecks
const avalanche::Processor *const m_avalanche
static const uint64_t MIN_TX_SIZE
The minimum allowed size for a transaction, in bytes.
static const uint64_t DEFAULT_MAX_BLOCK_SIZE
Default setting for maximum allowed size for a block, in bytes.
uint64_t GetMaxBlockSigChecksCount(uint64_t maxBlockSize)
Compute the maximum number of sigchecks that can be contained in a block given the MAXIMUM block size...
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)
bool ParseMoney(const std::string &money_string, Amount &nRet)
Parse an amount denoted in full coins.
static const bool DEFAULT_PRINTPRIORITY
int64_t UpdateTime(CBlockHeader *pblock, const CChainParams &chainParams, const CBlockIndex *pindexPrev, int64_t adjustedTime)
static BlockAssembler::Options DefaultOptions(const Config &config)
static constexpr uint64_t DEFAULT_MAX_GENERATED_BLOCK_SIZE
Default for -blockmaxsize, which controls the maximum size of block the mining code will create.
static constexpr Amount DEFAULT_BLOCK_MIN_TX_FEE_PER_KB(1000 *SATOSHI)
Default for -blockmintxfee, which sets the minimum feerate for a transaction in blocks created by min...
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.
static constexpr Amount zero() noexcept
Parameters that influence chain consensus.
bool fPowAllowMinDifficultyBlocks
uint64_t nMaxGeneratedBlockSize
uint64_t nExcessiveBlockSize
#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.