20 #include <minerfund.h>
34 #include <unordered_map>
40 int64_t nOldTime = pblock->
nTime;
41 int64_t nNewTime{std::max<int64_t>(
45 if (nOldTime < nNewTime) {
46 pblock->
nTime = nNewTime;
54 return nNewTime - nOldTime;
122 std::unique_ptr<CBlockTemplate>
141 assert(pindexPrev !=
nullptr);
167 ->
bool { return a.tx->GetId() < b.tx->GetId(); });
173 pblock->
vtx.push_back(entry.
tx);
183 coinbaseTx.
vin.resize(1);
185 coinbaseTx.
vout.resize(1);
186 coinbaseTx.
vout[0].scriptPubKey = scriptPubKeyIn;
187 coinbaseTx.
vout[0].nValue =
191 const Amount blockReward = coinbaseTx.
vout[0].nValue;
194 if (!whitelisted.empty()) {
197 coinbaseTx.
vout[0].nValue -= fund;
198 coinbaseTx.
vout.emplace_back(
202 std::vector<CScript> stakingRewardsPayoutScripts;
205 stakingRewardsPayoutScripts)) {
207 coinbaseTx.
vout[0].nValue -= stakingRewards;
208 coinbaseTx.
vout.emplace_back(stakingRewards,
209 stakingRewardsPayoutScripts[0]);
215 coinbaseTx.
vin[0].scriptSig
216 << std::vector<uint8_t>(
MIN_TX_SIZE - coinbaseSize - 1);
226 "CreateNewBlock(): total size: %u txs: %u fees: %ld sigChecks %d\n",
241 .withCheckMerkleRoot(
false))) {
242 throw std::runtime_error(
strprintf(
"%s: TestBlockValidity failed: %s",
249 "CreateNewBlock() addTxs: %.2fms, validity: %.2fms (total %.2fms)\n",
250 0.001 * (nTime1 - nTimeStart), 0.001 * (nTime2 - nTime1),
251 0.001 * (nTime2 - nTimeStart));
269 pblocktemplate->entries.emplace_back(entry->GetSharedTx(), entry->GetFee(),
270 entry->GetSigChecks());
274 nFees += entry->GetFee();
278 "fee rate %s txid %s\n",
280 entry->GetTx().GetId().ToString());
299 std::unordered_map<CTxMemPoolEntryRef, size_t> missingParentCount;
300 missingParentCount.reserve(mempool.
size() / 2);
303 std::unordered_set<CTxMemPoolEntryRef> skippedChildren;
305 auto hasMissingParents =
310 if (
auto pcIt = missingParentCount.find(entry);
311 pcIt != missingParentCount.end()) {
314 return pcIt->second != 0;
316 return !entry->GetMemPoolParentsConst().empty();
322 const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
323 int64_t nConsecutiveFailed = 0;
327 std::queue<CTxMemPoolEntryRef> backlog;
330 auto nextEntry = [&backlog, &mi](
bool &isFromBacklog) {
331 if (backlog.empty()) {
335 auto &entry = backlog.front();
338 isFromBacklog =
true;
343 while (!backlog.empty() ||
346 bool isFromBacklog =
false;
360 if (!isFromBacklog && hasMissingParents(entry)) {
361 skippedChildren.insert(entry);
366 if (!
TestTxFits(entry->GetTxSize(), entry->GetSigChecks())) {
367 ++nConsecutiveFailed;
368 if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES &&
378 if (!
CheckTx(entry->GetTx())) {
383 nConsecutiveFailed = 0;
396 for (
const auto &child : entry->GetMemPoolChildrenConst()) {
400 const auto &[parentCount,
_] = missingParentCount.try_emplace(
401 child, child.get()->GetMemPoolParentsConst().size());
404 const bool allParentsAdded = --parentCount->second == 0;
409 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
std::unique_ptr< avalanche::Processor > g_avalanche
Global avalanche instance.
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.
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: Amount / kB.
std::string ToString() const
A mutable version of CTransaction.
std::vector< CTxOut > vout
An outpoint - a combination of a transaction hash and an index n into its vout.
Serialized script, used inside transaction inputs and outputs.
The basic transaction that is broadcasted on the network and contained in blocks.
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
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
BlockAssembler(const Config &config, Chainstate &chainstate, const CTxMemPool *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.
bool TestTxFits(uint64_t txSize, int64_t txSigChecks) const
Test if a new Tx would "fit" in the block.
uint64_t nMaxGeneratedBlockSigChecks
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,...)
Amount GetMinerFundAmount(const Consensus::Params ¶ms, const Amount &coinbaseValue, const CBlockIndex *pprev)
std::unordered_set< CTxDestination, TxDestinationHasher > GetMinerFundWhitelist(const Consensus::Params ¶ms)
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)
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(boo 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.