LCOV - code coverage report
Current view: top level - src/test/util - txmempool.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 59.4 % 133 79
Test Date: 2025-10-25 04:38:23 Functions: 75.0 % 8 6
Branches: 32.6 % 282 92

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2022 The Bitcoin Core developers
       2                 :             : // Distributed under the MIT software license, see the accompanying
       3                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :             : 
       5                 :             : #include <test/util/txmempool.h>
       6                 :             : 
       7                 :             : #include <chainparams.h>
       8                 :             : #include <node/context.h>
       9                 :             : #include <node/mempool_args.h>
      10                 :             : #include <policy/rbf.h>
      11                 :             : #include <policy/truc_policy.h>
      12                 :             : #include <txmempool.h>
      13                 :             : #include <test/util/transaction_utils.h>
      14                 :             : #include <util/check.h>
      15                 :             : #include <util/time.h>
      16                 :             : #include <util/translation.h>
      17                 :             : #include <validation.h>
      18                 :             : 
      19                 :             : using node::NodeContext;
      20                 :             : 
      21                 :         190 : CTxMemPool::Options MemPoolOptionsForTest(const NodeContext& node)
      22                 :             : {
      23                 :         190 :     CTxMemPool::Options mempool_opts{
      24                 :             :         // Default to always checking mempool regardless of
      25                 :             :         // chainparams.DefaultConsistencyChecks for tests
      26                 :             :         .check_ratio = 1,
      27                 :         190 :         .signals = node.validation_signals.get(),
      28                 :         190 :     };
      29                 :         190 :     const auto result{ApplyArgsManOptions(*node.args, ::Params(), mempool_opts)};
      30         [ +  - ]:         190 :     Assert(result);
      31                 :         190 :     return mempool_opts;
      32                 :         190 : }
      33                 :             : 
      34                 :       26804 : CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CMutableTransaction& tx) const
      35                 :             : {
      36         [ +  - ]:       53608 :     return FromTx(MakeTransactionRef(tx));
      37                 :             : }
      38                 :             : 
      39                 :       27595 : CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CTransactionRef& tx) const
      40                 :             : {
      41                 :       27595 :     return CTxMemPoolEntry{tx, nFee, TicksSinceEpoch<std::chrono::seconds>(time), nHeight, m_sequence, spendsCoinbase, sigOpCost, lp};
      42                 :             : }
      43                 :             : 
      44                 :          27 : std::optional<std::string> CheckPackageMempoolAcceptResult(const Package& txns,
      45                 :             :                                                            const PackageMempoolAcceptResult& result,
      46                 :             :                                                            bool expect_valid,
      47                 :             :                                                            const CTxMemPool* mempool)
      48                 :             : {
      49         [ +  + ]:          27 :     if (expect_valid) {
      50         [ -  + ]:          19 :         if (result.m_state.IsInvalid()) {
      51         [ #  # ]:           0 :             return strprintf("Package validation unexpectedly failed: %s", result.m_state.ToString());
      52                 :             :         }
      53                 :             :     } else {
      54         [ -  + ]:           8 :         if (result.m_state.IsValid()) {
      55         [ #  # ]:           0 :             return strprintf("Package validation unexpectedly succeeded. %s", result.m_state.ToString());
      56                 :             :         }
      57                 :             :     }
      58   [ +  +  -  + ]:          53 :     if (result.m_state.GetResult() != PackageValidationResult::PCKG_POLICY && txns.size() != result.m_tx_results.size()) {
      59         [ #  # ]:           0 :         return strprintf("txns size %u does not match tx results size %u", txns.size(), result.m_tx_results.size());
      60                 :             :     }
      61         [ +  + ]:          78 :     for (const auto& tx : txns) {
      62                 :          51 :         const auto& wtxid = tx->GetWitnessHash();
      63         [ -  + ]:          51 :         if (result.m_tx_results.count(wtxid) == 0) {
      64         [ #  # ]:           0 :             return strprintf("result not found for tx %s", wtxid.ToString());
      65                 :             :         }
      66                 :             : 
      67                 :          51 :         const auto& atmp_result = result.m_tx_results.at(wtxid);
      68                 :          51 :         const bool valid{atmp_result.m_result_type == MempoolAcceptResult::ResultType::VALID};
      69   [ +  +  +  - ]:          51 :         if (expect_valid && atmp_result.m_state.IsInvalid()) {
      70   [ #  #  #  # ]:           0 :             return strprintf("tx %s unexpectedly failed: %s", wtxid.ToString(), atmp_result.m_state.ToString());
      71                 :             :         }
      72                 :             : 
      73                 :             :         // Each subpackage is allowed MAX_REPLACEMENT_CANDIDATES replacements (only checking individually here)
      74         [ -  + ]:          51 :         if (atmp_result.m_replaced_transactions.size() > MAX_REPLACEMENT_CANDIDATES) {
      75                 :           0 :             return strprintf("tx %s result replaced too many transactions",
      76         [ #  # ]:           0 :                                 wtxid.ToString());
      77                 :             :         }
      78                 :             : 
      79                 :             :         // Replacements can't happen for subpackages larger than 2
      80   [ +  +  +  - ]:          51 :         if (!atmp_result.m_replaced_transactions.empty() &&
      81   [ +  +  +  -  :          51 :             atmp_result.m_wtxids_fee_calculations.has_value() && atmp_result.m_wtxids_fee_calculations.value().size() > 2) {
             -  +  +  - ]
      82                 :           0 :              return strprintf("tx %s was part of a too-large package RBF subpackage",
      83         [ #  # ]:           0 :                                 wtxid.ToString());
      84                 :             :         }
      85                 :             : 
      86   [ +  +  +  - ]:          51 :         if (!atmp_result.m_replaced_transactions.empty() && mempool) {
      87                 :           4 :             LOCK(mempool->cs);
      88                 :             :             // If replacements occurred and it used 2 transactions, this is a package RBF and should result in a cluster of size 2
      89   [ +  -  -  +  :           4 :             if (atmp_result.m_wtxids_fee_calculations.has_value() && atmp_result.m_wtxids_fee_calculations.value().size() == 2) {
                   +  + ]
      90   [ +  -  +  -  :           4 :                 const auto cluster = mempool->GatherClusters({tx->GetHash()});
                   -  + ]
      91   [ -  +  -  +  :           2 :                 if (cluster.size() != 2) return strprintf("tx %s has too many ancestors or descendants for a package rbf", wtxid.ToString());
             -  -  -  - ]
      92         [ -  - ]:           2 :             }
      93                 :           4 :         }
      94                 :             : 
      95                 :             :         // m_vsize and m_base_fees should exist iff the result was VALID or MEMPOOL_ENTRY
      96                 :          51 :         const bool mempool_entry{atmp_result.m_result_type == MempoolAcceptResult::ResultType::MEMPOOL_ENTRY};
      97         [ -  + ]:          51 :         if (atmp_result.m_base_fees.has_value() != (valid || mempool_entry)) {
      98   [ #  #  #  # ]:           0 :             return strprintf("tx %s result should %shave m_base_fees", wtxid.ToString(), valid || mempool_entry ? "" : "not ");
      99                 :             :         }
     100         [ -  + ]:          51 :         if (atmp_result.m_vsize.has_value() != (valid || mempool_entry)) {
     101   [ #  #  #  # ]:           0 :             return strprintf("tx %s result should %shave m_vsize", wtxid.ToString(), valid || mempool_entry ? "" : "not ");
     102                 :             :         }
     103                 :             : 
     104                 :             :         // m_other_wtxid should exist iff the result was DIFFERENT_WITNESS
     105                 :          51 :         const bool diff_witness{atmp_result.m_result_type == MempoolAcceptResult::ResultType::DIFFERENT_WITNESS};
     106         [ -  + ]:          51 :         if (atmp_result.m_other_wtxid.has_value() != diff_witness) {
     107   [ #  #  #  # ]:           0 :             return strprintf("tx %s result should %shave m_other_wtxid", wtxid.ToString(), diff_witness ? "" : "not ");
     108                 :             :         }
     109                 :             : 
     110                 :             :         // m_effective_feerate and m_wtxids_fee_calculations should exist iff the result was valid
     111                 :             :         // or if the failure was TX_RECONSIDERABLE
     112   [ +  +  +  + ]:          51 :         const bool valid_or_reconsiderable{atmp_result.m_result_type == MempoolAcceptResult::ResultType::VALID ||
     113         [ +  + ]:          23 :                     atmp_result.m_state.GetResult() == TxValidationResult::TX_RECONSIDERABLE};
     114         [ -  + ]:          51 :         if (atmp_result.m_effective_feerate.has_value() != valid_or_reconsiderable) {
     115                 :           0 :             return strprintf("tx %s result should %shave m_effective_feerate",
     116   [ #  #  #  # ]:           0 :                                     wtxid.ToString(), valid ? "" : "not ");
     117                 :             :         }
     118         [ -  + ]:          51 :         if (atmp_result.m_wtxids_fee_calculations.has_value() != valid_or_reconsiderable) {
     119                 :           0 :             return strprintf("tx %s result should %shave m_effective_feerate",
     120   [ #  #  #  # ]:           0 :                                     wtxid.ToString(), valid ? "" : "not ");
     121                 :             :         }
     122                 :             : 
     123         [ +  + ]:          51 :         if (mempool) {
     124                 :             :             // The tx by txid should be in the mempool iff the result was not INVALID.
     125                 :          46 :             const bool txid_in_mempool{atmp_result.m_result_type != MempoolAcceptResult::ResultType::INVALID};
     126         [ -  + ]:          46 :             if (mempool->exists(tx->GetHash()) != txid_in_mempool) {
     127   [ #  #  #  # ]:           0 :                 return strprintf("tx %s should %sbe in mempool", wtxid.ToString(), txid_in_mempool ? "" : "not ");
     128                 :             :             }
     129                 :             :             // Additionally, if the result was DIFFERENT_WITNESS, we shouldn't be able to find the tx in mempool by wtxid.
     130   [ +  +  +  + ]:          46 :             if (tx->HasWitness() && atmp_result.m_result_type == MempoolAcceptResult::ResultType::DIFFERENT_WITNESS) {
     131         [ -  + ]:           3 :                 if (mempool->exists(wtxid)) {
     132         [ #  # ]:           0 :                     return strprintf("wtxid %s should not be in mempool", wtxid.ToString());
     133                 :             :                 }
     134                 :             :             }
     135         [ +  + ]:          53 :             for (const auto& tx_ref : atmp_result.m_replaced_transactions) {
     136         [ -  + ]:           7 :                 if (mempool->exists(tx_ref->GetHash())) {
     137         [ #  # ]:           0 :                     return strprintf("tx %s should not be in mempool as it was replaced", tx_ref->GetWitnessHash().ToString());
     138                 :             :                 }
     139                 :             :             }
     140                 :             :         }
     141                 :             :     }
     142                 :          27 :     return std::nullopt;
     143                 :             : }
     144                 :             : 
     145                 :           0 : void CheckMempoolEphemeralInvariants(const CTxMemPool& tx_pool)
     146                 :             : {
     147                 :           0 :     LOCK(tx_pool.cs);
     148   [ #  #  #  # ]:           0 :     for (const auto& tx_info : tx_pool.infoAll()) {
     149   [ #  #  #  # ]:           0 :         const auto& entry = *Assert(tx_pool.GetEntry(tx_info.tx->GetHash()));
     150                 :             : 
     151         [ #  # ]:           0 :         std::vector<uint32_t> dust_indexes = GetDust(*tx_info.tx, tx_pool.m_opts.dust_relay_feerate);
     152                 :             : 
     153   [ #  #  #  # ]:           0 :         Assert(dust_indexes.size() < 2);
     154                 :             : 
     155         [ #  # ]:           0 :         if (dust_indexes.empty()) continue;
     156                 :             : 
     157                 :             :         // Transaction must have no base fee
     158   [ #  #  #  #  :           0 :         Assert(entry.GetFee() == 0 && entry.GetModifiedFee() == 0);
                   #  # ]
     159                 :             : 
     160                 :             :         // Transaction has single dust; make sure it's swept or will not be mined
     161         [ #  # ]:           0 :         const auto& children = entry.GetMemPoolChildrenConst();
     162                 :             : 
     163                 :             :         // Multiple children should never happen as non-dust-spending child
     164                 :             :         // can get mined as package
     165         [ #  # ]:           0 :         Assert(children.size() < 2);
     166                 :             : 
     167         [ #  # ]:           0 :         if (children.empty()) {
     168                 :             :             // No children and no fees; modified fees aside won't get mined so it's fine
     169                 :             :             // Happens naturally if child spend is RBF cycled away.
     170                 :           0 :             continue;
     171                 :             :         }
     172                 :             : 
     173                 :             :         // Only-child should be spending the dust
     174                 :           0 :         const auto& only_child = children.begin()->get().GetTx();
     175                 :           0 :         COutPoint dust_outpoint{tx_info.tx->GetHash(), dust_indexes[0]};
     176   [ #  #  #  # ]:           0 :         Assert(std::any_of(only_child.vin.begin(), only_child.vin.end(), [&dust_outpoint](const CTxIn& txin) {
     177                 :             :             return txin.prevout == dust_outpoint;
     178                 :             :             }));
     179         [ #  # ]:           0 :     }
     180                 :           0 : }
     181                 :             : 
     182                 :           0 : void CheckMempoolTRUCInvariants(const CTxMemPool& tx_pool)
     183                 :             : {
     184                 :           0 :     LOCK(tx_pool.cs);
     185   [ #  #  #  #  :           0 :     for (const auto& tx_info : tx_pool.infoAll()) {
                   #  # ]
     186   [ #  #  #  # ]:           0 :         const auto& entry = *Assert(tx_pool.GetEntry(tx_info.tx->GetHash()));
     187         [ #  # ]:           0 :         if (tx_info.tx->version == TRUC_VERSION) {
     188                 :             :             // Check that special maximum virtual size is respected
     189   [ #  #  #  # ]:           0 :             Assert(entry.GetTxSize() <= TRUC_MAX_VSIZE);
     190                 :             : 
     191                 :             :             // Check that special TRUC ancestor/descendant limits and rules are always respected
     192         [ #  # ]:           0 :             Assert(entry.GetCountWithDescendants() <= TRUC_DESCENDANT_LIMIT);
     193         [ #  # ]:           0 :             Assert(entry.GetCountWithAncestors() <= TRUC_ANCESTOR_LIMIT);
     194         [ #  # ]:           0 :             Assert(entry.GetSizeWithDescendants() <= TRUC_MAX_VSIZE + TRUC_CHILD_MAX_VSIZE);
     195         [ #  # ]:           0 :             Assert(entry.GetSizeWithAncestors() <= TRUC_MAX_VSIZE + TRUC_CHILD_MAX_VSIZE);
     196                 :             : 
     197                 :             :             // If this transaction has at least 1 ancestor, it's a "child" and has restricted weight.
     198         [ #  # ]:           0 :             if (entry.GetCountWithAncestors() > 1) {
     199   [ #  #  #  # ]:           0 :                 Assert(entry.GetTxSize() <= TRUC_CHILD_MAX_VSIZE);
     200                 :             :                 // All TRUC transactions must only have TRUC unconfirmed parents.
     201         [ #  # ]:           0 :                 const auto& parents = entry.GetMemPoolParentsConst();
     202   [ #  #  #  # ]:           0 :                 Assert(parents.begin()->get().GetSharedTx()->version == TRUC_VERSION);
     203                 :             :             }
     204         [ #  # ]:           0 :         } else if (entry.GetCountWithAncestors() > 1) {
     205                 :             :             // All non-TRUC transactions must only have non-TRUC unconfirmed parents.
     206         [ #  # ]:           0 :             for (const auto& parent : entry.GetMemPoolParentsConst()) {
     207   [ #  #  #  # ]:           0 :                 Assert(parent.get().GetSharedTx()->version != TRUC_VERSION);
     208                 :             :             }
     209                 :             :         }
     210                 :             :     }
     211                 :           0 : }
     212                 :             : 
     213                 :       27576 : void AddToMempool(CTxMemPool& tx_pool, const CTxMemPoolEntry& entry)
     214                 :             : {
     215         [ +  - ]:       27576 :     LOCK2(cs_main, tx_pool.cs);
     216         [ +  - ]:       27576 :     auto changeset = tx_pool.GetChangeSet();
     217   [ +  -  +  - ]:       55152 :     changeset->StageAddition(entry.GetSharedTx(), entry.GetFee(),
     218         [ +  - ]:       27576 :             entry.GetTime().count(), entry.GetHeight(), entry.GetSequence(),
     219         [ +  - ]:       27576 :             entry.GetSpendsCoinbase(), entry.GetSigOpCost(), entry.GetLockPoints());
     220         [ +  - ]:       27576 :     changeset->Apply();
     221   [ +  -  +  - ]:       82728 : }
     222                 :             : 
     223                 :           3 : void MockMempoolMinFee(const CFeeRate& target_feerate, CTxMemPool& mempool)
     224                 :             : {
     225         [ +  - ]:           3 :     LOCK2(cs_main, mempool.cs);
     226                 :             :     // Transactions in the mempool will affect the new minimum feerate.
     227   [ +  -  -  + ]:           3 :     assert(mempool.size() == 0);
     228                 :             :     // The target feerate cannot be too low...
     229                 :             :     // ...otherwise the transaction's feerate will need to be negative.
     230         [ -  + ]:           3 :     assert(target_feerate > mempool.m_opts.incremental_relay_feerate);
     231                 :             :     // ...otherwise this is not meaningful. The feerate policy uses the maximum of both feerates.
     232         [ -  + ]:           3 :     assert(target_feerate > mempool.m_opts.min_relay_feerate);
     233                 :             : 
     234                 :             :     // Manually create an invalid transaction. Manually set the fee in the CTxMemPoolEntry to
     235                 :             :     // achieve the exact target feerate.
     236         [ +  - ]:           3 :     CMutableTransaction mtx{};
     237         [ +  - ]:           3 :     mtx.vin.emplace_back(COutPoint{Txid::FromUint256(uint256{123}), 0});
     238   [ +  -  +  -  :           6 :     mtx.vout.emplace_back(1 * COIN, GetScriptForDestination(WitnessV0ScriptHash(CScript() << OP_TRUE)));
             +  -  +  - ]
     239                 :             :     // Set a large size so that the fee evaluated at target_feerate (which is usually in sats/kvB) is an integer.
     240                 :             :     // Otherwise, GetMinFee() may end up slightly different from target_feerate.
     241         [ +  - ]:           3 :     BulkTransaction(mtx, 4000);
     242         [ +  - ]:           3 :     const auto tx{MakeTransactionRef(mtx)};
     243                 :           3 :     LockPoints lp;
     244                 :             :     // The new mempool min feerate is equal to the removed package's feerate + incremental feerate.
     245   [ +  -  +  - ]:           3 :     const auto tx_fee = target_feerate.GetFee(GetVirtualTransactionSize(*tx)) -
     246   [ +  -  +  - ]:           3 :         mempool.m_opts.incremental_relay_feerate.GetFee(GetVirtualTransactionSize(*tx));
     247                 :           3 :     {
     248         [ +  - ]:           3 :         auto changeset = mempool.GetChangeSet();
     249         [ +  - ]:           3 :         changeset->StageAddition(tx, /*fee=*/tx_fee,
     250                 :             :                 /*time=*/0, /*entry_height=*/1, /*entry_sequence=*/0,
     251                 :             :                 /*spends_coinbase=*/true, /*sigops_cost=*/1, lp);
     252         [ +  - ]:           3 :         changeset->Apply();
     253                 :           3 :     }
     254         [ +  - ]:           3 :     mempool.TrimToSize(0);
     255   [ +  -  -  + ]:           3 :     assert(mempool.GetMinFee() == target_feerate);
     256   [ +  -  +  - ]:          12 : }
        

Generated by: LCOV version 2.0-1