35 int64_t nOldTime = pblock->
nTime;
39 if (nOldTime < nNewTime) {
40 pblock->
nTime = nNewTime;
48 return nNewTime - nOldTime;
123 std::unique_ptr<CBlockTemplate>
142 assert(pindexPrev !=
nullptr);
162 int nPackagesSelected = 0;
163 int nDescendantsUpdated = 0;
172 ->
bool { return a.tx->GetId() < b.tx->GetId(); });
178 pblock->
vtx.push_back(entry.
tx);
188 coinbaseTx.
vin.resize(1);
190 coinbaseTx.
vout.resize(1);
191 coinbaseTx.
vout[0].scriptPubKey = scriptPubKeyIn;
192 coinbaseTx.
vout[0].nValue =
196 const std::vector<CTxDestination> whitelisted =
198 if (!whitelisted.empty()) {
200 coinbaseTx.
vout[0].nValue -= fund;
201 coinbaseTx.
vout.emplace_back(fund,
208 coinbaseTx.
vin[0].scriptSig
209 << std::vector<uint8_t>(
MIN_TX_SIZE - coinbaseSize - 1);
219 "CreateNewBlock(): total size: %u txs: %u fees: %ld sigChecks %d\n",
234 .withCheckMerkleRoot(
false))) {
235 throw std::runtime_error(
strprintf(
"%s: TestBlockValidity failed: %s",
241 "CreateNewBlock() packages: %.2fms (%d packages, %d updated "
242 "descendants), validity: %.2fms (total %.2fms)\n",
243 0.001 * (nTime1 - nTimeStart), nPackagesSelected,
244 nDescendantsUpdated, 0.001 * (nTime2 - nTime1),
245 0.001 * (nTime2 - nTimeStart));
251 for (CTxMemPool::setEntries::iterator iit = testSet.begin();
252 iit != testSet.end();) {
255 testSet.erase(iit++);
263 int64_t packageSigChecks)
const {
264 auto blockSizeWithPackage =
nBlockSize + packageSize;
296 nPotentialBlockSize += nTxSize;
303 pblocktemplate->entries.emplace_back(iter->GetSharedTx(), iter->GetFee(),
304 iter->GetSigChecks());
308 nFees += iter->GetFee();
311 bool fPrintPriority =
313 if (fPrintPriority) {
315 "fee rate %s txid %s\n",
317 iter->GetTx().GetId().ToString());
324 int nDescendantsUpdated = 0;
330 if (alreadyAdded.count(desc)) {
334 ++nDescendantsUpdated;
335 modtxiter mit = mapModifiedTx.find(desc);
336 if (mit == mapModifiedTx.end()) {
338 mit = mapModifiedTx.insert(modEntry).first;
344 return nDescendantsUpdated;
359 return mapModifiedTx.count(it) ||
inBlock.count(it) || failedTx.count(it);
364 std::vector<CTxMemPool::txiter> &sortedEntries) {
368 sortedEntries.clear();
369 sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
370 std::sort(sortedEntries.begin(), sortedEntries.end(),
382 int &nDescendantsUpdated) {
400 CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator
407 const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
408 int64_t nConsecutiveFailed = 0;
411 !mapModifiedTx.empty()) {
422 bool fUsingModified =
false;
428 fUsingModified =
true;
438 fUsingModified =
true;
450 uint64_t packageSize = iter->GetSizeWithAncestors();
451 Amount packageFees = iter->GetModFeesWithAncestors();
452 int64_t packageSigChecks = iter->GetSigChecksWithAncestors();
453 if (fUsingModified) {
454 packageSize = modit->nSizeWithAncestors;
455 packageFees = modit->nModFeesWithAncestors;
456 packageSigChecks = modit->nSigChecksWithAncestors;
463 if (fUsingModified) {
468 failedTx.insert(iter);
477 if (fUsingModified) {
482 failedTx.insert(iter);
485 ++nConsecutiveFailed;
487 if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES &&
498 uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
501 nNoLimit, nNoLimit, nNoLimit, dummy,
505 ancestors.insert(iter);
509 if (fUsingModified) {
511 failedTx.insert(iter);
517 nConsecutiveFailed = 0;
520 std::vector<CTxMemPool::txiter> sortedEntries;
523 for (
auto &entry : sortedEntries) {
526 mapModifiedTx.erase(entry);
536 static const std::vector<uint8_t>
538 std::string cbmsg =
"/EB" +
getSubVersionEB(nExcessiveBlockSize) +
"/";
539 std::vector<uint8_t> vec(cbmsg.begin(), cbmsg.end());
544 uint64_t nExcessiveBlockSize,
545 unsigned int &nExtraNonce) {
557 txCoinbase.
vin[0].scriptSig =
564 txCoinbase.
vin[0].scriptSig
565 << std::vector<uint8_t>(
MIN_TX_SIZE - coinbaseSize - 1);
bool IsMagneticAnomalyEnabled(const Consensus::Params ¶ms, int32_t nHeight)
Check if Nov 15, 2018 HF has activated using block height.
static constexpr Amount SATOSHI
RecursiveMutex cs_main
Global state.
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.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean 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
CChainState 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.
Fee rate in satoshis per kilobyte: Amount / kB.
std::string ToString() const
Amount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
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.
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
std::set< txiter, CompareIteratorById > setEntries
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
bool CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents=true) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Try to calculate all in-mempool ancestors of entry.
CTransactionRef get(const TxId &txid) const
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
virtual uint64_t GetMaxBlockSize() const =0
std::string ToString() const
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms)
Determine what nVersion a new block should use.
Generate a new block, without valid proof-of-work.
uint64_t nMaxGeneratedBlockSize
void onlyUnconfirmed(CTxMemPool::setEntries &testSet)
Remove confirmed (inBlock) entries from given set.
void resetBlock()
Clear the block's state and prepare for assembling a new block.
CChainState & m_chainstate
bool TestPackage(uint64_t packageSize, int64_t packageSigChecks) const
Test if a new package would "fit" in the block.
const CTxMemPool & m_mempool
bool TestPackageTransactions(const CTxMemPool::setEntries &package) const
Perform checks on each transaction in a package: locktime, serialized size (if necessary).
void addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated) EXCLUSIVE_LOCKS_REQUIRED(m_mempool.cs)
Add transactions based on feerate including unconfirmed ancestors.
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn)
Construct a new block template with coinbase to scriptPubKeyIn.
void SortForBlock(const CTxMemPool::setEntries &package, std::vector< CTxMemPool::txiter > &sortedEntries)
Sort the package in an order that is valid to appear in a block.
BlockAssembler(const Config &config, CChainState &chainstate, const CTxMemPool &mempool)
CTxMemPool::setEntries inBlock
int UpdatePackagesForAdded(const CTxMemPool::setEntries &alreadyAdded, indexed_modified_transaction_set &mapModifiedTx) EXCLUSIVE_LOCKS_REQUIRED(m_mempool.cs)
Add descendants of given transactions to mapModifiedTx with ancestor state updated assuming given tra...
const CChainParams & chainParams
static std::optional< int64_t > m_last_block_size
std::unique_ptr< CBlockTemplate > pblocktemplate
static std::optional< int64_t > m_last_block_num_txs
void AddToBlock(CTxMemPool::txiter iter)
Add a tx to the block.
bool SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx) EXCLUSIVE_LOCKS_REQUIRED(m_mempool.cs)
Return true if given transaction from mapTx has already been evaluated, or if the transaction's cache...
uint64_t nMaxGeneratedBlockSigChecks
static const int MAX_COINBASE_SCRIPTSIG_SIZE
Coinbase scripts have their own script size limit.
static constexpr unsigned int LOCKTIME_MEDIAN_TIME_PAST
Use GetMedianTimePast() instead of nTime for end point timestamp.
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...
VersionBitsCache g_versionbitscache
Global cache for versionbits deployment status.
#define LogPrint(category,...)
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Compute the Merkle root of the transactions in a block.
std::vector< CTxDestination > GetMinerFundWhitelist(const Consensus::Params ¶ms, const CBlockIndex *pindexPrev)
Amount GetMinerFundAmount(const Amount &coinbaseValue)
bool ParseMoney(const std::string &money_string, Amount &nRet)
Parse an amount denoted in full coins.
indexed_modified_transaction_set::nth_index< 0 >::type::iterator modtxiter
static const bool DEFAULT_PRINTPRIORITY
indexed_modified_transaction_set::index< ancestor_score >::type::iterator modtxscoreiter
void IncrementExtraNonce(CBlock *pblock, const CBlockIndex *pindexPrev, uint64_t nExcessiveBlockSize, unsigned int &nExtraNonce)
Modify the extranonce in a block.
int64_t UpdateTime(CBlockHeader *pblock, const CChainParams &chainParams, const CBlockIndex *pindexPrev)
static BlockAssembler::Options DefaultOptions(const Config &config)
boost::multi_index_container< CTxMemPoolModifiedEntry, boost::multi_index::indexed_by< boost::multi_index::ordered_unique< modifiedentry_iter, CompareCTxMemPoolIter >, boost::multi_index::ordered_non_unique< boost::multi_index::tag< ancestor_score >, boost::multi_index::identity< CTxMemPoolModifiedEntry >, CompareTxMemPoolEntryByAncestorFee > > > indexed_modified_transaction_set
static const std::vector< uint8_t > getExcessiveBlockSizeSig(uint64_t nExcessiveBlockSize)
std::string getSubVersionEB(uint64_t MaxBlockSize)
This function convert MaxBlockSize from byte to MB with a decimal precision one digit rounded down E....
int64_t GetVirtualTransactionSize(int64_t nSize, int64_t nSigChecks, unsigned int bytes_per_sigCheck)
Compute the virtual transaction size (size, or more if sigChecks are too dense).
static const uint64_t DEFAULT_MAX_GENERATED_BLOCK_SIZE
Default for -blockmaxsize, which controls the maximum size of block the mining code will create.
static const 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...
static constexpr uint32_t STANDARD_LOCKTIME_VERIFY_FLAGS
Used as the flags parameter to sequence and nLocktime checks in non-consensus code.
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)
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
static constexpr Amount zero()
Parameters that influence chain consensus.
bool fPowAllowMinDifficultyBlocks
uint64_t nMaxGeneratedBlockSize
uint64_t nExcessiveBlockSize
uint64_t GetVirtualSizeWithAncestors() const
int64_t nSigChecksWithAncestors
uint64_t nSizeWithAncestors
int64_t GetTimeMicros()
Returns the system time (not mockable)
int64_t GetAdjustedTime()
bool ContextualCheckTransaction(const Consensus::Params ¶ms, const CTransaction &tx, TxValidationState &state, int nHeight, int64_t nLockTimeCutoff)
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, CChainState &chainstate, const CBlock &block, CBlockIndex *pindexPrev, 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