9#include <chainparams.h>
42#include <versionbits.h>
46#include <condition_variable>
61 const int height{pindexPrev->
nHeight + 1};
64 if (height % difficulty_adjustment_interval == 0) {
69 if (height % difficulty_adjustment_interval == difficulty_adjustment_interval - 1) {
70 const int first_height{height -
static_cast<int>(difficulty_adjustment_interval) + 1};
72 min_time = std::max<int64_t>(min_time, first_block->
GetBlockTime());
79 int64_t nOldTime = pblock->
nTime;
83 if (nOldTime < nNewTime) {
84 pblock->
nTime = nNewTime;
92 return nNewTime - nOldTime;
99 block.
vtx.at(0) = MakeTransactionRef(tx);
111 m_mempool{options.use_mempool ? mempool : nullptr},
135 const auto time_start{SteadyClock::now()};
144 pblock->
vtx.emplace_back();
148 assert(pindexPrev !=
nullptr);
168 const auto time_1{SteadyClock::now()};
180 coinbaseTx.
vin.resize(1);
181 coinbaseTx.
vin[0].prevout.SetNull();
183 coinbase_tx.
sequence = coinbaseTx.
vin[0].nSequence;
186 coinbaseTx.
vout.resize(1);
190 coinbaseTx.
vout[0].nValue = block_reward;
208 coinbaseTx.
vin[0].scriptSig <<
OP_0;
214 pblock->
vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
218 if (final_coinbase->HasWitness()) {
219 const auto& witness_stack{final_coinbase->vin[0].scriptWitness.stack};
222 Assert(witness_stack.size() == 1 && witness_stack[0].size() == 32);
226 Assert(witness_index >= 0 &&
static_cast<size_t>(witness_index) < final_coinbase->vout.size());
227 coinbase_tx.
required_outputs.push_back(final_coinbase->vout[witness_index]);
240 throw std::runtime_error(
strprintf(
"TestBlockValidity failed: %s", state.ToString()));
243 const auto time_2{SteadyClock::now()};
270 for (
const auto tx : txs) {
289 LogInfo(
"fee rate %s txid %s\n",
300 const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
301 constexpr int32_t BLOCK_FULL_ENOUGH_WEIGHT_DELTA = 4000;
302 int64_t nConsecutiveFailed = 0;
304 std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> selected_transactions;
310 FeePerVSize chunk_feerate_vsize = ToFeePerVSize(chunk_feerate);
312 while (selected_transactions.size() > 0) {
319 int64_t chunk_sig_ops = 0;
320 int64_t chunk_weight = 0;
321 for (
const auto& tx : selected_transactions) {
322 chunk_sig_ops += tx.get().GetSigOpCost();
323 chunk_weight += tx.get().GetTxWeight();
330 ++nConsecutiveFailed;
334 if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES &&
nBlockWeight +
343 nConsecutiveFailed = 0;
344 for (
const auto& tx : selected_transactions) {
347 pblocktemplate->m_package_feerates.emplace_back(chunk_feerate_vsize);
350 selected_transactions.clear();
352 chunk_feerate_vsize = ToFeePerVSize(chunk_feerate);
358 if (block.
vtx.size() == 0) {
359 block.
vtx.emplace_back(coinbase);
361 block.
vtx[0] = coinbase;
364 block.
nTime = timestamp;
380 BlockValidationState m_state;
382 explicit SubmitBlockStateCatcher(
const uint256& hash) : m_hash{hash} {}
385 void BlockChecked(
const std::shared_ptr<const CBlock>& block,
const BlockValidationState& state)
override
387 if (block->GetHash() != m_hash)
return;
408 auto sc = std::make_shared<SubmitBlockStateCatcher>(block->GetHash());
411 bool accepted = chainman.
ProcessNewBlock(block,
true,
true, &new_block);
416 if (!new_block && accepted) {
417 reason =
"duplicate";
418 }
else if (!accepted && (!sc->m_found || sc->m_state.IsValid())) {
423 reason =
"inconclusive";
424 }
else if (!sc->m_found) {
427 reason =
"inconclusive";
428 }
else if (!sc->m_state.IsValid()) {
429 reason = sc->m_state.GetRejectReason();
430 debug = sc->m_state.GetDebugMessage();
432 const bool result{accepted && new_block && reason.empty()};
440 interrupt_wait =
true;
441 kernel_notifications.m_tip_block_cv.notify_all();
447 const std::unique_ptr<CBlockTemplate>& block_template,
450 bool& interrupt_wait)
459 const auto deadline = now + wait_options.
timeout;
464 bool tip_changed{
false};
469 AssertLockHeld(kernel_notifications.m_tip_block_mutex);
470 const auto tip_block{kernel_notifications.TipBlock()};
474 tip_changed =
Assume(tip_block) && tip_block != block_template->block.hashPrevBlock;
475 return tip_changed || chainman.
m_interrupt || interrupt_wait;
477 if (interrupt_wait) {
478 interrupt_wait =
false;
491 if (!tip_changed && allow_min_difficulty) {
493 if (now > tip_time + 20min) {
514 if (tip_changed)
return new_tmpl;
517 if (current_fees == -1) {
518 current_fees = std::accumulate(block_template->vTxFees.begin(), block_template->vTxFees.end(),
CAmount{0});
522 const CAmount new_fees = std::accumulate(new_tmpl->vTxFees.begin(), new_tmpl->vTxFees.end(),
CAmount{0});
524 if (new_fees >= current_fees + wait_options.
fee_threshold)
return new_tmpl;
528 }
while (now < deadline);
545 while (
const std::optional<int> remaining = chainman.BlocksAheadOfTip()) {
546 const int cooldown_seconds = std::clamp(*remaining, 3, 20);
552 const auto tip_block = kernel_notifications.TipBlock();
553 return chainman.m_interrupt || interrupt_mining || (tip_block && *tip_block != last_tip_hash);
556 interrupt_mining =
false;
561 const auto tip_block = kernel_notifications.
TipBlock();
562 if (tip_block && *tip_block != last_tip_hash) {
563 last_tip_hash = *tip_block;
578 if (timeout < 0ms) timeout = 0ms;
579 if (timeout > std::chrono::years{100}) timeout = std::chrono::years{100};
580 auto deadline{std::chrono::steady_clock::now() + timeout};
588 return kernel_notifications.TipBlock() || chainman.m_interrupt || interrupt;
597 return Assume(kernel_notifications.TipBlock()) != current_tip || chainman.m_interrupt || interrupt;
constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
int64_t CAmount
Amount in satoshis (Can be negative).
#define CHECK_NONFATAL(condition)
Identity function.
#define Assert(val)
Identity function.
#define Assume(val)
Assume is the identity function.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
void resetBlock()
Clear the block's state and prepare for assembling a new block.
bool TestChunkTransactions(const std::vector< CTxMemPoolEntryRef > &txs) const
Perform locktime checks on each transaction in a chunk: This check should always succeed,...
void AddToBlock(const CTxMemPoolEntry &entry)
Add a tx to the block.
bool TestChunkBlockLimits(int64_t chunk_weight, int64_t chunk_sigops_cost) const
Test if a new chunk would "fit" in the block.
std::unique_ptr< CBlockTemplate > CreateNewBlock()
Construct a new block template.
void addChunks() EXCLUSIVE_LOCKS_REQUIRED(m_mempool -> cs)
Add transactions based on chunk feerate.
Wrapper around FeeFrac & derived types, which adds a feerate-based ordering which treats equal-feerat...
bool m_checked_merkle_root
std::vector< CTransactionRef > vtx
bool m_checked_witness_commitment
The block chain is a tree shaped structure starting with the genesis block at the root,...
uint256 GetBlockHash() const
int64_t GetBlockTime() const
int64_t GetMedianTimePast() const
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
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.
const Consensus::Params & GetConsensus() const
bool MineBlocksOnDemand() const
Whether it is possible to mine blocks on demand (no retargeting).
CFeeRate()=default
Fee rate of 0 satoshis per 0 vB.
const Txid & GetHash() const LIFETIMEBOUND
static constexpr uint32_t MAX_SEQUENCE_NONFINAL
This is the maximum sequence number that enables both nLockTime and OP_CHECKLOCKTIMEVERIFY (BIP 65).
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
const CTransaction & GetTx() const
int32_t GetTxWeight() const
int64_t GetSigOpCost() const
CTransactionRef GetSharedTx() const
int32_t GetTxSize() const
const CAmount & GetFee() const
CAmount GetModifiedFee() const
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
void StopBlockBuilding() const EXCLUSIVE_LOCKS_REQUIRED(cs)
void StartBlockBuilding() const EXCLUSIVE_LOCKS_REQUIRED(cs)
void IncludeBuilderChunk() const EXCLUSIVE_LOCKS_REQUIRED(cs)
void SkipBuilderChunk() const EXCLUSIVE_LOCKS_REQUIRED(cs)
FeePerWeight GetBlockBuilderChunk(std::vector< CTxMemPoolEntry::CTxMemPoolEntryRef > &entries) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Implement this to subscribe to events generated in validation and mempool.
Chainstate stores and provides an API to update our local knowledge of the current best chain.
ChainstateManager & m_chainman
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
Chainstate & ActiveChainstate() const
bool ProcessNewBlock(const std::shared_ptr< const CBlock > &block, bool force_processing, bool min_pow_checked, bool *new_block) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
const util::SignalInterrupt & m_interrupt
VersionBitsCache m_versionbitscache
Track versionbit status.
const CChainParams & GetParams() const
void GenerateCoinbaseCommitment(CBlock &block, const CBlockIndex *pindexPrev) const
Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks...
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
node::BlockManager m_blockman
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Determine what nVersion a new block should use.
Generate a new block, without valid proof-of-work.
Chainstate & m_chainstate
void resetBlock()
Clear the block's state and prepare for assembling a new block.
const CTxMemPool *const m_mempool
bool TestChunkTransactions(const std::vector< CTxMemPoolEntryRef > &txs) const
Perform locktime checks on each transaction in a chunk: This check should always succeed,...
const CChainParams & chainparams
void AddToBlock(const CTxMemPoolEntry &entry)
Add a tx to the block.
uint64_t nBlockSigOpsCost
int64_t m_lock_time_cutoff
std::unique_ptr< CBlockTemplate > pblocktemplate
static std::optional< int64_t > m_last_block_num_txs
The number of transactions in the last assembled block (excluding coinbase transaction).
bool TestChunkBlockLimits(int64_t chunk_weight, int64_t chunk_sigops_cost) const
Test if a new chunk would "fit" in the block.
std::unique_ptr< CBlockTemplate > CreateNewBlock()
Construct a new block template.
static std::optional< int64_t > m_last_block_weight
The weight of the last assembled block (including reserved weight for block header,...
void addChunks() EXCLUSIVE_LOCKS_REQUIRED(m_mempool -> cs)
Add transactions based on chunk feerate.
const BlockCreateOptions m_options
BlockAssembler(Chainstate &chainstate, const CTxMemPool *mempool, BlockCreateOptions create_options)
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
std::optional< uint256 > TipBlock() EXCLUSIVE_LOCKS_REQUIRED(m_tip_block_mutex)
std::string ToString() const
constexpr uint256()=default
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
constexpr int NO_WITNESS_COMMITMENT
Index marker for when no witness commitment is present in a coinbase transaction.
int GetWitnessCommitmentIndex(const CBlock &block)
Compute at which vout of the block's coinbase transaction the witness commitment occurs,...
constexpr int64_t MAX_BLOCK_SIGOPS_COST
The maximum allowed number of signature check operations in a block (network rule).
constexpr int64_t MAX_TIMEWARP
Maximum number of seconds that the timestamp of the first block of a difficulty adjustment period is ...
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
FeePerUnit< VSizeTag > FeePerVSize
FeePerUnit< WeightTag > FeePerWeight
#define LogDebug(category,...)
void RegenerateCommitments(CBlock &block, ChainstateManager &chainman)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed.
std::optional< BlockRef > WaitTipChanged(ChainstateManager &chainman, KernelNotifications &kernel_notifications, const uint256 ¤t_tip, MillisecondsDouble &timeout, bool &interrupt)
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
BlockCreateOptions FlattenMiningOptions(BlockCreateOptions options)
Replace null optional values with their hardcoded defaults.
int64_t GetMinimumTime(const CBlockIndex *pindexPrev, const int64_t difficulty_adjustment_interval)
Get the minimum time a miner should use in the next block.
void InterruptWait(KernelNotifications &kernel_notifications, bool &interrupt_wait)
std::unique_ptr< CBlockTemplate > WaitAndCreateNewBlock(ChainstateManager &chainman, KernelNotifications &kernel_notifications, CTxMemPool *mempool, const std::unique_ptr< CBlockTemplate > &block_template, const BlockWaitOptions &wait_options, const BlockCreateOptions &create_options, bool &interrupt_wait)
Return a new block template when fees rise to a certain threshold or after a new tip; return nullopt ...
void AddMerkleRootAndCoinbase(CBlock &block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce)
Result< void > CheckMiningOptions(BlockCreateOptions options, bool use_argnames)
Check option values for validity.
bool CooldownIfHeadersAhead(ChainstateManager &chainman, KernelNotifications &kernel_notifications, const BlockRef &last_tip, bool &interrupt_mining)
Wait while the best known header extends the current chain tip AND at least one block is being added ...
std::optional< BlockRef > GetTip(ChainstateManager &chainman)
bool SubmitBlock(ChainstateManager &chainman, const std::shared_ptr< const CBlock > &block, std::string &reason, std::string &debug)
bilingual_str ErrorString(const Result< T > &result)
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock, const Consensus::Params ¶ms)
std::shared_ptr< const CTransaction > CTransactionRef
A mutable version of CTransaction.
std::vector< CTxOut > vout
Parameters that influence chain consensus.
int64_t DifficultyAdjustmentInterval() const
bool fPowAllowMinDifficultyBlocks
static time_point now() noexcept
Return current system time or mocked time, if set.
static time_point now() noexcept
Return current system time or mocked time, if set.
std::chrono::time_point< NodeClock > time_point
Hash/height pair to help track and identify blocks.
ValidationSignals * signals
Block template creation options.
std::optional< bool > print_modified_fee
Whether to log the fee rate of each transaction when it is added to the block template.
std::optional< CFeeRate > block_min_fee_rate
Minimum fee rate for transactions to be included.
CScript coinbase_output_script
Script to put in the coinbase transaction.
bool test_block_validity
Whether to call TestBlockValidity() at the end of CreateNewBlock().
std::optional< uint64_t > block_max_weight
Maximum block weight, defaults to -maxblockweight.
size_t coinbase_output_max_additional_sigops
The maximum additional sigops which the pool will add in coinbase transaction outputs.
std::optional< uint64_t > block_reserved_weight
The default reserved weight for the fixed-size block header, transaction count and coinbase transacti...
MillisecondsDouble timeout
How long to wait before returning nullptr instead of a new template.
CAmount fee_threshold
The wait method will not return a new template unless it has fees at least fee_threshold sats higher ...
Template containing all coinbase transaction fields that are set by our miner code.
CScript script_sig_prefix
Prefix which needs to be placed at the beginning of the scriptSig.
CAmount block_reward_remaining
Block subsidy plus fees, minus any non-zero required_outputs.
std::vector< CTxOut > required_outputs
std::optional< uint256 > witness
The first (and only) witness stack element of the coinbase input.
#define WAIT_LOCK(cs, name)
#define WITH_LOCK(cs, code)
#define EXCLUSIVE_LOCKS_REQUIRED(...)
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.
constexpr unsigned MAX_CLUSTER_COUNT_LIMIT
std::chrono::duration< double, std::chrono::milliseconds::period > MillisecondsDouble
constexpr auto TicksSinceEpoch(Timepoint t)
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
BlockValidationState TestBlockValidity(Chainstate &chainstate, const CBlock &block, const bool check_pow, const bool check_merkle_root)
Verify a block, including transactions.