Branch data Line data Source code
# 1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
# 2 : : // Copyright (c) 2009-2021 The Bitcoin Core developers
# 3 : : // Distributed under the MIT software license, see the accompanying
# 4 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
# 5 : :
# 6 : : #ifndef BITCOIN_TXMEMPOOL_H
# 7 : : #define BITCOIN_TXMEMPOOL_H
# 8 : :
# 9 : : #include <atomic>
# 10 : : #include <map>
# 11 : : #include <optional>
# 12 : : #include <set>
# 13 : : #include <string>
# 14 : : #include <utility>
# 15 : : #include <vector>
# 16 : :
# 17 : : #include <coins.h>
# 18 : : #include <consensus/amount.h>
# 19 : : #include <indirectmap.h>
# 20 : : #include <policy/feerate.h>
# 21 : : #include <policy/packages.h>
# 22 : : #include <primitives/transaction.h>
# 23 : : #include <random.h>
# 24 : : #include <sync.h>
# 25 : : #include <util/epochguard.h>
# 26 : : #include <util/hasher.h>
# 27 : :
# 28 : : #include <boost/multi_index/hashed_index.hpp>
# 29 : : #include <boost/multi_index/ordered_index.hpp>
# 30 : : #include <boost/multi_index/sequenced_index.hpp>
# 31 : : #include <boost/multi_index_container.hpp>
# 32 : :
# 33 : : class CBlockIndex;
# 34 : : class CChain;
# 35 : : class CChainState;
# 36 : : extern RecursiveMutex cs_main;
# 37 : :
# 38 : : /** Fake height value used in Coin to signify they are only in the memory pool (since 0.8) */
# 39 : : static const uint32_t MEMPOOL_HEIGHT = 0x7FFFFFFF;
# 40 : :
# 41 : : struct LockPoints {
# 42 : : // Will be set to the blockchain height and median time past
# 43 : : // values that would be necessary to satisfy all relative locktime
# 44 : : // constraints (BIP68) of this tx given our view of block chain history
# 45 : : int height{0};
# 46 : : int64_t time{0};
# 47 : : // As long as the current chain descends from the highest height block
# 48 : : // containing one of the inputs used in the calculation, then the cached
# 49 : : // values are still valid even after a reorg.
# 50 : : CBlockIndex* maxInputBlock{nullptr};
# 51 : : };
# 52 : :
# 53 : : /**
# 54 : : * Test whether the LockPoints height and time are still valid on the current chain
# 55 : : */
# 56 : : bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
# 57 : :
# 58 : : struct CompareIteratorByHash {
# 59 : : // SFINAE for T where T is either a pointer type (e.g., a txiter) or a reference_wrapper<T>
# 60 : : // (e.g. a wrapped CTxMemPoolEntry&)
# 61 : : template <typename T>
# 62 : : bool operator()(const std::reference_wrapper<T>& a, const std::reference_wrapper<T>& b) const
# 63 : 11841376 : {
# 64 : 11841376 : return a.get().GetTx().GetHash() < b.get().GetTx().GetHash();
# 65 : 11841376 : }
# 66 : : template <typename T>
# 67 : : bool operator()(const T& a, const T& b) const
# 68 : 136713385 : {
# 69 : 136713385 : return a->GetTx().GetHash() < b->GetTx().GetHash();
# 70 : 136713385 : }
# 71 : : };
# 72 : :
# 73 : : /** \class CTxMemPoolEntry
# 74 : : *
# 75 : : * CTxMemPoolEntry stores data about the corresponding transaction, as well
# 76 : : * as data about all in-mempool transactions that depend on the transaction
# 77 : : * ("descendant" transactions).
# 78 : : *
# 79 : : * When a new entry is added to the mempool, we update the descendant state
# 80 : : * (nCountWithDescendants, nSizeWithDescendants, and nModFeesWithDescendants) for
# 81 : : * all ancestors of the newly added transaction.
# 82 : : *
# 83 : : */
# 84 : :
# 85 : : class CTxMemPoolEntry
# 86 : : {
# 87 : : public:
# 88 : : typedef std::reference_wrapper<const CTxMemPoolEntry> CTxMemPoolEntryRef;
# 89 : : // two aliases, should the types ever diverge
# 90 : : typedef std::set<CTxMemPoolEntryRef, CompareIteratorByHash> Parents;
# 91 : : typedef std::set<CTxMemPoolEntryRef, CompareIteratorByHash> Children;
# 92 : :
# 93 : : private:
# 94 : : const CTransactionRef tx;
# 95 : : mutable Parents m_parents;
# 96 : : mutable Children m_children;
# 97 : : const CAmount nFee; //!< Cached to avoid expensive parent-transaction lookups
# 98 : : const size_t nTxWeight; //!< ... and avoid recomputing tx weight (also used for GetTxSize())
# 99 : : const size_t nUsageSize; //!< ... and total memory usage
# 100 : : const int64_t nTime; //!< Local time when entering the mempool
# 101 : : const unsigned int entryHeight; //!< Chain height when entering the mempool
# 102 : : const bool spendsCoinbase; //!< keep track of transactions that spend a coinbase
# 103 : : const int64_t sigOpCost; //!< Total sigop cost
# 104 : : CAmount feeDelta{0}; //!< Used for determining the priority of the transaction for mining in a block
# 105 : : LockPoints lockPoints; //!< Track the height and time at which tx was final
# 106 : :
# 107 : : // Information about descendants of this transaction that are in the
# 108 : : // mempool; if we remove this transaction we must remove all of these
# 109 : : // descendants as well.
# 110 : : uint64_t nCountWithDescendants{1}; //!< number of descendant transactions
# 111 : : uint64_t nSizeWithDescendants; //!< ... and size
# 112 : : CAmount nModFeesWithDescendants; //!< ... and total fees (all including us)
# 113 : :
# 114 : : // Analogous statistics for ancestor transactions
# 115 : : uint64_t nCountWithAncestors{1};
# 116 : : uint64_t nSizeWithAncestors;
# 117 : : CAmount nModFeesWithAncestors;
# 118 : : int64_t nSigOpCostWithAncestors;
# 119 : :
# 120 : : public:
# 121 : : CTxMemPoolEntry(const CTransactionRef& tx, CAmount fee,
# 122 : : int64_t time, unsigned int entry_height,
# 123 : : bool spends_coinbase,
# 124 : : int64_t sigops_cost, LockPoints lp);
# 125 : :
# 126 : 565609054 : const CTransaction& GetTx() const { return *this->tx; }
# 127 : 118050 : CTransactionRef GetSharedTx() const { return this->tx; }
# 128 : 277670405 : const CAmount& GetFee() const { return nFee; }
# 129 : : size_t GetTxSize() const;
# 130 : 13679 : size_t GetTxWeight() const { return nTxWeight; }
# 131 : 62662565 : std::chrono::seconds GetTime() const { return std::chrono::seconds{nTime}; }
# 132 : 139728 : unsigned int GetHeight() const { return entryHeight; }
# 133 : 14225775 : int64_t GetSigOpCost() const { return sigOpCost; }
# 134 : 144967475 : CAmount GetModifiedFee() const { return nFee + feeDelta; }
# 135 : 11155268 : size_t DynamicMemoryUsage() const { return nUsageSize; }
# 136 : 1610 : const LockPoints& GetLockPoints() const { return lockPoints; }
# 137 : :
# 138 : : // Adjusts the descendant state.
# 139 : : void UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount);
# 140 : : // Adjusts the ancestor state
# 141 : : void UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int64_t modifySigOps);
# 142 : : // Updates the fee delta used for mining priority score, and the
# 143 : : // modified fees with descendants/ancestors.
# 144 : : void UpdateFeeDelta(CAmount newFeeDelta);
# 145 : : // Update the LockPoints after a reorg
# 146 : : void UpdateLockPoints(const LockPoints& lp);
# 147 : :
# 148 : 3065488 : uint64_t GetCountWithDescendants() const { return nCountWithDescendants; }
# 149 : 67881204 : uint64_t GetSizeWithDescendants() const { return nSizeWithDescendants; }
# 150 : 54212508 : CAmount GetModFeesWithDescendants() const { return nModFeesWithDescendants; }
# 151 : :
# 152 : 805 : bool GetSpendsCoinbase() const { return spendsCoinbase; }
# 153 : :
# 154 : 300153058 : uint64_t GetCountWithAncestors() const { return nCountWithAncestors; }
# 155 : 20420243 : uint64_t GetSizeWithAncestors() const { return nSizeWithAncestors; }
# 156 : 20416479 : CAmount GetModFeesWithAncestors() const { return nModFeesWithAncestors; }
# 157 : 11056754 : int64_t GetSigOpCostWithAncestors() const { return nSigOpCostWithAncestors; }
# 158 : :
# 159 : 36590153 : const Parents& GetMemPoolParentsConst() const { return m_parents; }
# 160 : 35299644 : const Children& GetMemPoolChildrenConst() const { return m_children; }
# 161 : 15331 : Parents& GetMemPoolParents() const { return m_parents; }
# 162 : 13199 : Children& GetMemPoolChildren() const { return m_children; }
# 163 : :
# 164 : : mutable size_t vTxHashesIdx; //!< Index in mempool's vTxHashes
# 165 : : mutable Epoch::Marker m_epoch_marker; //!< epoch when last touched, useful for graph algorithms
# 166 : : };
# 167 : :
# 168 : : // extracts a transaction hash from CTxMemPoolEntry or CTransactionRef
# 169 : : struct mempoolentry_txid
# 170 : : {
# 171 : : typedef uint256 result_type;
# 172 : : result_type operator() (const CTxMemPoolEntry &entry) const
# 173 : 53725249 : {
# 174 : 53725249 : return entry.GetTx().GetHash();
# 175 : 53725249 : }
# 176 : :
# 177 : : result_type operator() (const CTransactionRef& tx) const
# 178 : 33194 : {
# 179 : 33194 : return tx->GetHash();
# 180 : 33194 : }
# 181 : : };
# 182 : :
# 183 : : // extracts a transaction witness-hash from CTxMemPoolEntry or CTransactionRef
# 184 : : struct mempoolentry_wtxid
# 185 : : {
# 186 : : typedef uint256 result_type;
# 187 : : result_type operator() (const CTxMemPoolEntry &entry) const
# 188 : 5624963 : {
# 189 : 5624963 : return entry.GetTx().GetWitnessHash();
# 190 : 5624963 : }
# 191 : :
# 192 : : result_type operator() (const CTransactionRef& tx) const
# 193 : 0 : {
# 194 : 0 : return tx->GetWitnessHash();
# 195 : 0 : }
# 196 : : };
# 197 : :
# 198 : :
# 199 : : /** \class CompareTxMemPoolEntryByDescendantScore
# 200 : : *
# 201 : : * Sort an entry by max(score/size of entry's tx, score/size with all descendants).
# 202 : : */
# 203 : : class CompareTxMemPoolEntryByDescendantScore
# 204 : : {
# 205 : : public:
# 206 : : bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
# 207 : 27091234 : {
# 208 : 27091234 : double a_mod_fee, a_size, b_mod_fee, b_size;
# 209 : :
# 210 : 27091234 : GetModFeeAndSize(a, a_mod_fee, a_size);
# 211 : 27091234 : GetModFeeAndSize(b, b_mod_fee, b_size);
# 212 : :
# 213 : : // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
# 214 : 27091234 : double f1 = a_mod_fee * b_size;
# 215 : 27091234 : double f2 = a_size * b_mod_fee;
# 216 : :
# 217 [ + + ]: 27091234 : if (f1 == f2) {
# 218 : 26544430 : return a.GetTime() >= b.GetTime();
# 219 : 26544430 : }
# 220 : 546804 : return f1 < f2;
# 221 : 27091234 : }
# 222 : :
# 223 : : // Return the fee/size we're using for sorting this entry.
# 224 : : void GetModFeeAndSize(const CTxMemPoolEntry &a, double &mod_fee, double &size) const
# 225 : 54182468 : {
# 226 : : // Compare feerate with descendants to feerate of the transaction, and
# 227 : : // return the fee/size for the max.
# 228 : 54182468 : double f1 = (double)a.GetModifiedFee() * a.GetSizeWithDescendants();
# 229 : 54182468 : double f2 = (double)a.GetModFeesWithDescendants() * a.GetTxSize();
# 230 : :
# 231 [ + + ]: 54182468 : if (f2 > f1) {
# 232 : 28670 : mod_fee = a.GetModFeesWithDescendants();
# 233 : 28670 : size = a.GetSizeWithDescendants();
# 234 : 54153798 : } else {
# 235 : 54153798 : mod_fee = a.GetModifiedFee();
# 236 : 54153798 : size = a.GetTxSize();
# 237 : 54153798 : }
# 238 : 54182468 : }
# 239 : : };
# 240 : :
# 241 : : /** \class CompareTxMemPoolEntryByScore
# 242 : : *
# 243 : : * Sort by feerate of entry (fee/size) in descending order
# 244 : : * This is only used for transaction relay, so we use GetFee()
# 245 : : * instead of GetModifiedFee() to avoid leaking prioritization
# 246 : : * information via the sort order.
# 247 : : */
# 248 : : class CompareTxMemPoolEntryByScore
# 249 : : {
# 250 : : public:
# 251 : : bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
# 252 : 132904148 : {
# 253 : 132904148 : double f1 = (double)a.GetFee() * b.GetTxSize();
# 254 : 132904148 : double f2 = (double)b.GetFee() * a.GetTxSize();
# 255 [ + + ]: 132904148 : if (f1 == f2) {
# 256 : 69257949 : return b.GetTx().GetHash() < a.GetTx().GetHash();
# 257 : 69257949 : }
# 258 : 63646199 : return f1 > f2;
# 259 : 132904148 : }
# 260 : : };
# 261 : :
# 262 : : class CompareTxMemPoolEntryByEntryTime
# 263 : : {
# 264 : : public:
# 265 : : bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
# 266 : 4763038 : {
# 267 : 4763038 : return a.GetTime() < b.GetTime();
# 268 : 4763038 : }
# 269 : : };
# 270 : :
# 271 : : /** \class CompareTxMemPoolEntryByAncestorScore
# 272 : : *
# 273 : : * Sort an entry by min(score/size of entry's tx, score/size with all ancestors).
# 274 : : */
# 275 : : class CompareTxMemPoolEntryByAncestorFee
# 276 : : {
# 277 : : public:
# 278 : : template<typename T>
# 279 : : bool operator()(const T& a, const T& b) const
# 280 : 5690979 : {
# 281 : 5690979 : double a_mod_fee, a_size, b_mod_fee, b_size;
# 282 : :
# 283 : 5690979 : GetModFeeAndSize(a, a_mod_fee, a_size);
# 284 : 5690979 : GetModFeeAndSize(b, b_mod_fee, b_size);
# 285 : :
# 286 : : // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
# 287 : 5690979 : double f1 = a_mod_fee * b_size;
# 288 : 5690979 : double f2 = a_size * b_mod_fee;
# 289 : :
# 290 [ + + ][ + + ]: 5690979 : if (f1 == f2) {
# 291 : 5348070 : return a.GetTx().GetHash() < b.GetTx().GetHash();
# 292 : 5348070 : }
# 293 : 342909 : return f1 > f2;
# 294 : 5690979 : }
# 295 : :
# 296 : : // Return the fee/size we're using for sorting this entry.
# 297 : : template <typename T>
# 298 : : void GetModFeeAndSize(const T &a, double &mod_fee, double &size) const
# 299 : 11381958 : {
# 300 : : // Compare feerate with ancestors to feerate of the transaction, and
# 301 : : // return the fee/size for the min.
# 302 : 11381958 : double f1 = (double)a.GetModifiedFee() * a.GetSizeWithAncestors();
# 303 : 11381958 : double f2 = (double)a.GetModFeesWithAncestors() * a.GetTxSize();
# 304 : :
# 305 [ + + ][ + + ]: 11381958 : if (f1 > f2) {
# 306 : 13451 : mod_fee = a.GetModFeesWithAncestors();
# 307 : 13451 : size = a.GetSizeWithAncestors();
# 308 : 11368507 : } else {
# 309 : 11368507 : mod_fee = a.GetModifiedFee();
# 310 : 11368507 : size = a.GetTxSize();
# 311 : 11368507 : }
# 312 : 11381958 : }
# 313 : : };
# 314 : :
# 315 : : // Multi_index tag names
# 316 : : struct descendant_score {};
# 317 : : struct entry_time {};
# 318 : : struct ancestor_score {};
# 319 : : struct index_by_wtxid {};
# 320 : :
# 321 : : class CBlockPolicyEstimator;
# 322 : :
# 323 : : /**
# 324 : : * Information about a mempool transaction.
# 325 : : */
# 326 : : struct TxMempoolInfo
# 327 : : {
# 328 : : /** The transaction itself */
# 329 : : CTransactionRef tx;
# 330 : :
# 331 : : /** Time the transaction entered the mempool. */
# 332 : : std::chrono::seconds m_time;
# 333 : :
# 334 : : /** Fee of the transaction. */
# 335 : : CAmount fee;
# 336 : :
# 337 : : /** Virtual size of the transaction. */
# 338 : : size_t vsize;
# 339 : :
# 340 : : /** The fee delta. */
# 341 : : int64_t nFeeDelta;
# 342 : : };
# 343 : :
# 344 : : /** Reason why a transaction was removed from the mempool,
# 345 : : * this is passed to the notification signal.
# 346 : : */
# 347 : : enum class MemPoolRemovalReason {
# 348 : : EXPIRY, //!< Expired from mempool
# 349 : : SIZELIMIT, //!< Removed in size limiting
# 350 : : REORG, //!< Removed for reorganization
# 351 : : BLOCK, //!< Removed for block
# 352 : : CONFLICT, //!< Removed for conflict with in-block transaction
# 353 : : REPLACED, //!< Removed for replacement
# 354 : : };
# 355 : :
# 356 : : /**
# 357 : : * CTxMemPool stores valid-according-to-the-current-best-chain transactions
# 358 : : * that may be included in the next block.
# 359 : : *
# 360 : : * Transactions are added when they are seen on the network (or created by the
# 361 : : * local node), but not all transactions seen are added to the pool. For
# 362 : : * example, the following new transactions will not be added to the mempool:
# 363 : : * - a transaction which doesn't meet the minimum fee requirements.
# 364 : : * - a new transaction that double-spends an input of a transaction already in
# 365 : : * the pool where the new transaction does not meet the Replace-By-Fee
# 366 : : * requirements as defined in BIP 125.
# 367 : : * - a non-standard transaction.
# 368 : : *
# 369 : : * CTxMemPool::mapTx, and CTxMemPoolEntry bookkeeping:
# 370 : : *
# 371 : : * mapTx is a boost::multi_index that sorts the mempool on 5 criteria:
# 372 : : * - transaction hash (txid)
# 373 : : * - witness-transaction hash (wtxid)
# 374 : : * - descendant feerate [we use max(feerate of tx, feerate of tx with all descendants)]
# 375 : : * - time in mempool
# 376 : : * - ancestor feerate [we use min(feerate of tx, feerate of tx with all unconfirmed ancestors)]
# 377 : : *
# 378 : : * Note: the term "descendant" refers to in-mempool transactions that depend on
# 379 : : * this one, while "ancestor" refers to in-mempool transactions that a given
# 380 : : * transaction depends on.
# 381 : : *
# 382 : : * In order for the feerate sort to remain correct, we must update transactions
# 383 : : * in the mempool when new descendants arrive. To facilitate this, we track
# 384 : : * the set of in-mempool direct parents and direct children in mapLinks. Within
# 385 : : * each CTxMemPoolEntry, we track the size and fees of all descendants.
# 386 : : *
# 387 : : * Usually when a new transaction is added to the mempool, it has no in-mempool
# 388 : : * children (because any such children would be an orphan). So in
# 389 : : * addUnchecked(), we:
# 390 : : * - update a new entry's setMemPoolParents to include all in-mempool parents
# 391 : : * - update the new entry's direct parents to include the new tx as a child
# 392 : : * - update all ancestors of the transaction to include the new tx's size/fee
# 393 : : *
# 394 : : * When a transaction is removed from the mempool, we must:
# 395 : : * - update all in-mempool parents to not track the tx in setMemPoolChildren
# 396 : : * - update all ancestors to not include the tx's size/fees in descendant state
# 397 : : * - update all in-mempool children to not include it as a parent
# 398 : : *
# 399 : : * These happen in UpdateForRemoveFromMempool(). (Note that when removing a
# 400 : : * transaction along with its descendants, we must calculate that set of
# 401 : : * transactions to be removed before doing the removal, or else the mempool can
# 402 : : * be in an inconsistent state where it's impossible to walk the ancestors of
# 403 : : * a transaction.)
# 404 : : *
# 405 : : * In the event of a reorg, the assumption that a newly added tx has no
# 406 : : * in-mempool children is false. In particular, the mempool is in an
# 407 : : * inconsistent state while new transactions are being added, because there may
# 408 : : * be descendant transactions of a tx coming from a disconnected block that are
# 409 : : * unreachable from just looking at transactions in the mempool (the linking
# 410 : : * transactions may also be in the disconnected block, waiting to be added).
# 411 : : * Because of this, there's not much benefit in trying to search for in-mempool
# 412 : : * children in addUnchecked(). Instead, in the special case of transactions
# 413 : : * being added from a disconnected block, we require the caller to clean up the
# 414 : : * state, to account for in-mempool, out-of-block descendants for all the
# 415 : : * in-block transactions by calling UpdateTransactionsFromBlock(). Note that
# 416 : : * until this is called, the mempool state is not consistent, and in particular
# 417 : : * mapLinks may not be correct (and therefore functions like
# 418 : : * CalculateMemPoolAncestors() and CalculateDescendants() that rely
# 419 : : * on them to walk the mempool are not generally safe to use).
# 420 : : *
# 421 : : * Computational limits:
# 422 : : *
# 423 : : * Updating all in-mempool ancestors of a newly added transaction can be slow,
# 424 : : * if no bound exists on how many in-mempool ancestors there may be.
# 425 : : * CalculateMemPoolAncestors() takes configurable limits that are designed to
# 426 : : * prevent these calculations from being too CPU intensive.
# 427 : : *
# 428 : : */
# 429 : : class CTxMemPool
# 430 : : {
# 431 : : protected:
# 432 : : const int m_check_ratio; //!< Value n means that 1 times in n we check.
# 433 : : std::atomic<unsigned int> nTransactionsUpdated{0}; //!< Used by getblocktemplate to trigger CreateNewBlock() invocation
# 434 : : CBlockPolicyEstimator* const minerPolicyEstimator;
# 435 : :
# 436 : : uint64_t totalTxSize GUARDED_BY(cs); //!< sum of all mempool tx's virtual sizes. Differs from serialized tx size since witness data is discounted. Defined in BIP 141.
# 437 : : CAmount m_total_fee GUARDED_BY(cs); //!< sum of all mempool tx's fees (NOT modified fee)
# 438 : : uint64_t cachedInnerUsage GUARDED_BY(cs); //!< sum of dynamic memory usage of all the map elements (NOT the maps themselves)
# 439 : :
# 440 : : mutable int64_t lastRollingFeeUpdate GUARDED_BY(cs);
# 441 : : mutable bool blockSinceLastRollingFeeBump GUARDED_BY(cs);
# 442 : : mutable double rollingMinimumFeeRate GUARDED_BY(cs); //!< minimum fee to get into the pool, decreases exponentially
# 443 : : mutable Epoch m_epoch GUARDED_BY(cs);
# 444 : :
# 445 : : // In-memory counter for external mempool tracking purposes.
# 446 : : // This number is incremented once every time a transaction
# 447 : : // is added or removed from the mempool for any reason.
# 448 : : mutable uint64_t m_sequence_number GUARDED_BY(cs){1};
# 449 : :
# 450 : : void trackPackageRemoved(const CFeeRate& rate) EXCLUSIVE_LOCKS_REQUIRED(cs);
# 451 : :
# 452 : : bool m_is_loaded GUARDED_BY(cs){false};
# 453 : :
# 454 : : public:
# 455 : :
# 456 : : static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12; // public only for testing
# 457 : :
# 458 : : typedef boost::multi_index_container<
# 459 : : CTxMemPoolEntry,
# 460 : : boost::multi_index::indexed_by<
# 461 : : // sorted by txid
# 462 : : boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>,
# 463 : : // sorted by wtxid
# 464 : : boost::multi_index::hashed_unique<
# 465 : : boost::multi_index::tag<index_by_wtxid>,
# 466 : : mempoolentry_wtxid,
# 467 : : SaltedTxidHasher
# 468 : : >,
# 469 : : // sorted by fee rate
# 470 : : boost::multi_index::ordered_non_unique<
# 471 : : boost::multi_index::tag<descendant_score>,
# 472 : : boost::multi_index::identity<CTxMemPoolEntry>,
# 473 : : CompareTxMemPoolEntryByDescendantScore
# 474 : : >,
# 475 : : // sorted by entry time
# 476 : : boost::multi_index::ordered_non_unique<
# 477 : : boost::multi_index::tag<entry_time>,
# 478 : : boost::multi_index::identity<CTxMemPoolEntry>,
# 479 : : CompareTxMemPoolEntryByEntryTime
# 480 : : >,
# 481 : : // sorted by fee rate with ancestors
# 482 : : boost::multi_index::ordered_non_unique<
# 483 : : boost::multi_index::tag<ancestor_score>,
# 484 : : boost::multi_index::identity<CTxMemPoolEntry>,
# 485 : : CompareTxMemPoolEntryByAncestorFee
# 486 : : >
# 487 : : >
# 488 : : > indexed_transaction_set;
# 489 : :
# 490 : : /**
# 491 : : * This mutex needs to be locked when accessing `mapTx` or other members
# 492 : : * that are guarded by it.
# 493 : : *
# 494 : : * @par Consistency guarantees
# 495 : : *
# 496 : : * By design, it is guaranteed that:
# 497 : : *
# 498 : : * 1. Locking both `cs_main` and `mempool.cs` will give a view of mempool
# 499 : : * that is consistent with current chain tip (`ActiveChain()` and
# 500 : : * `CoinsTip()`) and is fully populated. Fully populated means that if the
# 501 : : * current active chain is missing transactions that were present in a
# 502 : : * previously active chain, all the missing transactions will have been
# 503 : : * re-added to the mempool and should be present if they meet size and
# 504 : : * consistency constraints.
# 505 : : *
# 506 : : * 2. Locking `mempool.cs` without `cs_main` will give a view of a mempool
# 507 : : * consistent with some chain that was active since `cs_main` was last
# 508 : : * locked, and that is fully populated as described above. It is ok for
# 509 : : * code that only needs to query or remove transactions from the mempool
# 510 : : * to lock just `mempool.cs` without `cs_main`.
# 511 : : *
# 512 : : * To provide these guarantees, it is necessary to lock both `cs_main` and
# 513 : : * `mempool.cs` whenever adding transactions to the mempool and whenever
# 514 : : * changing the chain tip. It's necessary to keep both mutexes locked until
# 515 : : * the mempool is consistent with the new chain tip and fully populated.
# 516 : : */
# 517 : : mutable RecursiveMutex cs;
# 518 : : indexed_transaction_set mapTx GUARDED_BY(cs);
# 519 : :
# 520 : : using txiter = indexed_transaction_set::nth_index<0>::type::const_iterator;
# 521 : : std::vector<std::pair<uint256, txiter>> vTxHashes GUARDED_BY(cs); //!< All tx witness hashes/entries in mapTx, in random order
# 522 : :
# 523 : : typedef std::set<txiter, CompareIteratorByHash> setEntries;
# 524 : :
# 525 : : uint64_t CalculateDescendantMaximum(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs);
# 526 : : private:
# 527 : : typedef std::map<txiter, setEntries, CompareIteratorByHash> cacheMap;
# 528 : :
# 529 : :
# 530 : : void UpdateParent(txiter entry, txiter parent, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs);
# 531 : : void UpdateChild(txiter entry, txiter child, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs);
# 532 : :
# 533 : : std::vector<indexed_transaction_set::const_iterator> GetSortedDepthAndScore() const EXCLUSIVE_LOCKS_REQUIRED(cs);
# 534 : :
# 535 : : /**
# 536 : : * Track locally submitted transactions to periodically retry initial broadcast.
# 537 : : */
# 538 : : std::set<uint256> m_unbroadcast_txids GUARDED_BY(cs);
# 539 : :
# 540 : :
# 541 : : /**
# 542 : : * Helper function to calculate all in-mempool ancestors of staged_ancestors and apply ancestor
# 543 : : * and descendant limits (including staged_ancestors thsemselves, entry_size and entry_count).
# 544 : : * param@[in] entry_size Virtual size to include in the limits.
# 545 : : * param@[in] entry_count How many entries to include in the limits.
# 546 : : * param@[in] staged_ancestors Should contain entries in the mempool.
# 547 : : * param@[out] setAncestors Will be populated with all mempool ancestors.
# 548 : : */
# 549 : : bool CalculateAncestorsAndCheckLimits(size_t entry_size,
# 550 : : size_t entry_count,
# 551 : : setEntries& setAncestors,
# 552 : : CTxMemPoolEntry::Parents &staged_ancestors,
# 553 : : uint64_t limitAncestorCount,
# 554 : : uint64_t limitAncestorSize,
# 555 : : uint64_t limitDescendantCount,
# 556 : : uint64_t limitDescendantSize,
# 557 : : std::string &errString) const EXCLUSIVE_LOCKS_REQUIRED(cs);
# 558 : :
# 559 : : public:
# 560 : : indirectmap<COutPoint, const CTransaction*> mapNextTx GUARDED_BY(cs);
# 561 : : std::map<uint256, CAmount> mapDeltas GUARDED_BY(cs);
# 562 : :
# 563 : : /** Create a new CTxMemPool.
# 564 : : * Sanity checks will be off by default for performance, because otherwise
# 565 : : * accepting transactions becomes O(N^2) where N is the number of transactions
# 566 : : * in the pool.
# 567 : : *
# 568 : : * @param[in] estimator is used to estimate appropriate transaction fees.
# 569 : : * @param[in] check_ratio is the ratio used to determine how often sanity checks will run.
# 570 : : */
# 571 : : explicit CTxMemPool(CBlockPolicyEstimator* estimator = nullptr, int check_ratio = 0);
# 572 : :
# 573 : : /**
# 574 : : * If sanity-checking is turned on, check makes sure the pool is
# 575 : : * consistent (does not contain two transactions that spend the same inputs,
# 576 : : * all inputs are in the mapNextTx array). If sanity-checking is turned off,
# 577 : : * check does nothing.
# 578 : : */
# 579 : : void check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
# 580 : :
# 581 : : // addUnchecked must updated state for all ancestors of a given transaction,
# 582 : : // to track size/count of descendant transactions. First version of
# 583 : : // addUnchecked can be used to have it call CalculateMemPoolAncestors(), and
# 584 : : // then invoke the second version.
# 585 : : // Note that addUnchecked is ONLY called from ATMP outside of tests
# 586 : : // and any other callers may break wallet's in-mempool tracking (due to
# 587 : : // lack of CValidationInterface::TransactionAddedToMempool callbacks).
# 588 : : void addUnchecked(const CTxMemPoolEntry& entry, bool validFeeEstimate = true) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);
# 589 : : void addUnchecked(const CTxMemPoolEntry& entry, setEntries& setAncestors, bool validFeeEstimate = true) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);
# 590 : :
# 591 : : void removeRecursive(const CTransaction& tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
# 592 : : /** After reorg, filter the entries that would no longer be valid in the next block, and update
# 593 : : * the entries' cached LockPoints if needed. The mempool does not have any knowledge of
# 594 : : * consensus rules. It just appplies the callable function and removes the ones for which it
# 595 : : * returns true.
# 596 : : * @param[in] filter_final_and_mature Predicate that checks the relevant validation rules
# 597 : : * and updates an entry's LockPoints.
# 598 : : * */
# 599 : : void removeForReorg(CChain& chain, std::function<bool(txiter)> filter_final_and_mature) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);
# 600 : : void removeConflicts(const CTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(cs);
# 601 : : void removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs);
# 602 : :
# 603 : : void clear();
# 604 : : void _clear() EXCLUSIVE_LOCKS_REQUIRED(cs); //lock free
# 605 : : bool CompareDepthAndScore(const uint256& hasha, const uint256& hashb, bool wtxid=false);
# 606 : : void queryHashes(std::vector<uint256>& vtxid) const;
# 607 : : bool isSpent(const COutPoint& outpoint) const;
# 608 : : unsigned int GetTransactionsUpdated() const;
# 609 : : void AddTransactionsUpdated(unsigned int n);
# 610 : : /**
# 611 : : * Check that none of this transactions inputs are in the mempool, and thus
# 612 : : * the tx is not dependent on other mempool transactions to be included in a block.
# 613 : : */
# 614 : : bool HasNoInputsOf(const CTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs);
# 615 : :
# 616 : : /** Affect CreateNewBlock prioritisation of transactions */
# 617 : : void PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta);
# 618 : : void ApplyDelta(const uint256& hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs);
# 619 : : void ClearPrioritisation(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs);
# 620 : :
# 621 : : /** Get the transaction in the pool that spends the same prevout */
# 622 : : const CTransaction* GetConflictTx(const COutPoint& prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs);
# 623 : :
# 624 : : /** Returns an iterator to the given hash, if found */
# 625 : : std::optional<txiter> GetIter(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs);
# 626 : :
# 627 : : /** Translate a set of hashes into a set of pool iterators to avoid repeated lookups */
# 628 : : setEntries GetIterSet(const std::set<uint256>& hashes) const EXCLUSIVE_LOCKS_REQUIRED(cs);
# 629 : :
# 630 : : /** Remove a set of transactions from the mempool.
# 631 : : * If a transaction is in this set, then all in-mempool descendants must
# 632 : : * also be in the set, unless this transaction is being removed for being
# 633 : : * in a block.
# 634 : : * Set updateDescendants to true when removing a tx that was in a block, so
# 635 : : * that any in-mempool descendants have their ancestor state updated.
# 636 : : */
# 637 : : void RemoveStaged(setEntries& stage, bool updateDescendants, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
# 638 : :
# 639 : : /** UpdateTransactionsFromBlock is called when adding transactions from a
# 640 : : * disconnected block back to the mempool, new mempool entries may have
# 641 : : * children in the mempool (which is generally not the case when otherwise
# 642 : : * adding transactions).
# 643 : : * @post updated descendant state for descendants of each transaction in
# 644 : : * vHashesToUpdate (excluding any child transactions present in
# 645 : : * vHashesToUpdate, which are already accounted for). Updated state
# 646 : : * includes add fee/size information for such descendants to the
# 647 : : * parent and updated ancestor state to include the parent.
# 648 : : *
# 649 : : * @param[in] vHashesToUpdate The set of txids from the
# 650 : : * disconnected block that have been accepted back into the mempool.
# 651 : : * @param[in] ancestor_size_limit The maximum allowed size in virtual
# 652 : : * bytes of an entry and its ancestors
# 653 : : * @param[in] ancestor_count_limit The maximum allowed number of
# 654 : : * transactions including the entry and its ancestors.
# 655 : : */
# 656 : : void UpdateTransactionsFromBlock(const std::vector<uint256>& vHashesToUpdate,
# 657 : : uint64_t ancestor_size_limit, uint64_t ancestor_count_limit) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main) LOCKS_EXCLUDED(m_epoch);
# 658 : :
# 659 : : /** Try to calculate all in-mempool ancestors of entry.
# 660 : : * (these are all calculated including the tx itself)
# 661 : : * limitAncestorCount = max number of ancestors
# 662 : : * limitAncestorSize = max size of ancestors
# 663 : : * limitDescendantCount = max number of descendants any ancestor can have
# 664 : : * limitDescendantSize = max size of descendants any ancestor can have
# 665 : : * errString = populated with error reason if any limits are hit
# 666 : : * fSearchForParents = whether to search a tx's vin for in-mempool parents, or
# 667 : : * look up parents from mapLinks. Must be true for entries not in the mempool
# 668 : : */
# 669 : : 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);
# 670 : :
# 671 : : /** Calculate all in-mempool ancestors of a set of transactions not already in the mempool and
# 672 : : * check ancestor and descendant limits. Heuristics are used to estimate the ancestor and
# 673 : : * descendant count of all entries if the package were to be added to the mempool. The limits
# 674 : : * are applied to the union of all package transactions. For example, if the package has 3
# 675 : : * transactions and limitAncestorCount = 25, the union of all 3 sets of ancestors (including the
# 676 : : * transactions themselves) must be <= 22.
# 677 : : * @param[in] package Transaction package being evaluated for acceptance
# 678 : : * to mempool. The transactions need not be direct
# 679 : : * ancestors/descendants of each other.
# 680 : : * @param[in] limitAncestorCount Max number of txns including ancestors.
# 681 : : * @param[in] limitAncestorSize Max virtual size including ancestors.
# 682 : : * @param[in] limitDescendantCount Max number of txns including descendants.
# 683 : : * @param[in] limitDescendantSize Max virtual size including descendants.
# 684 : : * @param[out] errString Populated with error reason if a limit is hit.
# 685 : : */
# 686 : : bool CheckPackageLimits(const Package& package,
# 687 : : uint64_t limitAncestorCount,
# 688 : : uint64_t limitAncestorSize,
# 689 : : uint64_t limitDescendantCount,
# 690 : : uint64_t limitDescendantSize,
# 691 : : std::string &errString) const EXCLUSIVE_LOCKS_REQUIRED(cs);
# 692 : :
# 693 : : /** Populate setDescendants with all in-mempool descendants of hash.
# 694 : : * Assumes that setDescendants includes all in-mempool descendants of anything
# 695 : : * already in it. */
# 696 : : void CalculateDescendants(txiter it, setEntries& setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs);
# 697 : :
# 698 : : /** The minimum fee to get into the mempool, which may itself not be enough
# 699 : : * for larger-sized transactions.
# 700 : : * The incrementalRelayFee policy variable is used to bound the time it
# 701 : : * takes the fee rate to go back down all the way to 0. When the feerate
# 702 : : * would otherwise be half of this, it is set to 0 instead.
# 703 : : */
# 704 : : CFeeRate GetMinFee(size_t sizelimit) const;
# 705 : :
# 706 : : /** Remove transactions from the mempool until its dynamic size is <= sizelimit.
# 707 : : * pvNoSpendsRemaining, if set, will be populated with the list of outpoints
# 708 : : * which are not in mempool which no longer have any spends in this mempool.
# 709 : : */
# 710 : : void TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs);
# 711 : :
# 712 : : /** Expire all transaction (and their dependencies) in the mempool older than time. Return the number of removed transactions. */
# 713 : : int Expire(std::chrono::seconds time) EXCLUSIVE_LOCKS_REQUIRED(cs);
# 714 : :
# 715 : : /**
# 716 : : * Calculate the ancestor and descendant count for the given transaction.
# 717 : : * The counts include the transaction itself.
# 718 : : * When ancestors is non-zero (ie, the transaction itself is in the mempool),
# 719 : : * ancestorsize and ancestorfees will also be set to the appropriate values.
# 720 : : */
# 721 : : void GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize = nullptr, CAmount* ancestorfees = nullptr) const;
# 722 : :
# 723 : : /** @returns true if the mempool is fully loaded */
# 724 : : bool IsLoaded() const;
# 725 : :
# 726 : : /** Sets the current loaded state */
# 727 : : void SetIsLoaded(bool loaded);
# 728 : :
# 729 : : unsigned long size() const
# 730 : 11265 : {
# 731 : 11265 : LOCK(cs);
# 732 : 11265 : return mapTx.size();
# 733 : 11265 : }
# 734 : :
# 735 : : uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs)
# 736 : 910 : {
# 737 : 910 : AssertLockHeld(cs);
# 738 : 910 : return totalTxSize;
# 739 : 910 : }
# 740 : :
# 741 : : CAmount GetTotalFee() const EXCLUSIVE_LOCKS_REQUIRED(cs)
# 742 : 910 : {
# 743 : 910 : AssertLockHeld(cs);
# 744 : 910 : return m_total_fee;
# 745 : 910 : }
# 746 : :
# 747 : : bool exists(const GenTxid& gtxid) const
# 748 : 230554 : {
# 749 : 230554 : LOCK(cs);
# 750 [ + + ]: 230554 : if (gtxid.IsWtxid()) {
# 751 : 92181 : return (mapTx.get<index_by_wtxid>().count(gtxid.GetHash()) != 0);
# 752 : 92181 : }
# 753 : 138373 : return (mapTx.count(gtxid.GetHash()) != 0);
# 754 : 230554 : }
# 755 : :
# 756 : : CTransactionRef get(const uint256& hash) const;
# 757 : : txiter get_iter_from_wtxid(const uint256& wtxid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
# 758 : 127863 : {
# 759 : 127863 : AssertLockHeld(cs);
# 760 : 127863 : return mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid));
# 761 : 127863 : }
# 762 : : TxMempoolInfo info(const GenTxid& gtxid) const;
# 763 : : std::vector<TxMempoolInfo> infoAll() const;
# 764 : :
# 765 : : size_t DynamicMemoryUsage() const;
# 766 : :
# 767 : : /** Adds a transaction to the unbroadcast set */
# 768 : : void AddUnbroadcastTx(const uint256& txid)
# 769 : 9305 : {
# 770 : 9305 : LOCK(cs);
# 771 : : // Sanity check the transaction is in the mempool & insert into
# 772 : : // unbroadcast set.
# 773 [ + - ]: 9305 : if (exists(GenTxid::Txid(txid))) m_unbroadcast_txids.insert(txid);
# 774 : 9305 : };
# 775 : :
# 776 : : /** Removes a transaction from the unbroadcast set */
# 777 : : void RemoveUnbroadcastTx(const uint256& txid, const bool unchecked = false);
# 778 : :
# 779 : : /** Returns transactions in unbroadcast set */
# 780 : : std::set<uint256> GetUnbroadcastTxs() const
# 781 : 1630 : {
# 782 : 1630 : LOCK(cs);
# 783 : 1630 : return m_unbroadcast_txids;
# 784 : 1630 : }
# 785 : :
# 786 : : /** Returns whether a txid is in the unbroadcast set */
# 787 : : bool IsUnbroadcastTx(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
# 788 : 1346 : {
# 789 : 1346 : AssertLockHeld(cs);
# 790 : 1346 : return m_unbroadcast_txids.count(txid) != 0;
# 791 : 1346 : }
# 792 : :
# 793 : : /** Guards this internal counter for external reporting */
# 794 : 88539 : uint64_t GetAndIncrementSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs) {
# 795 : 88539 : return m_sequence_number++;
# 796 : 88539 : }
# 797 : :
# 798 : 8983 : uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs) {
# 799 : 8983 : return m_sequence_number;
# 800 : 8983 : }
# 801 : :
# 802 : : private:
# 803 : : /** UpdateForDescendants is used by UpdateTransactionsFromBlock to update
# 804 : : * the descendants for a single transaction that has been added to the
# 805 : : * mempool but may have child transactions in the mempool, eg during a
# 806 : : * chain reorg.
# 807 : : *
# 808 : : * @pre CTxMemPool::m_children is correct for the given tx and all
# 809 : : * descendants.
# 810 : : * @pre cachedDescendants is an accurate cache where each entry has all
# 811 : : * descendants of the corresponding key, including those that should
# 812 : : * be removed for violation of ancestor limits.
# 813 : : * @post if updateIt has any non-excluded descendants, cachedDescendants has
# 814 : : * a new cache line for updateIt.
# 815 : : * @post descendants_to_remove has a new entry for any descendant which exceeded
# 816 : : * ancestor limits relative to updateIt.
# 817 : : *
# 818 : : * @param[in] updateIt the entry to update for its descendants
# 819 : : * @param[in,out] cachedDescendants a cache where each line corresponds to all
# 820 : : * descendants. It will be updated with the descendants of the transaction
# 821 : : * being updated, so that future invocations don't need to walk the same
# 822 : : * transaction again, if encountered in another transaction chain.
# 823 : : * @param[in] setExclude the set of descendant transactions in the mempool
# 824 : : * that must not be accounted for (because any descendants in setExclude
# 825 : : * were added to the mempool after the transaction being updated and hence
# 826 : : * their state is already reflected in the parent state).
# 827 : : * @param[out] descendants_to_remove Populated with the txids of entries that
# 828 : : * exceed ancestor limits. It's the responsibility of the caller to
# 829 : : * removeRecursive them.
# 830 : : * @param[in] ancestor_size_limit the max number of ancestral bytes allowed
# 831 : : * for any descendant
# 832 : : * @param[in] ancestor_count_limit the max number of ancestor transactions
# 833 : : * allowed for any descendant
# 834 : : */
# 835 : : void UpdateForDescendants(txiter updateIt, cacheMap& cachedDescendants,
# 836 : : const std::set<uint256>& setExclude, std::set<uint256>& descendants_to_remove,
# 837 : : uint64_t ancestor_size_limit, uint64_t ancestor_count_limit) EXCLUSIVE_LOCKS_REQUIRED(cs);
# 838 : : /** Update ancestors of hash to add/remove it as a descendant transaction. */
# 839 : : void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs);
# 840 : : /** Set ancestor state for an entry */
# 841 : : void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs);
# 842 : : /** For each transaction being removed, update ancestors and any direct children.
# 843 : : * If updateDescendants is true, then also update in-mempool descendants'
# 844 : : * ancestor state. */
# 845 : : void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants) EXCLUSIVE_LOCKS_REQUIRED(cs);
# 846 : : /** Sever link between specified transaction and direct children. */
# 847 : : void UpdateChildrenForRemoval(txiter entry) EXCLUSIVE_LOCKS_REQUIRED(cs);
# 848 : :
# 849 : : /** Before calling removeUnchecked for a given transaction,
# 850 : : * UpdateForRemoveFromMempool must be called on the entire (dependent) set
# 851 : : * of transactions being removed at the same time. We use each
# 852 : : * CTxMemPoolEntry's setMemPoolParents in order to walk ancestors of a
# 853 : : * given transaction that is removed, so we can't remove intermediate
# 854 : : * transactions in a chain before we've updated all the state for the
# 855 : : * removal.
# 856 : : */
# 857 : : void removeUnchecked(txiter entry, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
# 858 : : public:
# 859 : : /** visited marks a CTxMemPoolEntry as having been traversed
# 860 : : * during the lifetime of the most recently created Epoch::Guard
# 861 : : * and returns false if we are the first visitor, true otherwise.
# 862 : : *
# 863 : : * An Epoch::Guard must be held when visited is called or an assert will be
# 864 : : * triggered.
# 865 : : *
# 866 : : */
# 867 : : bool visited(const txiter it) const EXCLUSIVE_LOCKS_REQUIRED(cs, m_epoch)
# 868 : 4733 : {
# 869 : 4733 : return m_epoch.visited(it->m_epoch_marker);
# 870 : 4733 : }
# 871 : :
# 872 : : bool visited(std::optional<txiter> it) const EXCLUSIVE_LOCKS_REQUIRED(cs, m_epoch)
# 873 : 0 : {
# 874 : 0 : assert(m_epoch.guarded()); // verify guard even when it==nullopt
# 875 : 0 : return !it || visited(*it);
# 876 : 0 : }
# 877 : : };
# 878 : :
# 879 : : /**
# 880 : : * CCoinsView that brings transactions from a mempool into view.
# 881 : : * It does not check for spendings by memory pool transactions.
# 882 : : * Instead, it provides access to all Coins which are either unspent in the
# 883 : : * base CCoinsView, are outputs from any mempool transaction, or are
# 884 : : * tracked temporarily to allow transaction dependencies in package validation.
# 885 : : * This allows transaction replacement to work as expected, as you want to
# 886 : : * have all inputs "available" to check signatures, and any cycles in the
# 887 : : * dependency graph are checked directly in AcceptToMemoryPool.
# 888 : : * It also allows you to sign a double-spend directly in
# 889 : : * signrawtransactionwithkey and signrawtransactionwithwallet,
# 890 : : * as long as the conflicting transaction is not yet confirmed.
# 891 : : */
# 892 : : class CCoinsViewMemPool : public CCoinsViewBacked
# 893 : : {
# 894 : : /**
# 895 : : * Coins made available by transactions being validated. Tracking these allows for package
# 896 : : * validation, since we can access transaction outputs without submitting them to mempool.
# 897 : : */
# 898 : : std::unordered_map<COutPoint, Coin, SaltedOutpointHasher> m_temp_added;
# 899 : : protected:
# 900 : : const CTxMemPool& mempool;
# 901 : :
# 902 : : public:
# 903 : : CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn);
# 904 : : bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
# 905 : : /** Add the coins created by this transaction. These coins are only temporarily stored in
# 906 : : * m_temp_added and cannot be flushed to the back end. Only used for package validation. */
# 907 : : void PackageAddTransaction(const CTransactionRef& tx);
# 908 : : };
# 909 : :
# 910 : : /**
# 911 : : * DisconnectedBlockTransactions
# 912 : :
# 913 : : * During the reorg, it's desirable to re-add previously confirmed transactions
# 914 : : * to the mempool, so that anything not re-confirmed in the new chain is
# 915 : : * available to be mined. However, it's more efficient to wait until the reorg
# 916 : : * is complete and process all still-unconfirmed transactions at that time,
# 917 : : * since we expect most confirmed transactions to (typically) still be
# 918 : : * confirmed in the new chain, and re-accepting to the memory pool is expensive
# 919 : : * (and therefore better to not do in the middle of reorg-processing).
# 920 : : * Instead, store the disconnected transactions (in order!) as we go, remove any
# 921 : : * that are included in blocks in the new chain, and then process the remaining
# 922 : : * still-unconfirmed transactions at the end.
# 923 : : */
# 924 : :
# 925 : : // multi_index tag names
# 926 : : struct txid_index {};
# 927 : : struct insertion_order {};
# 928 : :
# 929 : : struct DisconnectedBlockTransactions {
# 930 : : typedef boost::multi_index_container<
# 931 : : CTransactionRef,
# 932 : : boost::multi_index::indexed_by<
# 933 : : // sorted by txid
# 934 : : boost::multi_index::hashed_unique<
# 935 : : boost::multi_index::tag<txid_index>,
# 936 : : mempoolentry_txid,
# 937 : : SaltedTxidHasher
# 938 : : >,
# 939 : : // sorted by order in the blockchain
# 940 : : boost::multi_index::sequenced<
# 941 : : boost::multi_index::tag<insertion_order>
# 942 : : >
# 943 : : >
# 944 : : > indexed_disconnected_transactions;
# 945 : :
# 946 : : // It's almost certainly a logic bug if we don't clear out queuedTx before
# 947 : : // destruction, as we add to it while disconnecting blocks, and then we
# 948 : : // need to re-process remaining transactions to ensure mempool consistency.
# 949 : : // For now, assert() that we've emptied out this object on destruction.
# 950 : : // This assert() can always be removed if the reorg-processing code were
# 951 : : // to be refactored such that this assumption is no longer true (for
# 952 : : // instance if there was some other way we cleaned up the mempool after a
# 953 : : // reorg, besides draining this object).
# 954 : 63964 : ~DisconnectedBlockTransactions() { assert(queuedTx.empty()); }
# 955 : :
# 956 : : indexed_disconnected_transactions queuedTx;
# 957 : : uint64_t cachedInnerUsage = 0;
# 958 : :
# 959 : : // Estimate the overhead of queuedTx to be 6 pointers + an allocation, as
# 960 : : // no exact formula for boost::multi_index_contained is implemented.
# 961 : 7078 : size_t DynamicMemoryUsage() const {
# 962 : 7078 : return memusage::MallocUsage(sizeof(CTransactionRef) + 6 * sizeof(void*)) * queuedTx.size() + cachedInnerUsage;
# 963 : 7078 : }
# 964 : :
# 965 : : void addTransaction(const CTransactionRef& tx)
# 966 : 10064 : {
# 967 : 10064 : queuedTx.insert(tx);
# 968 : 10064 : cachedInnerUsage += RecursiveDynamicUsage(tx);
# 969 : 10064 : }
# 970 : :
# 971 : : // Remove entries based on txid_index, and update memory usage.
# 972 : : void removeForBlock(const std::vector<CTransactionRef>& vtx)
# 973 : 61823 : {
# 974 : : // Short-circuit in the common case of a block being added to the tip
# 975 [ + + ]: 61823 : if (queuedTx.empty()) {
# 976 : 58843 : return;
# 977 : 58843 : }
# 978 [ + + ]: 5233 : for (auto const &tx : vtx) {
# 979 : 5233 : auto it = queuedTx.find(tx->GetHash());
# 980 [ + + ]: 5233 : if (it != queuedTx.end()) {
# 981 : 194 : cachedInnerUsage -= RecursiveDynamicUsage(*it);
# 982 : 194 : queuedTx.erase(it);
# 983 : 194 : }
# 984 : 5233 : }
# 985 : 2980 : }
# 986 : :
# 987 : : // Remove an entry by insertion_order index, and update memory usage.
# 988 : : void removeEntry(indexed_disconnected_transactions::index<insertion_order>::type::iterator entry)
# 989 : 3205 : {
# 990 : 3205 : cachedInnerUsage -= RecursiveDynamicUsage(*entry);
# 991 : 3205 : queuedTx.get<insertion_order>().erase(entry);
# 992 : 3205 : }
# 993 : :
# 994 : : void clear()
# 995 : 0 : {
# 996 : 0 : cachedInnerUsage = 0;
# 997 : 0 : queuedTx.clear();
# 998 : 0 : }
# 999 : : };
# 1000 : :
# 1001 : : #endif // BITCOIN_TXMEMPOOL_H
|