32 while (!staged_ancestors.empty()) {
33 const auto stage = staged_ancestors.begin()->get();
35 txiter stageit = mapTx.find(stage->GetTx().GetId());
36 assert(stageit != mapTx.end());
37 setAncestors.insert(stageit);
38 staged_ancestors.erase(staged_ancestors.begin());
41 (*stageit)->GetMemPoolParentsConst();
42 for (
const auto &parent : parents) {
43 txiter parent_it = mapTx.find(parent.get()->GetTx().GetId());
44 assert(parent_it != mapTx.end());
47 if (setAncestors.count(parent_it) == 0) {
48 staged_ancestors.insert(parent);
58 bool fSearchForParents )
const {
62 if (fSearchForParents) {
71 staged_ancestors.insert(**piter);
76 staged_ancestors = entry->GetMemPoolParentsConst();
84 for (
const auto &parent : (*it)->GetMemPoolParentsConst()) {
85 auto parent_it = mapTx.find(parent.get()->GetTx().GetId());
86 assert(parent_it != mapTx.end());
93 (*it)->GetMemPoolChildrenConst();
94 for (
const auto &child : children) {
95 auto updateIt = mapTx.find(child.get()->GetTx().GetId());
96 assert(updateIt != mapTx.end());
102 for (
txiter removeIt : entriesToRemove) {
112 for (
txiter removeIt : entriesToRemove) {
118 : m_check_ratio(opts.check_ratio), m_max_size_bytes{opts.max_size_bytes},
119 m_expiry{opts.expiry}, m_min_relay_feerate{opts.min_relay_feerate},
120 m_dust_relay_feerate{opts.dust_relay_feerate},
121 m_permit_bare_multisig{opts.permit_bare_multisig},
122 m_max_datacarrier_bytes{opts.max_datacarrier_bytes},
123 m_require_standard{opts.require_standard} {
132 return mapNextTx.count(outpoint);
145 entry->SetEntryId(nextEntryId++);
151 entry->UpdateFeeDelta(feeDelta);
156 auto [newit, inserted] = mapTx.insert(entry);
167 cachedInnerUsage += entry->DynamicMemoryUsage();
170 std::set<TxId> setParentTransactions;
172 mapNextTx.insert(std::make_pair(&in.
prevout, &tx));
180 for (
const auto &pit :
GetIterSet(setParentTransactions)) {
187 totalTxSize += entry->GetTxSize();
188 m_total_fee += entry->GetFee();
196 const TxId &txid = (*it)->GetTx().GetId();
204 (*it)->GetSharedTx(), reason, mempool_sequence);
209 for (
const CTxIn &txin : (*it)->GetTx().vin) {
210 mapNextTx.erase(txin.prevout);
216 totalTxSize -= (*it)->GetTxSize();
217 m_total_fee -= (*it)->GetFee();
218 cachedInnerUsage -= (*it)->DynamicMemoryUsage();
235 if (setDescendants.count(entryit) == 0) {
236 stage.insert(entryit);
241 while (!stage.empty()) {
242 txiter it = *stage.begin();
243 setDescendants.insert(it);
244 stage.erase(stage.begin());
247 (*it)->GetMemPoolChildrenConst();
248 for (
const auto &child : children) {
249 txiter childiter = mapTx.find(child.get()->GetTx().GetId());
250 assert(childiter != mapTx.end());
252 if (!setDescendants.count(childiter)) {
253 stage.insert(childiter);
265 if (origit != mapTx.end()) {
266 txToRemove.insert(origit);
273 while (it != mapNextTx.end() &&
274 it->first->GetTxId() == origTx.
GetId()) {
275 txiter nextit = mapTx.find(it->second->GetId());
276 assert(nextit != mapTx.end());
277 txToRemove.insert(nextit);
283 for (
txiter it : txToRemove) {
294 auto it = mapNextTx.find(txin.
prevout);
295 if (it != mapNextTx.end()) {
297 if (txConflict != tx) {
311 lastRollingFeeUpdate =
GetTime();
312 blockSinceLastRollingFeeBump =
true;
316 const std::vector<CTransactionRef> &vtx) {
319 for (
const auto &tx : vtx) {
333 cachedInnerUsage = 0;
334 lastRollingFeeUpdate =
GetTime();
335 blockSinceLastRollingFeeBump =
false;
336 rollingMinimumFeeRate = 0;
346 int64_t spendheight)
const {
358 "Checking mempool with %u transactions and %u inputs\n",
359 (
unsigned int)mapTx.size(), (
unsigned int)mapNextTx.size());
361 uint64_t checkTotal = 0;
363 uint64_t innerUsage = 0;
369 checkTotal += entry->GetTxSize();
370 check_total_fee += entry->GetFee();
371 innerUsage += entry->DynamicMemoryUsage();
381 if (parentIt != mapTx.end()) {
385 setParentCheck.insert(*parentIt);
388 assert((*parentIt)->GetEntryId() < entry->GetEntryId());
396 auto prevoutNextIt = mapNextTx.find(txin.
prevout);
397 assert(prevoutNextIt != mapNextTx.end());
399 assert(prevoutNextIt->second == &tx);
401 auto comp = [](
const auto &a,
const auto &b) ->
bool {
402 return a.get()->GetTx().GetId() == b.get()->GetTx().GetId();
404 assert(setParentCheck.size() == entry->GetMemPoolParentsConst().size());
405 assert(std::equal(setParentCheck.begin(), setParentCheck.end(),
406 entry->GetMemPoolParentsConst().begin(), comp));
416 for (
const auto &ancestor : setAncestors) {
417 assert((*ancestor)->GetEntryId() < entry->GetEntryId());
422 auto iter = mapNextTx.lower_bound(
COutPoint(entry->GetTx().GetId(), 0));
423 for (; iter != mapNextTx.end() &&
424 iter->first->GetTxId() == entry->GetTx().GetId();
426 txiter childIt = mapTx.find(iter->second->GetId());
428 assert(childIt != mapTx.end());
429 setChildrenCheck.insert(*childIt);
431 assert(setChildrenCheck.size() ==
432 entry->GetMemPoolChildrenConst().size());
433 assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(),
434 entry->GetMemPoolChildrenConst().begin(), comp));
441 spendheight, txfee));
442 for (
const auto &input : tx.
vin) {
443 mempoolDuplicate.SpendCoin(input.prevout);
445 AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
448 for (
auto &[
_, nextTx] : mapNextTx) {
449 txiter it = mapTx.find(nextTx->GetId());
450 assert(it != mapTx.end());
451 assert(&(*it)->GetTx() == nextTx);
454 assert(totalTxSize == checkTotal);
455 assert(m_total_fee == check_total_fee);
456 assert(innerUsage == cachedInnerUsage);
460 const TxId &txidb)
const {
462 auto it1 = mapTx.find(txida);
463 if (it1 == mapTx.end()) {
466 auto it2 = mapTx.find(txidb);
467 if (it2 == mapTx.end()) {
470 return (*it1)->GetEntryId() < (*it2)->GetEntryId();
477 vtxid.reserve(mapTx.size());
480 vtxid.push_back(entry->GetTx().GetId());
485 GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it) {
487 (*it)->GetFee(), (*it)->GetTxSize(),
488 (*it)->GetModifiedFee() - (*it)->GetFee()};
494 std::vector<TxMempoolInfo> ret;
495 ret.reserve(mapTx.size());
497 const auto &index = mapTx.get<
entry_id>();
498 for (
auto it = index.begin(); it != index.end(); ++it) {
499 ret.push_back(
GetInfo(mapTx.project<0>(it)));
507 indexed_transaction_set::const_iterator i = mapTx.find(txid);
508 if (i == mapTx.end()) {
512 return (*i)->GetSharedTx();
517 indexed_transaction_set::const_iterator i = mapTx.find(txid);
518 if (i == mapTx.end()) {
539 Amount &delta = mapDeltas[txid];
541 txiter it = mapTx.find(txid);
542 if (it != mapTx.end()) {
544 e->UpdateFeeDelta(delta);
555 std::map<TxId, Amount>::const_iterator pos = mapDeltas.find(txid);
556 if (pos == mapDeltas.end()) {
560 nFeeDelta += pos->second;
565 mapDeltas.erase(txid);
569 const auto it = mapNextTx.find(prevout);
570 return it == mapNextTx.end() ? nullptr : it->second;
574 auto it = mapTx.find(txid);
575 if (it != mapTx.end()) {
584 for (
const auto &txid : txids) {
621 if (outpoint.
GetN() < ptx->vout.size()) {
632 for (uint32_t n = 0; n < tx->vout.size(); ++n) {
648 12 *
sizeof(
void *)) *
657 if (m_unbroadcast_txids.erase(txid)) {
661 (unchecked ?
" before confirmation that txn was sent out" :
""));
672 for (
txiter it : stageRevTopo) {
679 indexed_transaction_set::index<entry_time>::type::iterator it =
682 while (it != mapTx.get<
entry_time>().end() && (*it)->GetTime() < time) {
683 toremove.insert(mapTx.project<0>(it));
688 for (
txiter removeit : toremove) {
702 "Expired %i transactions from the memory pool\n", expired);
705 std::vector<COutPoint> vNoSpendsRemaining;
707 for (
const COutPoint &removed : vNoSpendsRemaining) {
715 if (add && (*entry)->GetMemPoolChildren().insert(*child).second) {
717 }
else if (!add && (*entry)->GetMemPoolChildren().erase(*child)) {
725 if (add && (*entry)->GetMemPoolParents().insert(*parent).second) {
727 }
else if (!add && (*entry)->GetMemPoolParents().erase(*parent)) {
734 if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0) {
739 if (time > lastRollingFeeUpdate + 10) {
747 rollingMinimumFeeRate =
748 rollingMinimumFeeRate /
749 pow(2.0, (time - lastRollingFeeUpdate) / halflife);
750 lastRollingFeeUpdate = time;
759 blockSinceLastRollingFeeBump =
false;
764 std::vector<COutPoint> *pvNoSpendsRemaining) {
767 unsigned nTxnRemoved = 0;
778 CFeeRate removed = (*it)->GetModifiedFeeRate();
782 maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
786 nTxnRemoved += stage.size();
788 if (pvNoSpendsRemaining) {
789 for (
const txiter &iter : stage) {
790 for (
const CTxIn &txin : (*iter)->GetTx().vin) {
792 pvNoSpendsRemaining->push_back(txin.
prevout);
803 "Removed %u txn, rolling minimum fee bumped to %s\n",
804 nTxnRemoved, maxFeeRateRemoved.
ToString());
815 m_load_tried = load_tried;
static constexpr Amount SATOSHI
CCoinsView backed by another CCoinsView.
CCoinsView that adds a memory cache for transactions to another CCoinsView.
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Abstract view on the open txout dataset.
virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
GetCoin, returning whether it exists and is not spent.
void Reset()
Clear m_temp_added and m_non_base_coins.
std::unordered_map< COutPoint, Coin, SaltedOutpointHasher > m_temp_added
Coins made available by transactions being validated.
CCoinsViewMemPool(CCoinsView *baseIn, const CTxMemPool &mempoolIn)
std::unordered_set< COutPoint, SaltedOutpointHasher > m_non_base_coins
Set of all coins that have been fetched from mempool or created using PackageAddTransaction (not base...
void PackageAddTransaction(const CTransactionRef &tx)
Add the coins created by this transaction.
const CTxMemPool & mempool
Fee rate in satoshis per kilobyte: Amount / kB.
std::string ToString() const
Amount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
void TransactionRemovedFromMempool(const CTransactionRef &, MemPoolRemovalReason, uint64_t mempool_sequence)
An outpoint - a combination of a transaction hash and an index n into its vout.
const TxId & GetTxId() const
The basic transaction that is broadcasted on the network and contained in blocks.
const std::vector< CTxOut > vout
const std::vector< CTxIn > vin
An input of a transaction.
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
std::set< std::reference_wrapper< const CTxMemPoolEntryRef >, CompareIteratorById > Children
std::set< std::reference_wrapper< const CTxMemPoolEntryRef >, CompareIteratorById > Parents
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
void removeConflicts(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(cs)
CFeeRate estimateFee() const
bool HasNoInputsOf(const CTransaction &tx) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Check that none of this transactions inputs are in the mempool, and thus the tx is not dependent on o...
void ClearPrioritisation(const TxId &txid) EXCLUSIVE_LOCKS_REQUIRED(cs)
std::set< txiter, CompareIteratorById > setEntries
void RemoveUnbroadcastTx(const TxId &txid, const bool unchecked=false)
Removes a transaction from the unbroadcast set.
bool GetLoadTried() const
bool CalculateAncestors(setEntries &setAncestors, CTxMemPoolEntry::Parents &staged_ancestors) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Helper function to calculate all in-mempool ancestors of staged_ancestors param@[in] staged_ancestors...
void updateFeeForBlock() EXCLUSIVE_LOCKS_REQUIRED(cs)
Called when a block is connected.
CFeeRate GetMinFee() const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
void trackPackageRemoved(const CFeeRate &rate) EXCLUSIVE_LOCKS_REQUIRED(cs)
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
void UpdateForRemoveFromMempool(const setEntries &entriesToRemove) EXCLUSIVE_LOCKS_REQUIRED(cs)
For each transaction being removed, update ancestors and any direct children.
const int m_check_ratio
Value n means that 1 times in n we check.
void TrimToSize(size_t sizelimit, std::vector< COutPoint > *pvNoSpendsRemaining=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs)
Remove transactions from the mempool until its dynamic size is <= sizelimit.
const std::chrono::seconds m_expiry
void AddTransactionsUpdated(unsigned int n)
void UpdateChildrenForRemoval(txiter entry) EXCLUSIVE_LOCKS_REQUIRED(cs)
Sever link between specified transaction and direct children.
bool CompareTopologically(const TxId &txida, const TxId &txidb) const
TxMempoolInfo info(const TxId &txid) const
const int64_t m_max_size_bytes
void getAllTxIds(std::vector< TxId > &vtxid) const
std::atomic< uint32_t > nTransactionsUpdated
Used by getblocktemplate to trigger CreateNewBlock() invocation.
setEntries GetIterSet(const std::set< TxId > &txids) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Translate a set of txids into a set of pool iterators to avoid repeated lookups.
size_t DynamicMemoryUsage() const
std::vector< TxMempoolInfo > infoAll() const
void LimitSize(CCoinsViewCache &coins_cache) EXCLUSIVE_LOCKS_REQUIRED(cs
Reduce the size of the mempool by expiring and then trimming the mempool.
void UpdateParent(txiter entry, txiter parent, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs)
void removeUnchecked(txiter entry, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Before calling removeUnchecked for a given transaction, UpdateForRemoveFromMempool must be called on ...
int Expire(std::chrono::seconds time) EXCLUSIVE_LOCKS_REQUIRED(cs)
Expire all transaction (and their dependencies) in the mempool older than time.
std::set< txiter, CompareIteratorByRevEntryId > setRevTopoEntries
bool exists(const TxId &txid) const
static const int ROLLING_FEE_HALFLIFE
CTransactionRef get(const TxId &txid) const
const CFeeRate m_min_relay_feerate
void PrioritiseTransaction(const TxId &txid, const Amount nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
uint64_t GetAndIncrementSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Guards this internal counter for external reporting.
void UpdateChild(txiter entry, txiter child, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs)
void check(const CCoinsViewCache &active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(void addUnchecked(CTxMemPoolEntryRef entry) EXCLUSIVE_LOCKS_REQUIRED(cs
If sanity-checking is turned on, check makes sure the pool is consistent (does not contain two transa...
RadixTree< CTxMemPoolEntry, MemPoolEntryRadixTreeAdapter > finalizedTxs
CTxMemPool(const Options &opts)
Create a new CTxMemPool.
const CTransaction * GetConflictTx(const COutPoint &prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Get the transaction in the pool that spends the same prevout.
bool CalculateMemPoolAncestors(const CTxMemPoolEntryRef &entry, setEntries &setAncestors, bool fSearchForParents=true) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Try to calculate all in-mempool ancestors of entry.
void removeForFinalizedBlock(const std::vector< CTransactionRef > &vtx) EXCLUSIVE_LOCKS_REQUIRED(cs)
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
void RemoveStaged(const setEntries &stage, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Remove a set of transactions from the mempool.
void UpdateParentsOf(bool add, txiter it) EXCLUSIVE_LOCKS_REQUIRED(cs)
Update parents of it to add/remove it as a child transaction.
void ApplyDelta(const TxId &txid, Amount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs)
void SetLoadTried(bool load_tried)
Set whether or not we've made an attempt to load the mempool (regardless of whether the attempt was s...
std::optional< txiter > GetIter(const TxId &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given txid, if found.
void check(const CCoinsViewCache &active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(void cs_main
bool isSpent(const COutPoint &outpoint) const
unsigned int GetTransactionsUpdated() const
void _clear() EXCLUSIVE_LOCKS_REQUIRED(cs)
T * get()
Get allows to access the undelying pointer.
std::string ToString() const
std::string GetHex() const
void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight, bool check_for_overwrite)
Utility function to add all of a transaction's outputs to a cache.
#define LogPrint(category,...)
std::string FormatMoney(const Amount amt)
Do not use these functions to represent or parse monetary amounts to or from JSON but use AmountFromV...
bool CheckTxInputs(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight, Amount &txfee)
Check whether all inputs of this transaction are valid (no double spends and amounts).
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
static size_t IncrementalDynamicUsage(const std::set< X, Y > &s)
static size_t MallocUsage(size_t alloc)
Compute the total memory used by allocating alloc bytes.
static constexpr CFeeRate MEMPOOL_FULL_FEE_INCREMENT(1000 *SATOSHI)
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or BIP...
std::shared_ptr< const CTransaction > CTransactionRef
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
static constexpr Amount zero() noexcept
RCUPtr< T > remove(const KeyType &key)
Remove an element from the tree.
A TxId is the identifier of a transaction.
Information about a mempool transaction.
Options struct containing options for constructing a CTxMemPool.
bilingual_str _(const char *psz)
Translation function.
static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it)
const std::string RemovalReasonToString(const MemPoolRemovalReason &r) noexcept
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
@ SIZELIMIT
Removed in size limiting.
@ BLOCK
Removed for block.
@ EXPIRY
Expired from mempool.
@ AVALANCHE
Removed by avalanche vote.
@ CONFLICT
Removed for conflict with in-block transaction.
@ REORG
Removed for reorganization.
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coins to signify they are only in the memory pool(since 0....
CMainSignals & GetMainSignals()