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