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;
75 : blockFitter(fitter), chainParams(chainstate.m_chainman.GetParams()),
76 m_mempool(mempool), m_chainstate(chainstate), m_avalanche(
avalanche),
77 fPrintPriority{options.fPrintPriority},
78 test_block_validity{options.test_block_validity},
79 add_finalized_txs{
avalanche && options.add_finalized_txs} {}
96std::unique_ptr<CBlockTemplate>
98 const auto time_start{SteadyClock::now()};
115 assert(pindexPrev !=
nullptr);
130 bool shouldAddFinalizedTxs =
136 if (shouldAddFinalizedTxs) {
144 if (!shouldAddFinalizedTxs &&
151 ->
bool { return a.tx->GetId() < b.tx->GetId(); });
157 pblock->
vtx.push_back(entry.
tx);
160 const auto time_1{SteadyClock::now()};
167 coinbaseTx.
vin.resize(1);
168 coinbaseTx.
vin[0].prevout = COutPoint();
169 coinbaseTx.
vout.resize(1);
170 coinbaseTx.
vout[0].scriptPubKey = scriptPubKeyIn;
171 coinbaseTx.
vout[0].nValue =
175 const Amount blockReward = coinbaseTx.
vout[0].nValue;
178 if (!whitelisted.empty()) {
181 coinbaseTx.
vout[0].nValue -= fund;
182 coinbaseTx.
vout.emplace_back(
186 std::vector<CScript> stakingRewardsPayoutScripts;
189 stakingRewardsPayoutScripts)) {
191 coinbaseTx.
vout[0].nValue -= stakingRewards;
192 coinbaseTx.
vout.emplace_back(stakingRewards,
193 stakingRewardsPayoutScripts[0]);
199 coinbaseTx.
vin[0].scriptSig
200 << std::vector<uint8_t>(
MIN_TX_SIZE - coinbaseSize - 1);
210 "CreateNewBlock(): total size: %u txs: %u fees: %ld sigChecks %d\n",
230 throw std::runtime_error(
strprintf(
"%s: TestBlockValidity failed: %s",
233 const auto time_2{SteadyClock::now()};
237 "CreateNewBlock() addTxs: %.2fms, validity: %.2fms (total %.2fms)\n",
238 Ticks<MillisecondsDouble>(time_1 - time_start),
239 Ticks<MillisecondsDouble>(time_2 - time_1),
240 Ticks<MillisecondsDouble>(time_2 - time_start));
246 pblocktemplate->entries.emplace_back(entry->GetSharedTx(), entry->GetFee(),
247 entry->GetSigChecks());
254 "fee rate %s txid %s\n",
256 entry->GetTx().GetId().ToString());
275 std::unordered_map<CTxMemPoolEntryRef, size_t> missingParentCount;
276 missingParentCount.reserve(mempool.
size() / 2);
279 std::unordered_set<CTxMemPoolEntryRef> skippedChildren;
281 auto hasMissingParents =
286 if (
auto pcIt = missingParentCount.find(entry);
287 pcIt != missingParentCount.end()) {
290 return pcIt->second != 0;
292 return !entry->GetMemPoolParentsConst().empty();
298 const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
299 int64_t nConsecutiveFailed = 0;
303 std::queue<CTxMemPoolEntryRef> backlog;
306 auto nextEntry = [&backlog, &mi](
bool &isFromBacklog) {
307 if (backlog.empty()) {
311 auto &entry = backlog.front();
314 isFromBacklog =
true;
319 while (!backlog.empty() ||
322 bool isFromBacklog =
false;
336 if (!isFromBacklog && hasMissingParents(entry)) {
337 skippedChildren.insert(entry);
343 entry->GetSigChecks())) {
344 ++nConsecutiveFailed;
345 if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES &&
356 if (!
CheckTx(entry->GetTx())) {
361 nConsecutiveFailed = 0;
374 for (
const auto &child : entry->GetMemPoolChildrenConst()) {
378 const auto &[parentCount,
_] = missingParentCount.try_emplace(
379 child, child.get()->GetMemPoolParentsConst().size());
382 const bool allParentsAdded = --parentCount->second == 0;
387 if (allParentsAdded && skippedChildren.count(child) > 0) {
407 if (mempool.
exists(entry->GetTx().GetId())) {
bool IsMagneticAnomalyEnabled(const Consensus::Params ¶ms, int32_t nHeight)
Check if Nov 15, 2018 HF has activated using block height.
static constexpr Amount SATOSHI
static constexpr bool DEFAULT_AVALANCHE_MINING_PRECONSENSUS
Default for -avalanchepreconsensusmining.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean 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.
bool exists(const TxId &txid) const
CTransactionRef get(const TxId &txid) const
RadixTree< CTxMemPoolEntry, MemPoolEntryRadixTreeAdapter > finalizedTxs
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)
bool isPreconsensusActivated(const CBlockIndex *pprev) const
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
void addFinalizedTxs(const CTxMemPool &mempool) EXCLUSIVE_LOCKS_REQUIRED(mempool.cs)
Add the finalized transactions to the block template.
const bool add_finalized_txs
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 bool test_block_validity
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)
static BlockFitter::Options ConfiguredOptions(const Config &config)
void ApplyArgsManOptions(const ArgsManager &args, const Config &config, BlockFitter::Options &options)
Apply options from ArgsManager to BlockFitter options.
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
bool forEachLeaf(Callable &&func) const
#define EXCLUSIVE_LOCKS_REQUIRED(...)
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 TestBlockValidity(BlockValidationState &state, const CChainParams ¶ms, Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev, const std::function< NodeClock::time_point()> &adjusted_time_callback, BlockValidationOptions validationOptions)
Check a block is completely valid from start to finish (only works on top of our current best block)
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.